]> git.cworth.org Git - empires-server/blob - tictactoe.js
tictactoe: Track API change for the /move request: "square" -> "move"
[empires-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
38 router.post('/move', (request, response) => {
39   const game = request.game;
40   const square = request.body.move;
41
42   const legal = game.add_move(square);
43
44   /* Inform this client whether the move was legal. */
45   response.send(JSON.stringify(legal));
46
47   /* And only if legal, inform all clients. */
48   if (! legal)
49     return;
50
51   game.broadcast_move(square);
52 });
53
54 exports.router = router;
55 exports.Game = TicTacToe;
56
57 TicTacToe.meta = {
58   name: "Tic Tac Toe",
59   identifier: "tictactoe"
60 };