1 const express = require("express");
2 const Game = require("./game.js");
4 const router = express.Router();
6 class TicTacToe extends Game {
11 board: Array(9).fill(""),
16 /* Returns Boolean indicating whether move was legal and added. */
18 /* Cannot move to an occupied square. */
19 if (this.state.board[square])
22 this.state.board[square] = this.state.next_player;
23 this.state.moves.push(square);
25 if (this.state.next_player === "X")
26 this.state.next_player = "O";
28 this.state.next_player = "X";
33 broadcast_move(square) {
34 this.broadcast_event("move", square);
37 handle_events(request, response) {
38 super.handle_events(request, response);
40 /* When a new client joins, give them the current game state,
41 * (which includes the history of moves). */
42 const state_json = JSON.stringify(this.state);
43 response.write(`event: game-state\ndata: ${state_json}\n\n`);
47 router.post('/move', (request, response) => {
48 const game = request.game;
49 const square = request.body.square;
51 const legal = game.add_move(square);
53 /* Inform this client whether the move was legal. */
54 response.send(JSON.stringify(legal));
56 /* And only if legal, inform all clients. */
60 game.broadcast_move(square);
63 router.get('/events', (request, response) => {
64 const game = request.game;
66 game.handle_events(request, response);
69 exports.router = router;
70 exports.Game = TicTacToe;
74 identifier: "tictactoe"