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