用户:
13661555450查看:5 回复:4 评论:5 创建时间:2022-10-03T17:15:06
world.onPlayerJoin(({ entity }) => {//每次玩家进入游戏都会运行
loadPlayer(entity)})
world.onPress(({entity})=>{
savePlayer(entity)})
async function savePlayer(entity) {//定义保存玩家状态的函数
if (entity.player.userKey) {//拥有userKey的玩家, 则玩家不是游客, 可以保存
entity.buffer=[]
for(i in entity.player.things){
entity.buffer.push(entity.player.things[i][1])
}
entity.buffer1=[]
for(i in entity.player.things_tool_number){
entity.buffer1.push(entity.player.things_tool_number[i][1])
}showPlayers()
await db.sql`
INSERT INTO player (
username,--玩家名字
things,
things2,
things_second,
things_tool,
things_tool_number,
userKey
)
VALUES(
${entity.player.name},
${JSON.stringify(Object.keys(entity.player.things))},
${JSON.stringify(entity.buffer)},
${JSON.stringify(entity.player.things_second)},
${JSON.stringify(entity.player.things_tool)},
${JSON.stringify(entity.buffer1)},
${entity.player.userKey}
)
ON CONFLICT("userKey")--如果玩家记录已经存在, 则不需要插入, 而是更新各个字段的值
DO UPDATE SET
username=excluded.username,
things=excluded.things,
things2=excluded.things2,
things_second=excluded.things_second,
things_tool=excluded.things_tool,
things_tool_number=excluded.things_tool_number
`
}
}
async function loadPlayer(entity,list) {
const data = (await (db.sql`SELECT * FROM player WHERE userKey=${entity.player.userKey} limit 1`))[0]
if (data) { //如果存在这个玩家的存档
entity.player.things_second=JSON.parse(data.things_second)
entity.player.things_tool=JSON.parse(data.things_tool)
a=JSON.parse(data.things)
b=JSON.parse(data.things2)
entity.player.things={}
for(i in a){
entity.player.things[a[i]]=[list[a[i]],b[i]]
}
c=JSON.parse(data.things_tool_number)
d=JSON.parse(data.things_tool)
entity.player.things_tool_number=[]
for(i in c){
entity.player.things_tool_number.push([list[d[i]],c[i]])
} //恢复道具列表, 这里的JSON.parse用于把字符串变回数组
}
}
async function showPlayers() {
console.clear() // 清空控制台
const playerList = await db.sql`SELECT * FROM player`
for (const p of playerList) {
console.log(JSON.stringify(p))
}
}
async function createTable() {
await db.sql`CREATE TABLE IF NOT EXISTS player (
username TEXT DEFAULT '',--玩家名字
things TEXT DEFAULT '',--道具列表
things2 TEXT DEFAULT '',
things_second TEXT DEFAULT '',
things_tool TEXT DEFAULT '',
things_tool_number TEXT DEFAULT '',
userKey TEXT PRIMARY KEY UNIQUE DEFAULT ''--玩家的识别码
)`
showPlayers()
}
(async function() {
await createTable()
}());
world.onPlayerJoin(async({entity})=>{
//entity.player.cameraMode = "fps"
entity.player.things={"TNT":[1,10]}
entity.player.things_second=["打火石"]
entity.player.things_tool=["打火石"]
entity.player.things_tool_number=[[4,30]]})