1 const express = require("express");
3 const app = express.Router();
8 this.board = Array(9).fill(null);
10 this.next_client_id = 1;
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 add_client(response) {
26 const id = this.next_client_id;
27 this.clients.push({id: id,
29 this.next_client_id++;
35 this.clients = this.clients.filter(client => client.id !== id);
38 /* Send a string to all clients */
39 broadcast_string(str) {
40 this.clients.forEach(client => client.response.write(str + '\n'));
43 /* Send an event to all clients.
45 * An event has both a declared type and a separate data block.
46 * It also ends with two newlines (to mark the end of the event).
48 broadcast_event(type, data) {
49 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
52 broadcast_move(square) {
53 this.broadcast_event("move", square);
57 app.get('/', (request, response) => {
58 const game = request.game;
60 if (! request.session.nickname)
61 response.render('choose-nickname.html', { game_name: "Tic Tac Toe" });
63 response.render('tictactoe-game.html');
66 app.post('/move', (request, response) => {
67 const game = request.game;
68 const square = request.body.square;
70 const legal = game.add_move(square);
72 /* Inform this client whether the move was legal. */
73 response.send(JSON.stringify(legal));
75 /* And only if legal, inform all clients. */
79 game.broadcast_move(square);
82 app.get('/events', (request, response) => {
83 const game = request.game;
85 /* These headers will keep the connection open so we can stream events. */
87 "Content-type": "text/event-stream",
88 "Connection": "keep-alive",
89 "Cache-Control": "no-cache"
91 response.writeHead(200, headers);
93 /* Add this new client to our list of clients. */
94 const id = game.add_client(response);
96 /* And queue up cleanup to be triggered on client close. */
97 request.on('close', () => {
98 game.remove_client(id);
103 exports.name = "tictactoe";
104 exports.Game = TicTacToe;