forked from heroiclabs/nakama-project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatch_handler.ts
392 lines (350 loc) · 14.7 KB
/
match_handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// Copyright 2020 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
const moduleName = "tic-tac-toe_js";
const tickRate = 5;
const maxEmptySec = 30;
const delaybetweenGamesSec = 5;
const turnTimeFastSec = 10;
const turnTimeNormalSec = 20;
const winningPositions: number[][] = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]
interface MatchLabel {
open: number
fast: number
}
interface State {
// Match label
label: MatchLabel
// Ticks where no actions have occurred.
emptyTicks: number
// Currently connected users, or reserved spaces.
presences: {[userId: string]: nkruntime.Presence | null}
// Number of users currently in the process of connecting to the match.
joinsInProgress: number
// True if there's a game currently in progress.
playing: boolean
// Current state of the board.
board: Board
// Mark assignments to player user IDs.
marks: {[userId: string]: Mark | null}
// Whose turn it currently is.
mark: Mark
// Ticks until they must submit their move.
deadlineRemainingTicks: number
// The winner of the current game.
winner: Mark | null
// The winner positions.
winnerPositions: BoardPosition[] | null
// Ticks until the next game starts, if applicable.
nextGameRemainingTicks: number
}
let matchInit: nkruntime.MatchInitFunction<State> = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, params: {[key: string]: string}) {
const fast = !!params['fast'];
var label: MatchLabel = {
open: 1,
fast: 0,
}
if (fast) {
label.fast = 1;
}
var state: State = {
label: label,
emptyTicks: 0,
presences: {},
joinsInProgress: 0,
playing: false,
board: [],
marks: {},
mark: Mark.UNDEFINED,
deadlineRemainingTicks: 0,
winner: null,
winnerPositions: null,
nextGameRemainingTicks: 0,
}
return {
state,
tickRate,
label: JSON.stringify(label),
}
}
let matchJoinAttempt: nkruntime.MatchJoinAttemptFunction<State> = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: State, presence: nkruntime.Presence, metadata: {[key: string]: any}) {
// Check if it's a user attempting to rejoin after a disconnect.
if (presence.userId in state.presences) {
if (state.presences[presence.userId] === null) {
// User rejoining after a disconnect.
state.joinsInProgress++;
return {
state: state,
accept: false,
}
} else {
// User attempting to join from 2 different devices at the same time.
return {
state: state,
accept: false,
rejectMessage: 'already joined',
}
}
}
// Check if match is full.
if (connectedPlayers(state) + state.joinsInProgress >= 2) {
return {
state: state,
accept: false,
rejectMessage: 'match full',
};
}
// New player attempting to connect.
state.joinsInProgress++;
return {
state,
accept: true,
}
}
let matchJoin: nkruntime.MatchJoinFunction<State> = function(ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: State, presences: nkruntime.Presence[]) {
const t = msecToSec(Date.now());
for (const presence of presences) {
state.emptyTicks = 0;
state.presences[presence.userId] = presence;
state.joinsInProgress--;
// Check if we must send a message to this user to update them on the current game state.
if (state.playing) {
// There's a game still currently in progress, the player is re-joining after a disconnect. Give them a state update.
let update: UpdateMessage = {
board: state.board,
mark: state.mark,
deadline: t + Math.floor(state.deadlineRemainingTicks/tickRate),
}
// Send a message to the user that just joined.
dispatcher.broadcastMessage(OpCode.UPDATE, JSON.stringify(update));
} else if (state.board.length !== 0 && Object.keys(state.marks).length !== 0 && state.marks[presence.userId]) {
logger.debug('player %s rejoined game', presence.userId);
// There's no game in progress but we still have a completed game that the user was part of.
// They likely disconnected before the game ended, and have since forfeited because they took too long to return.
let done: DoneMessage = {
board: state.board,
winner: state.winner,
winnerPositions: state.winnerPositions,
nextGameStart: t + Math.floor(state.nextGameRemainingTicks/tickRate)
}
// Send a message to the user that just joined.
dispatcher.broadcastMessage(OpCode.DONE, JSON.stringify(done))
}
}
// Check if match was open to new players, but should now be closed.
if (Object.keys(state.presences).length >= 2 && state.label.open != 0) {
state.label.open = 0;
const labelJSON = JSON.stringify(state.label);
dispatcher.matchLabelUpdate(labelJSON);
}
return {state};
}
let matchLeave: nkruntime.MatchLeaveFunction<State> = function(ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: State, presences: nkruntime.Presence[]) {
for (let presence of presences) {
logger.info("Player: %s left match: %s.", presence.userId, ctx.matchId);
state.presences[presence.userId] = null;
}
return {state};
}
let matchLoop: nkruntime.MatchLoopFunction<State> = function(ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: State, messages: nkruntime.MatchMessage[]) {
logger.debug('Running match loop. Tick: %d', tick);
if (connectedPlayers(state) + state.joinsInProgress === 0) {
state.emptyTicks++;
if (state.emptyTicks >= maxEmptySec * tickRate) {
// Match has been empty for too long, close it.
logger.info('closing idle match');
return null;
}
}
let t = msecToSec(Date.now());
// If there's no game in progress check if we can (and should) start one!
if (!state.playing) {
// Between games any disconnected users are purged, there's no in-progress game for them to return to anyway.
for (let userID in state.presences) {
if (state.presences[userID] === null) {
delete state.presences[userID];
}
}
// Check if we need to update the label so the match now advertises itself as open to join.
if (Object.keys(state.presences).length < 2 && state.label.open != 1) {
state.label.open = 1;
let labelJSON = JSON.stringify(state.label);
dispatcher.matchLabelUpdate(labelJSON);
}
// Check if we have enough players to start a game.
if (Object.keys(state.presences).length < 2) {
return { state };
}
// Check if enough time has passed since the last game.
if (state.nextGameRemainingTicks > 0) {
state.nextGameRemainingTicks--
return { state };
}
// We can start a game! Set up the game state and assign the marks to each player.
state.playing = true;
state.board = new Array(9);
state.marks = {};
let marks = [Mark.X, Mark.O];
Object.keys(state.presences).forEach(userId => {
state.marks[userId] = marks.shift() ?? null;
});
state.mark = Mark.X;
state.winner = null;
state.winnerPositions = null;
state.deadlineRemainingTicks = calculateDeadlineTicks(state.label);
state.nextGameRemainingTicks = 0;
// Notify the players a new game has started.
let msg: StartMessage = {
board: state.board,
marks: state.marks,
mark: state.mark,
deadline: t + Math.floor(state.deadlineRemainingTicks / tickRate),
}
dispatcher.broadcastMessage(OpCode.START, JSON.stringify(msg));
return { state };
}
// There's a game in progresstate. Check for input, update match state, and send messages to clientstate.
for (const message of messages) {
switch (message.opCode) {
case OpCode.MOVE:
logger.debug('Received move message from user: %v', state.marks);
let mark = state.marks[message.sender.userId] ?? null;
if (mark === null || state.mark != mark) {
// It is not this player's turn.
dispatcher.broadcastMessage(OpCode.REJECTED, null, [message.sender]);
continue;
}
let msg = {} as MoveMessage;
try {
msg = JSON.parse(nk.binaryToString(message.data));
} catch (error) {
// Client sent bad data.
dispatcher.broadcastMessage(OpCode.REJECTED, null, [message.sender]);
logger.debug('Bad data received: %v', error);
continue;
}
if (state.board[msg.position]) {
// Client sent a position outside the board, or one that has already been played.
dispatcher.broadcastMessage(OpCode.REJECTED, null, [message.sender]);
continue;
}
// Update the game state.
state.board[msg.position] = mark;
state.mark = mark === Mark.O ? Mark.X : Mark.O;
state.deadlineRemainingTicks = calculateDeadlineTicks(state.label);
// Check if game is over through a winning move.
const [winner, winningPos] = winCheck(state.board, mark);
if (winner) {
state.winner = mark;
state.winnerPositions = winningPos;
state.playing = false;
state.deadlineRemainingTicks = 0;
state.nextGameRemainingTicks = delaybetweenGamesSec * tickRate;
}
// Check if game is over because no more moves are possible.
let tie = state.board.every(v => v !== null);
if (tie) {
// Update state to reflect the tie, and schedule the next game.
state.playing = false;
state.deadlineRemainingTicks = 0;
state.nextGameRemainingTicks = delaybetweenGamesSec * tickRate;
}
let opCode: OpCode
let outgoingMsg: Message
if (state.playing) {
opCode = OpCode.UPDATE
let msg: UpdateMessage = {
board: state.board,
mark: state.mark,
deadline: t + Math.floor(state.deadlineRemainingTicks/tickRate),
}
outgoingMsg = msg;
} else {
opCode = OpCode.DONE
let msg: DoneMessage = {
board: state.board,
winner: state.winner,
winnerPositions: state.winnerPositions,
nextGameStart: t + Math.floor(state.nextGameRemainingTicks/tickRate),
}
outgoingMsg = msg;
}
dispatcher.broadcastMessage(opCode, JSON.stringify(outgoingMsg));
break;
default:
// No other opcodes are expected from the client, so automatically treat it as an error.
dispatcher.broadcastMessage(OpCode.REJECTED, null, [message.sender]);
logger.error('Unexpected opcode received: %d', message.opCode);
}
}
// Keep track of the time remaining for the player to submit their move. Idle players forfeit.
if (state.playing) {
state.deadlineRemainingTicks--;
if (state.deadlineRemainingTicks <= 0 ) {
// The player has run out of time to submit their move.
state.playing = false;
state.winner = state.mark === Mark.O ? Mark.X : Mark.O;
state.deadlineRemainingTicks = 0;
state.nextGameRemainingTicks = delaybetweenGamesSec * tickRate;
let msg: DoneMessage = {
board: state.board,
winner: state.winner,
nextGameStart: t + Math.floor(state.nextGameRemainingTicks/tickRate),
winnerPositions: null,
}
dispatcher.broadcastMessage(OpCode.DONE, JSON.stringify(msg));
}
}
return { state };
}
let matchTerminate: nkruntime.MatchTerminateFunction<State> = function(ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: State, graceSeconds: number) {
return { state };
}
let matchSignal: nkruntime.MatchSignalFunction<State> = function(ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: State) {
return { state };
}
function calculateDeadlineTicks(l: MatchLabel): number {
if (l.fast === 1) {
return turnTimeFastSec * tickRate;
} else {
return turnTimeNormalSec * tickRate;
}
}
function winCheck(board: Board, mark: Mark): [boolean, Mark[] | null] {
for(let wp of winningPositions) {
if (board[wp[0]] === mark &&
board[wp[1]] === mark &&
board[wp[2]] === mark) {
return [true, wp];
}
}
return [false, null];
}
function connectedPlayers(s: State): number {
let count = 0;
for(const p of Object.keys(s.presences)) {
if (p !== null) {
count++;
}
}
return count;
}