新建项目
This commit is contained in:
82
pages/join/join.js
Normal file
82
pages/join/join.js
Normal file
@@ -0,0 +1,82 @@
|
||||
const service = require("../../services/game-service");
|
||||
|
||||
Page({
|
||||
data: {
|
||||
code: "",
|
||||
name: "我",
|
||||
avatar: "我",
|
||||
preview: null,
|
||||
previewHint: "",
|
||||
canJoin: false,
|
||||
submitting: false
|
||||
},
|
||||
|
||||
onLoad(options) {
|
||||
if (options.code) {
|
||||
this.setData({ code: options.code });
|
||||
this.previewRoom(options.code);
|
||||
}
|
||||
},
|
||||
|
||||
onCodeInput(event) {
|
||||
const code = event.detail.value.replace(/\D/g, "").slice(0, 6);
|
||||
this.setData({ code, preview: null, previewHint: "", canJoin: false });
|
||||
if (code.length === 6) this.previewRoom(code);
|
||||
},
|
||||
|
||||
onNameInput(event) {
|
||||
const name = event.detail.value;
|
||||
this.setData({ name, avatar: name.slice(0, 1) || "?" });
|
||||
},
|
||||
|
||||
previewRoom(code) {
|
||||
const preview = service.getRoom(code);
|
||||
let previewHint = "";
|
||||
let canJoin = false;
|
||||
if (!preview) {
|
||||
previewHint = "没有找到这个房间,请检查房间码";
|
||||
} else if (preview.status === "finished") {
|
||||
previewHint = "这场游戏已经结束";
|
||||
} else if (preview.status === "cancelled") {
|
||||
previewHint = "房间已被房主取消";
|
||||
} else if (preview.status !== "waiting") {
|
||||
previewHint = "游戏已经开始,暂时无法加入";
|
||||
} else {
|
||||
const alreadyJoined = preview.players.some(
|
||||
(player) => player.id === service.USER_ID
|
||||
);
|
||||
canJoin = alreadyJoined || preview.players.length < preview.settings.maxPlayers;
|
||||
if (!canJoin) previewHint = "房间人数已满";
|
||||
}
|
||||
this.setData({ preview, previewHint, canJoin });
|
||||
},
|
||||
|
||||
useDemoCode() {
|
||||
this.setData({ code: "731204" });
|
||||
this.previewRoom("731204");
|
||||
},
|
||||
|
||||
join() {
|
||||
if (this.data.submitting) return;
|
||||
if (this.data.code.length !== 6) {
|
||||
wx.showToast({ title: "请输入六位房间码", icon: "none" });
|
||||
return;
|
||||
}
|
||||
if (!this.data.name.trim()) {
|
||||
wx.showToast({ title: "请输入游戏昵称", icon: "none" });
|
||||
return;
|
||||
}
|
||||
if (!this.data.canJoin) {
|
||||
wx.showToast({ title: this.data.previewHint || "当前不能加入房间", icon: "none" });
|
||||
return;
|
||||
}
|
||||
this.setData({ submitting: true });
|
||||
try {
|
||||
const room = service.joinRoom(this.data.code, this.data.name.trim());
|
||||
wx.redirectTo({ url: `/pages/lobby/lobby?code=${room.code}` });
|
||||
} catch (error) {
|
||||
this.setData({ submitting: false });
|
||||
wx.showToast({ title: error.message, icon: "none" });
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user