]> git.cworth.org Git - lmno-server/blob - tictactoe.js
Move some checks from TicTacToe.add_move to Game.add_move
[lmno-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 result = super.add_move(player, square);
19
20     /* If the generic Game class can reject this move, then we don't
21      * need to look at it any further. */
22     if (! result.legal)
23       return result;
24
25     /* Cannot move to an occupied square. */
26     if (this.state.board[square])
27     {
28       return { legal: false,
29                message: "Square is already occupied" };
30     }
31
32     this.state.board[square] = this.state.team_to_play;
33     this.state.moves.push(square);
34
35     if (this.state.team_to_play === "X")
36       this.state.team_to_play = "O";
37     else
38       this.state.team_to_play = "X";
39
40     return { legal: true };
41   }
42 }
43
44 TicTacToe.router = express.Router();
45
46 TicTacToe.meta = {
47   name: "Tic Tac Toe",
48   identifier: "tictactoe"
49 };
50
51 exports.Game = TicTacToe;