]> git.cworth.org Git - lmno-server/blob - tictactoe.js
Put add_client/remove_client and the various broadcast functions into Game
[lmno-server] / tictactoe.js
1 const express = require("express");
2 const Game = require("./game.js");
3
4 const engine_name = "tictactoe";
5
6 const router = express.Router();
7
8 class TicTacToe extends Game {
9   constructor() {
10     super(engine_name);
11     this.moves = [];
12     this.board = Array(9).fill(null);
13   }
14
15   /* Returns Boolean indicating whether move was legal and added. */
16   add_move(square) {
17     /* Cannot move to an occupied square. */
18     if (this.board[square])
19       return false;
20
21     this.board[square] = 'X';
22     this.moves.push(square);
23
24     return true;
25   }
26
27   broadcast_move(square) {
28     this.broadcast_event("move", square);
29   }
30 }
31
32 router.get('/', (request, response) => {
33   const game = request.game;
34
35   if (! request.session.nickname)
36     response.render('choose-nickname.html', { game_name: "Tic Tac Toe" });
37   else
38     response.render('tictactoe-game.html');
39 });
40
41 router.post('/move', (request, response) => {
42   const game = request.game;
43   const square = request.body.square;
44
45   const legal = game.add_move(square);
46
47   /* Inform this client whether the move was legal. */
48   response.send(JSON.stringify(legal));
49
50   /* And only if legal, inform all clients. */
51   if (! legal)
52     return;
53
54   game.broadcast_move(square);
55 });
56
57 router.get('/events', (request, response) => {
58   const game = request.game;
59
60   /* These headers will keep the connection open so we can stream events. */
61   const headers = {
62     "Content-type": "text/event-stream",
63     "Connection": "keep-alive",
64     "Cache-Control": "no-cache"
65   };
66   response.writeHead(200, headers);
67
68   /* Add this new client to our list of clients. */
69   const id = game.add_client(response);
70
71   /* And queue up cleanup to be triggered on client close. */
72   request.on('close', () => {
73     game.remove_client(id);
74   });
75 });
76
77 exports.router = router;
78 exports.name = engine_name;
79 exports.Game = TicTacToe;