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