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);
14 this.next_client_id = 1;
17 /* Returns Boolean indicating whether move was legal and added. */
19 /* Cannot move to an occupied square. */
20 if (this.board[square])
23 this.board[square] = 'X';
24 this.moves.push(square);
29 add_client(response) {
30 const id = this.next_client_id;
31 this.clients.push({id: id,
33 this.next_client_id++;
39 this.clients = this.clients.filter(client => client.id !== id);
42 /* Send a string to all clients */
43 broadcast_string(str) {
44 this.clients.forEach(client => client.response.write(str + '\n'));
47 /* Send an event to all clients.
49 * An event has both a declared type and a separate data block.
50 * It also ends with two newlines (to mark the end of the event).
52 broadcast_event(type, data) {
53 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
56 broadcast_move(square) {
57 this.broadcast_event("move", square);
61 router.get('/', (request, response) => {
62 const game = request.game;
64 if (! request.session.nickname)
65 response.render('choose-nickname.html', { game_name: "Tic Tac Toe" });
67 response.render('tictactoe-game.html');
70 router.post('/move', (request, response) => {
71 const game = request.game;
72 const square = request.body.square;
74 const legal = game.add_move(square);
76 /* Inform this client whether the move was legal. */
77 response.send(JSON.stringify(legal));
79 /* And only if legal, inform all clients. */
83 game.broadcast_move(square);
86 router.get('/events', (request, response) => {
87 const game = request.game;
89 /* These headers will keep the connection open so we can stream events. */
91 "Content-type": "text/event-stream",
92 "Connection": "keep-alive",
93 "Cache-Control": "no-cache"
95 response.writeHead(200, headers);
97 /* Add this new client to our list of clients. */
98 const id = game.add_client(response);
100 /* And queue up cleanup to be triggered on client close. */
101 request.on('close', () => {
102 game.remove_client(id);
106 exports.router = router;
107 exports.name = engine_name;
108 exports.Game = TicTacToe;