]> git.cworth.org Git - lmno-server/blob - tictactoe.js
Add a minimal implementation of the TicTacToe game engine
[lmno-server] / tictactoe.js
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");
6
7 const app = express();
8 app.use(cors());
9 app.use(body_parser.urlencoded({ extended: false }));
10 app.use(body_parser.json());
11
12 nunjucks.configure("templates", {
13   autoescape: true,
14   express: app
15 });
16
17 class TicTacToe {
18   constructor() {
19     this.moves = [];
20     this.board = Array(9).fill(null);
21     this.clients = [];
22     this.next_client_id = 1;
23   }
24
25   /* Returns Boolean indicating whether move was legal and added. */
26   add_move(square) {
27     /* Cannot move to an occupied square. */
28     if (this.board[square])
29       return false;
30
31     this.board[square] = 'X';
32     this.moves.push(square);
33
34     return true;
35   }
36
37   add_client(response) {
38     const id = this.next_client_id;
39     this.clients.push({id: id,
40                        response: response});
41     this.next_client_id++;
42
43     return id;
44   }
45
46   remove_client(id) {
47     this.clients = this.clients.filter(client => client.id !== id);
48   }
49
50   /* Send a string to all clients */
51   broadcast_string(str) {
52     this.clients.forEach(client => client.response.write(str + '\n'));
53   }
54
55   /* Send an event to all clients.
56    *
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).
59    */
60   broadcast_event(type, data) {
61     this.broadcast_string(`event: ${type}\ndata: ${data}\n`);
62   }
63
64   broadcast_move(square) {
65     this.broadcast_event("move", square);
66   }
67 }
68
69 app.get('/', (request, response) => {
70   const game = request.game;
71
72   if (! request.session.nickname)
73     response.render('choose-nickname.html', { game_name: "Tic Tac Toe" });
74   else
75     response.render('tictactoe-game.html');
76 });
77
78 app.post('/move', (request, response) => {
79   const game = request.game;
80   const square = request.body.square;
81
82   const legal = game.add_move(square);
83
84   /* Inform this client whether the move was legal. */
85   response.send(JSON.stringify(legal));
86
87   /* And only if legal, inform all clients. */
88   if (! legal)
89     return;
90
91   game.broadcast_move(square);
92 });
93
94 app.get('/events', (request, response) => {
95   const game = request.game;
96
97   /* These headers will keep the connection open so we can stream events. */
98   const headers = {
99     "Content-type": "text/event-stream",
100     "Connection": "keep-alive",
101     "Cache-Control": "no-cache"
102   };
103   response.writeHead(200, headers);
104
105   /* Add this new client to our list of clients. */
106   const id = game.add_client(response);
107
108   /* And queue up cleanup to be triggered on client close. */
109   request.on('close', () => {
110     game.remove_client(id);
111   });
112 });
113
114 exports.app = app;
115 exports.name = "tictactoe";
116 exports.Game = TicTacToe;