1 const express = require("express");
2 const Game = require("./game.js");
4 const router = express.Router();
6 class TicTacToe extends Game {
10 this.board = Array(9).fill(null);
13 /* Returns Boolean indicating whether move was legal and added. */
15 /* Cannot move to an occupied square. */
16 if (this.board[square])
19 this.board[square] = 'X';
20 this.moves.push(square);
25 broadcast_move(square) {
26 this.broadcast_event("move", square);
29 handle_events(request, response) {
30 super.handle_events(request, response);
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`);
39 router.post('/move', (request, response) => {
40 const game = request.game;
41 const square = request.body.square;
43 const legal = game.add_move(square);
45 /* Inform this client whether the move was legal. */
46 response.send(JSON.stringify(legal));
48 /* And only if legal, inform all clients. */
52 game.broadcast_move(square);
55 router.get('/events', (request, response) => {
56 const game = request.game;
58 game.handle_events(request, response);
61 exports.router = router;
62 exports.Game = TicTacToe;
66 identifier: "tictactoe"
69 exports.meta = TicTacToe.meta;