X-Git-Url: https://git.cworth.org/git?p=empires-server;a=blobdiff_plain;f=game.js;h=86a0e70b96f311dc2133898e679c1afa619406a7;hp=20cd2411e2275ff8aef51e1c35a3772931815b6b;hb=2690233f317b87e7336b0404ae711837e726d5cf;hpb=ea14cbbefb26afd558aff8329d92f1a7b9442bac diff --git a/game.js b/game.js index 20cd241..86a0e70 100644 --- a/game.js +++ b/game.js @@ -1,30 +1,222 @@ +const no_team = { name: "" }; + +/* A single player can have multiple connections, (think, multiple + * browser windows with a common session cookie). */ +class Player { + constructor(id, session_id, name, connection) { + this.id = id; + this.session_id = session_id; + this.name = name; + this.connections = [connection]; + this.team = no_team; + } + + add_connection(connection) { + /* Don't add a duplicate connection if this player already has it. */ + for (let c of this.connections) { + if (c === connection) + return; + } + + this.connections.push(connection); + } + + /* Returns the number of remaining connections after this one is removed. */ + remove_connection(connection) { + this.connections.filter(c => c !== connection); + return this.connections.length; + } + + /* Send a string to all connections for this player. */ + send(data) { + this.connections.forEach(connection => connection.write(data)); + } + + info_json() { + return JSON.stringify({ + id: this.id, + name: this.name, + team: this.team.name, + score: this.score + }); + } +} + /* Base class providing common code for game engine implementations. */ class Game { - constructor(name) { - this.name = name; - this.clients = []; - this.next_client_id = 1; + constructor(id) { + this.id = id; + this.players = []; + this.players_by_session = {}; + this.next_player_id = 1; + this.teams = []; + this.state = { + team_to_play: no_team + }; + this.first_move = true; + + /* Send a comment to every connected client every 15 seconds. */ + setInterval(() => {this.broadcast_string(":");}, 15000); + } + + /* Suport for game meta-data. + * + * What we want here is an effectively static field that is + * accessible through either the class name (SomeGame.meta) or an + * instance (some_game.meta). To pull this off we do keep two copies + * of the data. But the game classes can just set SomeGame.meta once + * and then reference it either way. + */ + static set meta(data) { + /* This allows class access (SomeGame.meta) via the get method below. */ + this._meta = data; + + /* While this allows access via an instance (some_game.meta). */ + this.prototype.meta = data; + } + + static get meta() { + return this._meta; } - add_client(response) { - const id = this.next_client_id; - this.clients.push({id: id, - response: response}); - this.next_client_id++; + /* Just performs some checks for whether a move is definitely not + * legal (such as not the player's turn). A child class is expected + * to override this (and call super.add_move early!) to implement + * the actual logic for a move. */ + add_move(player, move) { - return id; + /* The checks here don't apply on the first move. */ + if (! this.first_move) { + + /* Discard any move asserting to be the first move if it's no + * longer the first move. This resolves the race condition if + * multiple players attempt to make the first move. */ + if (move.assert_first_move) { + return { legal: false, + message: "Your opponent beat you to the first move" }; + } + + /* Cannot move if you are not on a team. */ + if (player.team === no_team) + { + return { legal: false, + message: "You must be on a team to take a turn" }; + } + + /* Cannot move if it's not this player's team's turn. */ + if (player.team !== this.state.team_to_play) + { + return { legal: false, + message: "It's not your turn to move" }; + } + } + + return { legal: true }; } - remove_client(id) { - this.clients = this.clients.filter(client => client.id !== id); + /* Assign team only if player is unassigned. + * Return true if assignment made, false otherwise. */ + assign_player_to_team_perhaps(player, team) + { + if (player.team !== no_team) + return false; + + player.team = team; + this.broadcast_event("player-update", player.info_json()); + + return true; } - /* Send a string to all clients */ + /* This function is called after the child add_move has returned + * 'result' so that any generic processing can happen. + * + * In particular, we assign teams for a two-player game where a + * player assumed a team by making the first move. */ + post_move(player, result) + { + if (this.first_move && result.legal) { + this.first_move = false; + + this.assign_player_to_team_perhaps(player, this.teams[0]); + + /* Yes, start at 1 to skip teams[0] which we just assigned. */ + for (let i = 1; i < this.teams.length; i++) { + const other = this.players.find(p => (p !== player) && (p.team === no_team)); + if (!other) + return; + this.assign_player_to_team_perhaps(other, this.teams[i]); + } + } + } + + add_player(session, connection) { + /* First see if we already have a player object for this session. */ + const existing = this.players_by_session[session.id]; + if (existing) { + existing.add_connection(connection); + return existing; + } + + /* No existing player. Add a new one. */ + const id = this.next_player_id; + let nickname = session.nickname; + if (nickname === "") + nickname = "Guest"; + const nickname_orig = nickname; + + /* Ensure we don't have a name collision with a previous player. */ + let unique_suffix = 1; + while (this.players.find(player => player.name === nickname)) + { + nickname = `${nickname_orig}${unique_suffix.toString().padStart(2, '0')}`; + unique_suffix++; + } + + const player = new Player(id, session.id, nickname, connection); + + /* Broadcast before adding player to list (to avoid announcing the + * new player to itself). */ + const player_data = JSON.stringify({ id: player.id, name: player.name }); + this.broadcast_event("player-enter", player_data); + + this.players.push(player); + this.players_by_session[session.id] = player; + this.next_player_id++; + + /* After adding the player to the list, and if we are already past + * the first move, assign this player to the first team that + * doesn't already have a player assigned (if any). */ + if (! this.first_move) { + const have_players = Array(this.teams.length).fill(false); + this.players.forEach(p => { + if (p.team.id !== undefined) + have_players[p.team.id] = true; + }); + const first_empty = have_players.findIndex(i => i === false); + this.assign_player_to_team_perhaps(player, this.teams[first_empty]); + } + + return player; + } + + /* Drop a connection object from a player, and if it's the last one, + * then drop that player from the game's list of players. */ + remove_player_connection(player, connection) { + const remaining = player.remove_connection(connection); + if (remaining === 0) { + const player_data = JSON.stringify({ id: player.id }); + this.players.filter(p => p !== player); + delete this.players_by_session[player.session_id]; + this.broadcast_event("player-exit", player_data); + } + } + + /* Send a string to all players */ broadcast_string(str) { - this.clients.forEach(client => client.response.write(str + '\n')); + this.players.forEach(player => player.send(str + '\n')); } - /* Send an event to all clients. + /* Send an event to all players. * * An event has both a declared type and a separate data block. * It also ends with two newlines (to mark the end of the event). @@ -33,6 +225,10 @@ class Game { this.broadcast_string(`event: ${type}\ndata: ${data}\n`); } + broadcast_event_object(type, obj) { + this.broadcast_event(type, JSON.stringify(obj)); + } + handle_events(request, response) { /* These headers will keep the connection open so we can stream events. */ const headers = { @@ -42,13 +238,80 @@ class Game { }; response.writeHead(200, headers); - /* Add this new client to our list of clients. */ - const id = this.add_client(response); + /* 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_client(id); + 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`); + + /* As well as player-enter events for all existing players. */ + this.players.filter(p => p !== player).forEach(p => { + response.write(`event: player-enter\ndata: ${p.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_name = 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_name !== null && (player.team.name !== team_name)) + { + if (team_name === "") { + player.team = no_team; + updated = true; + } else { + const index = this.teams.findIndex(t => t.name === team_name); + if (index >= 0) { + player.team = this.teams[index]; + updated = true; + } + } + } + + if (updated) + this.broadcast_event("player-update", player.info_json()); + + response.send(""); + } + + broadcast_move(move) { + this.broadcast_event("move", JSON.stringify(move)); } }