1 const express = require("express");
2 const Game = require("./game.js");
4 const engine_name = "tictactoe";
6 const router = express.Router();
8 class TicTacToe extends Game {
12 this.board = Array(9).fill(null);
15 /* Returns Boolean indicating whether move was legal and added. */
17 /* Cannot move to an occupied square. */
18 if (this.board[square])
21 this.board[square] = 'X';
22 this.moves.push(square);
27 broadcast_move(square) {
28 this.broadcast_event("move", square);
31 handle_events(request, response) {
32 super.handle_events(request, response);
34 /* When a new client joins, replay all previous moves to it. */
35 for (let move of this.moves) {
36 response.write(`event: move\ndata: ${move}\n\n`);
41 router.get('/', (request, response) => {
42 const game = request.game;
44 if (! request.session.nickname)
45 response.render('choose-nickname.html', { game_name: game.meta.name });
47 response.render('tictactoe-game.html');
50 router.post('/move', (request, response) => {
51 const game = request.game;
52 const square = request.body.square;
54 const legal = game.add_move(square);
56 /* Inform this client whether the move was legal. */
57 response.send(JSON.stringify(legal));
59 /* And only if legal, inform all clients. */
63 game.broadcast_move(square);
66 router.get('/events', (request, response) => {
67 const game = request.game;
69 game.handle_events(request, response);
72 exports.router = router;
73 exports.name = engine_name;
74 exports.Game = TicTacToe;
80 exports.meta = TicTacToe.meta;