Skip to content

Commit 52035aa

Browse files
committed
完善创建房间和加入房间逻辑
1 parent 8700115 commit 52035aa

18 files changed

+3503
-4471
lines changed

client-lib-copy-test.bat

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
@echo off
2+
set sourceDir=source\bin
3+
set destinationDir=client-test\lib
4+
5+
xcopy "%sourceDir%\*" "%destinationDir%\" /s /i /y

client-test/dist/gs-client.js

+19-1
Original file line numberDiff line numberDiff line change
@@ -125,10 +125,28 @@ core.entityManager.getNetworkManager().getNetworkAdapter().onServerUpdate(functi
125125
document.getElementById('player-session').textContent = "SESSION:" + serverState.payload;
126126
}
127127
if (serverState.type != 'heartbeat') {
128-
document.getElementById('loggerArea').append("[".concat(serverState.type, "]: ").concat(JSON.stringify(serverState.payload), "\n"));
128+
document.getElementById('loggerArea').textContent += ("[".concat(serverState.type, "]: ").concat(JSON.stringify(serverState.payload), "\n"));
129129
console.warn('更新游戏状态', serverState);
130130
}
131131
});
132+
document.addEventListener("DOMContentLoaded", function () {
133+
// 获取加入房间按钮
134+
var joinRoomButton = document.getElementById("join-room-btn");
135+
var createRoomButton = document.getElementById("create-room-btn");
136+
var leaveRoomButton = document.getElementById('leave-room-btn');
137+
joinRoomButton.onclick = function (ev) {
138+
console.log("发送加入房间指令");
139+
};
140+
createRoomButton.onclick = function (ev) {
141+
console.log("发送创建房间指令");
142+
networkAdapter.RoomAPI.createRoom(10, function (roomId) {
143+
document.getElementById('room-id').textContent = "ID: " + roomId;
144+
});
145+
};
146+
leaveRoomButton.onclick = function (ev) {
147+
console.log("发送退出房间指令");
148+
};
149+
});
132150
var lastTimestamp = performance.now();
133151
var timestamp = 0;
134152
function update() {

client-test/index.html

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ <h2>玩家信息</h2>
1818
<div id="room-actions">
1919
<h2>房间信息</h2>
2020
<p id="room-id">ID: </p>
21+
<button id="create-room-btn">创建房间</button>
2122
<button id="join-room-btn">加入房间</button>
2223
<button id="leave-room-btn">退出房间</button>
2324
</div>

client-test/lib/gs.d.ts

+36-2
Original file line numberDiff line numberDiff line change
@@ -698,8 +698,6 @@ declare module gs {
698698
declare module gs {
699699
class Authentication {
700700
private connection;
701-
private token;
702-
private verificationCode;
703701
constructor(connection: Connection);
704702
/**
705703
* 启动身份验证过程。
@@ -729,6 +727,15 @@ declare module gs {
729727
send(message: any): void;
730728
}
731729
}
730+
declare module gs {
731+
const ErrorCodes: {
732+
SUCCESS: string;
733+
AUTH_FAIL: string;
734+
WRONG_PASSWORD: string;
735+
REGISTRATION_FAILED: string;
736+
RECONNECT_FAIL: string;
737+
};
738+
}
732739
declare module gs {
733740
class GNetworkAdapter implements NetworkAdapter {
734741
private serverUrl;
@@ -739,6 +746,9 @@ declare module gs {
739746
private authentication;
740747
private sessionId;
741748
private lastKnownState;
749+
private messageHandler;
750+
private roomAPI;
751+
readonly RoomAPI: RoomApi;
742752
constructor(serverUrl: string, username: string, password: string);
743753
private connect;
744754
sendInput(frameNumber: number, inputData: any): void;
@@ -756,6 +766,7 @@ declare module gs {
756766
}
757767
declare module gs {
758768
interface NetworkAdapter {
769+
send(message: Message): void;
759770
/**
760771
* 将输入数据发送到服务器
761772
* @param frameNumber 客户端帧编号
@@ -790,6 +801,29 @@ declare module gs {
790801
static sendToConnection(connection: Connection, message: Message): void;
791802
}
792803
}
804+
declare module gs {
805+
class MessageHandler {
806+
private messageHandlers;
807+
emit(message: Message): void;
808+
on(type: string, handler: (msg: Message) => void): void;
809+
private handleMessage;
810+
}
811+
}
812+
declare module gs {
813+
class RoomApi {
814+
adapter: NetworkAdapter;
815+
private createRoomCallback;
816+
constructor(adapter: NetworkAdapter);
817+
createRoom(maxPlayers: number, callback: (roomId: string) => void): void;
818+
joinRoom(roomId: string, playerId: string): void;
819+
leaveRoom(): void;
820+
/**
821+
* 当房间创建成功时被调用
822+
* @param roomId - 房间ID
823+
*/
824+
onRoomCreated(roomId: string): void;
825+
}
826+
}
793827
declare module gs {
794828
interface ISyncStrategy {
795829
sendState(state: any): void;

client-test/lib/gs.js

+89-7
Original file line numberDiff line numberDiff line change
@@ -1887,8 +1887,6 @@ var gs;
18871887
(function (gs) {
18881888
var Authentication = /** @class */ (function () {
18891889
function Authentication(connection) {
1890-
this.token = null;
1891-
this.verificationCode = null;
18921890
this.connection = connection;
18931891
}
18941892
/**
@@ -1911,10 +1909,8 @@ var gs;
19111909
* @param message - 身份验证消息对象。
19121910
*/
19131911
Authentication.prototype.handleAuthenticationMessage = function (message) {
1914-
switch (message.type) {
1915-
case 'authentication':
1916-
this.afterAuthenticated();
1917-
break;
1912+
if (message.payload.code == gs.ErrorCodes.SUCCESS) {
1913+
this.afterAuthenticated();
19181914
}
19191915
};
19201916
/**
@@ -1952,6 +1948,16 @@ var gs;
19521948
gs.Connection = Connection;
19531949
})(gs || (gs = {}));
19541950
var gs;
1951+
(function (gs) {
1952+
gs.ErrorCodes = {
1953+
SUCCESS: 'SUCCESS',
1954+
AUTH_FAIL: 'AUTH_FAIL',
1955+
WRONG_PASSWORD: 'WRONG_PASSWORD',
1956+
REGISTRATION_FAILED: 'REGISTRATION_FAILED',
1957+
RECONNECT_FAIL: 'RECONNECT_FAIL',
1958+
};
1959+
})(gs || (gs = {}));
1960+
var gs;
19551961
(function (gs) {
19561962
var GNetworkAdapter = /** @class */ (function () {
19571963
function GNetworkAdapter(serverUrl, username, password) {
@@ -1961,9 +1967,18 @@ var gs;
19611967
this.sessionId = null;
19621968
this.lastKnownState = null;
19631969
this.connection = new gs.Connection(serverUrl);
1970+
this.messageHandler = new gs.MessageHandler();
19641971
this.authentication = new gs.Authentication(this.connection);
1972+
this.roomAPI = new gs.RoomApi(this);
19651973
this.connect(username, password);
19661974
}
1975+
Object.defineProperty(GNetworkAdapter.prototype, "RoomAPI", {
1976+
get: function () {
1977+
return this.roomAPI;
1978+
},
1979+
enumerable: true,
1980+
configurable: true
1981+
});
19671982
GNetworkAdapter.prototype.connect = function (username, password) {
19681983
var _this = this;
19691984
this.socket = this.connection.Socket;
@@ -1995,8 +2010,11 @@ var gs;
19952010
});
19962011
this.socket.addEventListener('message', function (event) {
19972012
var message = JSON.parse(event.data);
2013+
_this.messageHandler.emit(message);
19982014
if (message.type === 'authentication') {
1999-
_this.sessionId = message.payload.sessionId; // 存储sessionId
2015+
if (message.payload.code == gs.ErrorCodes.SUCCESS) {
2016+
_this.sessionId = message.payload.sessionId; // 存储sessionId
2017+
}
20002018
_this.authentication.handleAuthenticationMessage(message);
20012019
}
20022020
else if (message.type === 'sessionId') {
@@ -2008,6 +2026,10 @@ var gs;
20082026
else if (message.type == 'heartbeat') {
20092027
// 心跳包
20102028
}
2029+
else if (message.type == 'roomCreated') {
2030+
// 房间创建
2031+
_this.roomAPI.onRoomCreated(message.payload.roomId);
2032+
}
20112033
else {
20122034
console.warn("[g-client]: \u672A\u77E5\u7684\u6D88\u606F\u7C7B\u578B: " + message.type);
20132035
}
@@ -2082,6 +2104,66 @@ var gs;
20822104
gs.WebSocketUtils = WebSocketUtils;
20832105
})(gs || (gs = {}));
20842106
var gs;
2107+
(function (gs) {
2108+
var MessageHandler = /** @class */ (function () {
2109+
function MessageHandler() {
2110+
}
2111+
MessageHandler.prototype.emit = function (message) {
2112+
this.handleMessage(message);
2113+
};
2114+
MessageHandler.prototype.on = function (type, handler) {
2115+
this.messageHandlers[type] = handler;
2116+
};
2117+
MessageHandler.prototype.handleMessage = function (message) {
2118+
if (!this.messageHandlers)
2119+
return;
2120+
var handler = this.messageHandlers[message.type];
2121+
if (handler) {
2122+
handler(message);
2123+
}
2124+
};
2125+
return MessageHandler;
2126+
}());
2127+
gs.MessageHandler = MessageHandler;
2128+
})(gs || (gs = {}));
2129+
var gs;
2130+
(function (gs) {
2131+
var RoomApi = /** @class */ (function () {
2132+
function RoomApi(adapter) {
2133+
this.adapter = adapter;
2134+
this.createRoomCallback = null;
2135+
}
2136+
RoomApi.prototype.createRoom = function (maxPlayers, callback) {
2137+
this.createRoomCallback = callback;
2138+
var message = {
2139+
type: 'createRoom',
2140+
payload: { 'maxPlayers': maxPlayers }
2141+
};
2142+
this.adapter.send(message);
2143+
};
2144+
RoomApi.prototype.joinRoom = function (roomId, playerId) {
2145+
var message = {
2146+
type: 'joinRoom',
2147+
payload: { 'roomId': roomId, 'playerId': playerId }
2148+
};
2149+
this.adapter.send(message);
2150+
};
2151+
RoomApi.prototype.leaveRoom = function () {
2152+
};
2153+
/**
2154+
* 当房间创建成功时被调用
2155+
* @param roomId - 房间ID
2156+
*/
2157+
RoomApi.prototype.onRoomCreated = function (roomId) {
2158+
if (this.createRoomCallback) {
2159+
this.createRoomCallback(roomId);
2160+
}
2161+
};
2162+
return RoomApi;
2163+
}());
2164+
gs.RoomApi = RoomApi;
2165+
})(gs || (gs = {}));
2166+
var gs;
20852167
(function (gs) {
20862168
/**
20872169
* 快照插值策略

client-test/lib/gs.min.js

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

client-test/src/index.ts

+22-7
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,36 @@ core.entityManager.getNetworkManager().getNetworkAdapter().onServerUpdate((serve
2929
}
3030

3131
if (serverState.type != 'heartbeat') {
32-
document.getElementById('loggerArea').append(`[${serverState.type}]: ${JSON.stringify(serverState.payload)}\n`);
32+
document.getElementById('loggerArea').textContent += (`[${serverState.type}]: ${JSON.stringify(serverState.payload)}\n`);
3333

3434
console.warn('更新游戏状态', serverState);
3535
}
3636
});
3737

38-
document.getElementById('join-room-btn').onclick = ( ev: MouseEvent)=> {
39-
const joinMessage: gs.Message = {
40-
type: 'joinRoom',
41-
payload: null
38+
document.addEventListener("DOMContentLoaded", function() {
39+
// 获取加入房间按钮
40+
const joinRoomButton = document.getElementById("join-room-btn");
41+
const createRoomButton = document.getElementById("create-room-btn");
42+
const leaveRoomButton = document.getElementById('leave-room-btn');
43+
44+
joinRoomButton.onclick = ( ev: MouseEvent)=> {
45+
console.log("发送加入房间指令");
46+
}
47+
48+
createRoomButton.onclick = (ev: MouseEvent) => {
49+
console.log("发送创建房间指令");
50+
51+
networkAdapter.RoomAPI.createRoom(10, roomId => {
52+
document.getElementById('room-id').textContent = "ID: " + roomId;
53+
});
4254
};
4355

44-
networkAdapter.send(joinMessage)
45-
}
56+
leaveRoomButton.onclick = (ev: MouseEvent) => {
57+
console.log("发送退出房间指令");
4658

59+
networkAdapter.RoomAPI.leaveRoom();
60+
};
61+
});
4762

4863
let lastTimestamp = performance.now();
4964
let timestamp = 0;

server/src/GameLogic/Player.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,9 @@ export class Player {
99
* @param id - 玩家的唯一标识符。
1010
* @param connection - 玩家的连接对象。
1111
*/
12-
constructor(public id: string, public connection: Connection) {}
12+
private constructor(public id: string, public connection: Connection) {}
13+
14+
static create(connection: Connection): Player {
15+
return new Player(connection.id, connection);
16+
}
1317
}

server/src/GameLogic/Room.ts

+14-1
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ export class Room {
1818
/**
1919
* 创建一个新的房间实例。
2020
* @param id - 房间 ID。
21+
* @param owner - 房间拥有者
2122
* @param maxPlayers - 房间最大玩家数。
2223
*/
23-
constructor(public id: string, public maxPlayers: number) {}
24+
constructor(public id: string, public owner: string, public maxPlayers: number) {}
2425

2526
/**
2627
* 添加玩家到房间。
@@ -44,6 +45,11 @@ export class Room {
4445
const index = this.players.findIndex((p) => p.id === player.id);
4546
if (index > -1) {
4647
this.players.splice(index, 1);
48+
49+
// 更换房主
50+
if (this.owner == player.id && this.hasPlayers()) {
51+
this.owner = this.players[0].id;
52+
}
4753
} else {
4854
logger.error('[g-server]: 未在房间找到该玩家 %s', player.id);
4955
}
@@ -56,4 +62,11 @@ export class Room {
5662
public getPlayerIds(): string[] {
5763
return this.players.map(player => player.id);
5864
}
65+
66+
/**
67+
* 房间内是否还有玩家
68+
*/
69+
public hasPlayers(): boolean {
70+
return this.players.length != 0;
71+
}
5972
}

0 commit comments

Comments
 (0)