]> git.cworth.org Git - empires-server/blob - tictactoe.js
tictactoe: Replay previous moves when a new client connects
[empires-server] / tictactoe.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 const engine_name = "tictactoe";
5
6 const router = express.Router();
7
8 class TicTacToe extends Game {
9   constructor() {
10     super(engine_name);
11     this.moves = [];
12     this.board = Array(9).fill(null);
13   }
14
15   /* Returns Boolean indicating whether move was legal and added. */
16   add_move(square) {
17     /* Cannot move to an occupied square. */
18     if (this.board[square])
19       return false;
20
21     this.board[square] = 'X';
22     this.moves.push(square);
23
24     return true;
25   }
26
27   broadcast_move(square) {
28     this.broadcast_event("move", square);
29   }
30
31   handle_events(request, response) {
32     super.handle_events(request, response);
33
34     /* When a new client joins, replay all previous moves to it. */
35     for (let move of this.moves) {
36       response.write(`event: move\ndata: ${move}\n\n`);
37     }
38   }
39 }
40
41 router.get('/', (request, response) => {
42   const game = request.game;
43
44   if (! request.session.nickname)
45     response.render('choose-nickname.html', { game_name: "Tic Tac Toe" });
46   else
47     response.render('tictactoe-game.html');
48 });
49
50 router.post('/move', (request, response) => {
51   const game = request.game;
52   const square = request.body.square;
53
54   const legal = game.add_move(square);
55
56   /* Inform this client whether the move was legal. */
57   response.send(JSON.stringify(legal));
58
59   /* And only if legal, inform all clients. */
60   if (! legal)
61     return;
62
63   game.broadcast_move(square);
64 });
65
66 router.get('/events', (request, response) => {
67   const game = request.game;
68
69   game.handle_events(request, response);
70 });
71
72 exports.router = router;
73 exports.name = engine_name;
74 exports.Game = TicTacToe;