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("");
11 this.next_player = "X";
14 /* Returns Boolean indicating whether move was legal and added. */
16 /* Cannot move to an occupied square. */
17 if (this.board[square])
20 this.board[square] = this.next_player;
21 this.moves.push(square);
23 if (this.next_player === "X")
24 this.next_player = "O";
26 this.next_player = "X";
31 broadcast_move(square) {
32 this.broadcast_event("move", square);
35 handle_events(request, response) {
36 super.handle_events(request, response);
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`);
45 router.post('/move', (request, response) => {
46 const game = request.game;
47 const square = request.body.square;
49 const legal = game.add_move(square);
51 /* Inform this client whether the move was legal. */
52 response.send(JSON.stringify(legal));
54 /* And only if legal, inform all clients. */
58 game.broadcast_move(square);
61 router.get('/events', (request, response) => {
62 const game = request.game;
64 game.handle_events(request, response);
67 exports.router = router;
68 exports.Game = TicTacToe;
72 identifier: "tictactoe"