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