Commit 22e42686 authored by liwei's avatar liwei

feat: 联机改为本地 AI 对战

LeanCloud 对战服务已不可用,改为本机房主并在 2.3 秒后由 AI 补上对手。
Co-authored-by: 's avatarCursor <cursoragent@cursor.com>
parent 304ab2f7
import { RandomInt } from "./util_BoardGame2";
/**
* 本地单机版,用来替换 LeanCloud 联机。
* 其他同类型游戏只改各自的 NetworkHelper,场景、GameServer、AI 保持不动。
* 要保住的对外行为:
* - init() 返回本机 playerId,并且 playerId === room.roomInfo.owner(本机当房主,才会启动 GameServer)
* - sendFrame(data) 在下一拍回调 on("frameEvent"),数据仍是 event.data.frame.items[0].data
*/
export class NetworkHelper {
_eventListeners: any = {};
_closed = false;
ctor() { }
on(eventName, func) {
......@@ -27,105 +35,38 @@ export class NetworkHelper {
listenerInited = false;
room: any;
client: any;
playerId: string;
async initRoom() {
const client = new globalThis.Play.Client({
appId: "JCKc6bU8FywdjIPupjNH8Jwx-gzGzoHsz",
appKey: "WUrRDpb46z2qFLsUNbhknYcP",
userId: `${new Date().getTime()}_${RandomInt(100000000)}`,
playServer: 'https://lyn5nahs.lc-cn-n1-shared.com'
});
console.log('client = ', client);
await client.connect();
this.client = client;
console.log('连接成功');
this.playerId = `${new Date().getTime()}_${RandomInt(100000000)}`;
}
player: any;
joinRoom(roomType: string, maxPlayers: number) {
return new Promise((resolve, reject) => {
const roomProp = { roomType, maxPlayers };
this.client.joinRandomRoom({
matchProperties: roomProp,
}).then((room) => {
resolve(this.onJoinRoomSuccess(room));
}).catch((error) => {
console.log('加入房间失败');
if (error.code == 4301) {
const options = {
visible: true,
playerTtl: 0,
emptyRoomTtl: 0,
maxPlayerCount: maxPlayers,
customRoomProperties: roomProp,
customRoomPropertyKeysForLobby: ['roomType', 'maxPlayers'],
flag: globalThis.Play.CreateRoomFlag.MasterUpdateRoomProperties
};
this.client.createRoom({
roomOptions: options,
}).then((room) => {
resolve(this.onJoinRoomSuccess(room));
}).catch((error) => {
console.error(error.code, error.detail);
});
}
});
});
}
onJoinRoomSuccess(room: globalThis.Play.Room) {
console.log('加入房间成功 room = ', room);
const playerMe = room.playerList.find(player => player.isLocal);
const masterPlayer = room.playerList.find(player => player.isMaster);
const masterId = masterPlayer.userId;
const playerId = playerMe.userId;
this.room = new FakeRoom(masterId);
this.room = new FakeRoom(this.playerId);
this.room.players.push(this.room.player);
this.player = this.room.player;
this.client.on(globalThis.Play.Event.PLAYER_ROOM_LEFT, (event) => {
this.onLeaveRoom({ data: { leavePlayerId: event.leftPlayer.userId } });
});
this.client.on(globalThis.Play.Event.PLAYER_ROOM_JOINED, (event) => {
this.onJoinRoom({ playerId: event.newPlayer.userId });
});
this.client.on(globalThis.Play.Event.CUSTOM_EVENT, (event) => {
this.onRecvFrame({ data: event.eventData });
});
// this.room.onDisconnect(this.onDisconnect.bind(this));
// this.room.onDismiss(this.onDisconnect.bind(this));
return playerId;
console.log("本地房间已创建", roomType, maxPlayers);
return Promise.resolve(this.playerId);
}
async leaveRoom() {
await this.client.close();
console.log("退房成功");
}
async leaveRoom() { }
async dismissRoom() {
if (this.room.ownerId == this.player.id) {
console.log("房间已解散");
}
}
async dismissRoom() { }
async closeRoom() {
// 设置房间不可见
await this.client.setRoomVisible(false);
console.log(this.client.room.visible);
}
async closeRoom() { }
async startFrameSync() {
console.log("开始帧同步成功");
}
async startFrameSync() { }
async stopFrameSync() {
console.log("停止帧同步成功");
}
async stopFrameSync() { }
sendFrame(data: any) {
this.client.sendEvent(0, { frame: { items: [{ data: data }] } }, {
receiverGroup: globalThis.Play.ReceiverGroup.All,
});
const event = { data: { frame: { items: [{ data: data }] } } };
setTimeout(() => {
if (this._closed) {
return;
}
this.onRecvFrame(event);
}, 0);
}
onJoinRoom(event) {
......@@ -133,16 +74,12 @@ export class NetworkHelper {
if (this._eventListeners["playerJoin"]) {
this._eventListeners["playerJoin"](event);
}
this.room.players.forEach(player => {
console.log('player.playerId = ', player.playerId);
});
}
onLeaveRoom(event) {
console.log("onLeaveRoom");
if (this._eventListeners["playerLeave"]) {
this._eventListeners["playerLeave"](event);
}
console.log("玩家退出", event.data.leavePlayerId);
}
onRecvFromClient() { }
......@@ -168,17 +105,7 @@ export class NetworkHelper {
onRecvFromGameSvr() { }
async onDestroy() {
try {
console.log("onDestroy1");
// MGOBE.Listener.clear();
this.stopFrameSync();
this.closeRoom();
this.dismissRoom();
this.leaveRoom();
console.log("onDestroy2");
} catch (e) {
console.log(JSON.stringify(e));
}
this._closed = true;
}
log(str) {
......@@ -233,4 +160,4 @@ class FakeRoom {
this.ownerId = playerId;
this.roomInfo = { owner: playerId }
}
}
\ No newline at end of file
}
......@@ -113,7 +113,7 @@ export class GameServer {
this._aiPlayerList.push(new AI(this.networkHelper, playerInfo));
this.addPlayer(playerInfo);
}
}, RandomInt(10000, 15000))
}, 2300)
);
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment