]> git.cworth.org Git - lmno-server/blob - tictactoe.js
Standardize transmission of game "state" when a client joins
[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
38 router.post('/move', (request, response) => {
39   const game = request.game;
40   const square = request.body.square;
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 router.get('/events', (request, response) => {
55   const game = request.game;
56
57   game.handle_events(request, response);
58 });
59
60 exports.router = router;
61 exports.Game = TicTacToe;
62
63 TicTacToe.meta = {
64   name: "Tic Tac Toe",
65   identifier: "tictactoe"
66 };