]> git.cworth.org Git - empires-server/blob - tictactoe.js
tictactoe: Simplify code by not reusing the expression "this.state"
[empires-server] / tictactoe.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 class TicTacToe extends Game {
5   constructor(id) {
6     super(id);
7     this.state = {
8       moves: [],
9       board: Array(9).fill(""),
10       team_to_play: "X",
11     };
12     this.teams = ["X", "O"];
13   }
14
15   /* Returns true if move was legal and added, false otherwise. */
16   add_move(player, square) {
17
18     const state = this.state;
19     const result = super.add_move(player, square);
20
21     /* If the generic Game class can reject this move, then we don't
22      * need to look at it any further. */
23     if (! result.legal)
24       return result;
25
26     /* Cannot move to an occupied square. */
27     if (state.board[square])
28     {
29       return { legal: false,
30                message: "Square is already occupied" };
31     }
32
33     state.board[square] = state.team_to_play;
34     state.moves.push(square);
35
36     if (state.team_to_play === "X")
37       state.team_to_play = "O";
38     else
39       state.team_to_play = "X";
40
41     return { legal: true };
42   }
43 }
44
45 TicTacToe.router = express.Router();
46
47 TicTacToe.meta = {
48   name: "Tic Tac Toe",
49   identifier: "tictactoe"
50 };
51
52 exports.Game = TicTacToe;