+ handle_events(request, response) {
+ /* These headers will keep the connection open so we can stream events. */
+ const headers = {
+ "Content-type": "text/event-stream",
+ "Connection": "keep-alive",
+ "Cache-Control": "no-cache"
+ };
+ response.writeHead(200, headers);
+
+ /* Add this new player. */
+ const player = this.add_player(request.session, response);
+
+ /* And queue up cleanup to be triggered on client close. */
+ request.on('close', () => {
+ this.remove_player_connection(player, response);
+ });
+
+ /* Give the client the game-info event. */
+ const game_info_json = JSON.stringify({
+ id: this.id,
+ url: `${request.protocol}://${request.hostname}/${this.id}`
+ });
+ response.write(`event: game-info\ndata: ${game_info_json}\n\n`);
+
+ /* And the player-info event. */
+ response.write(`event: player-info\ndata: ${player.info_json()}\n\n`);
+
+ /* Finally, if this game class has a "state" property, stream that
+ * current state to the client. */
+ if (this.state) {
+ const state_json = JSON.stringify(this.state);
+ response.write(`event: game-state\ndata: ${state_json}\n\n`);
+ }
+ }
+
+ handle_player(request, response) {
+ const player = this.players_by_session[request.session.id];
+ const name = request.body.name;
+ const team = request.body.team;
+ var updated = false;
+ if (! player) {
+ response.sendStatus(404);
+ return;
+ }
+
+ if (name && (player.name !== name)) {
+ player.name = name;
+
+ /* In addition to setting the name within this game's player
+ * object, also set the name in the session. */
+ request.session.nickname = name;
+ request.session.save();
+
+ updated = true;
+ }
+
+ if (team !== null && (player.team !== team) &&
+ (team === "" || this.teams.includes(team)))
+ {
+ player.team = team;
+
+ updated = true;
+ }
+
+ if (updated)
+ this.broadcast_event("player-update", player.info_json());
+
+ response.send("");
+ }
+
+ broadcast_move(move) {
+ this.broadcast_event("move", move);
+ }
+