1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
4 const path = require("path");
5 const nunjucks = require("nunjucks");
9 app.use(body_parser.urlencoded({ extended: false }));
10 app.use(body_parser.json());
12 nunjucks.configure("templates", {
20 this.board = Array(9).fill(null);
22 this.next_client_id = 1;
25 /* Returns Boolean indicating whether move was legal and added. */
27 /* Cannot move to an occupied square. */
28 if (this.board[square])
31 this.board[square] = 'X';
32 this.moves.push(square);
37 add_client(response) {
38 const id = this.next_client_id;
39 this.clients.push({id: id,
41 this.next_client_id++;
47 this.clients = this.clients.filter(client => client.id !== id);
50 /* Send a string to all clients */
51 broadcast_string(str) {
52 this.clients.forEach(client => client.response.write(str + '\n'));
55 /* Send an event to all clients.
57 * An event has both a declared type and a separate data block.
58 * It also ends with two newlines (to mark the end of the event).
60 broadcast_event(type, data) {
61 this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
64 broadcast_move(square) {
65 this.broadcast_event("move", square);
69 app.get('/', (request, response) => {
70 const game = request.game;
72 if (! request.session.nickname)
73 response.render('choose-nickname.html', { game_name: "Tic Tac Toe" });
75 response.render('tictactoe-game.html');
78 app.post('/move', (request, response) => {
79 const game = request.game;
80 const square = request.body.square;
82 const legal = game.add_move(square);
84 /* Inform this client whether the move was legal. */
85 response.send(JSON.stringify(legal));
87 /* And only if legal, inform all clients. */
91 game.broadcast_move(square);
94 app.get('/events', (request, response) => {
95 const game = request.game;
97 /* These headers will keep the connection open so we can stream events. */
99 "Content-type": "text/event-stream",
100 "Connection": "keep-alive",
101 "Cache-Control": "no-cache"
103 response.writeHead(200, headers);
105 /* Add this new client to our list of clients. */
106 const id = game.add_client(response);
108 /* And queue up cleanup to be triggered on client close. */
109 request.on('close', () => {
110 game.remove_client(id);
115 exports.name = "tictactoe";
116 exports.Game = TicTacToe;