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"; 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 { export class NetworkHelper {
_eventListeners: any = {}; _eventListeners: any = {};
_closed = false;
ctor() { } ctor() { }
on(eventName, func) { on(eventName, func) {
...@@ -27,105 +35,38 @@ export class NetworkHelper { ...@@ -27,105 +35,38 @@ export class NetworkHelper {
listenerInited = false; listenerInited = false;
room: any; room: any;
client: any; playerId: string;
async initRoom() { async initRoom() {
const client = new globalThis.Play.Client({ this.playerId = `${new Date().getTime()}_${RandomInt(100000000)}`;
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('连接成功');
} }
player: any; player: any;
joinRoom(roomType: string, maxPlayers: number) { joinRoom(roomType: string, maxPlayers: number) {
return new Promise((resolve, reject) => { this.room = new FakeRoom(this.playerId);
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.players.push(this.room.player); this.room.players.push(this.room.player);
this.player = this.room.player; this.player = this.room.player;
console.log("本地房间已创建", roomType, maxPlayers);
this.client.on(globalThis.Play.Event.PLAYER_ROOM_LEFT, (event) => { return Promise.resolve(this.playerId);
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;
} }
async leaveRoom() { async leaveRoom() { }
await this.client.close();
console.log("退房成功");
}
async dismissRoom() { async dismissRoom() { }
if (this.room.ownerId == this.player.id) {
console.log("房间已解散");
}
}
async closeRoom() { async closeRoom() { }
// 设置房间不可见
await this.client.setRoomVisible(false);
console.log(this.client.room.visible);
}
async startFrameSync() { async startFrameSync() { }
console.log("开始帧同步成功");
}
async stopFrameSync() { async stopFrameSync() { }
console.log("停止帧同步成功");
}
sendFrame(data: any) { sendFrame(data: any) {
this.client.sendEvent(0, { frame: { items: [{ data: data }] } }, { const event = { data: { frame: { items: [{ data: data }] } } };
receiverGroup: globalThis.Play.ReceiverGroup.All, setTimeout(() => {
}); if (this._closed) {
return;
}
this.onRecvFrame(event);
}, 0);
} }
onJoinRoom(event) { onJoinRoom(event) {
...@@ -133,16 +74,12 @@ export class NetworkHelper { ...@@ -133,16 +74,12 @@ export class NetworkHelper {
if (this._eventListeners["playerJoin"]) { if (this._eventListeners["playerJoin"]) {
this._eventListeners["playerJoin"](event); this._eventListeners["playerJoin"](event);
} }
this.room.players.forEach(player => {
console.log('player.playerId = ', player.playerId);
});
} }
onLeaveRoom(event) { onLeaveRoom(event) {
console.log("onLeaveRoom"); console.log("onLeaveRoom");
if (this._eventListeners["playerLeave"]) { if (this._eventListeners["playerLeave"]) {
this._eventListeners["playerLeave"](event); this._eventListeners["playerLeave"](event);
} }
console.log("玩家退出", event.data.leavePlayerId);
} }
onRecvFromClient() { } onRecvFromClient() { }
...@@ -168,17 +105,7 @@ export class NetworkHelper { ...@@ -168,17 +105,7 @@ export class NetworkHelper {
onRecvFromGameSvr() { } onRecvFromGameSvr() { }
async onDestroy() { async onDestroy() {
try { this._closed = true;
console.log("onDestroy1");
// MGOBE.Listener.clear();
this.stopFrameSync();
this.closeRoom();
this.dismissRoom();
this.leaveRoom();
console.log("onDestroy2");
} catch (e) {
console.log(JSON.stringify(e));
}
} }
log(str) { log(str) {
...@@ -233,4 +160,4 @@ class FakeRoom { ...@@ -233,4 +160,4 @@ class FakeRoom {
this.ownerId = playerId; this.ownerId = playerId;
this.roomInfo = { owner: playerId } this.roomInfo = { owner: playerId }
} }
} }
\ No newline at end of file
...@@ -113,7 +113,7 @@ export class GameServer { ...@@ -113,7 +113,7 @@ export class GameServer {
this._aiPlayerList.push(new AI(this.networkHelper, playerInfo)); this._aiPlayerList.push(new AI(this.networkHelper, playerInfo));
this.addPlayer(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