const express = require("express");
const Game = require("./game.js");
+const MAX_PROMPT_ITEMS = 20;
+
+/* This time parameter specifies a time period in which a phase will
+ * not be considered idle in any circumstance. That is, this should be
+ * a reasonable time in which any "active" player should have at least
+ * started interacting with the current phase.
+ *
+ * Specified in seconds
+ */
+const PHASE_MINIMUM_TIME = 30;
+
+/* This parameter gives the amount of time that the game will wait to
+ * see activity from pending players. If this amount of time passes
+ * with no activity from any of them, the server will emit an "idle"
+ * event which will let clients issue a vote to end the current phase.
+ *
+ * Specified in seconds
+ */
+const PHASE_IDLE_TIMEOUT = 30;
+
class Empathy extends Game {
constructor(id) {
super(id);
this.state = {
- prompts: []
+ prompts: [],
+ active_prompt: null,
+ players_answered: [],
+ players_answering: new Set(),
+ answering_idle: false,
+ end_answers: new Set(),
+ ambiguities: null,
+ players_judged: [],
+ players_judging: new Set(),
+ judging_idle: false,
+ end_judging: new Set(),
+ scores: null
};
+ this.answers = [];
+ this.answering_idle_timer = 0;
+ this.answering_start_time_ms = 0;
+ this.judging_idle_timer = 0;
+ this.judging_start_time_ms = 0;
this.next_prompt_id = 1;
+ this.equivalencies = {};
+ }
+
+ reset() {
+
+ /* Before closing out the current round, we accumulate that score
+ * for each player into their runnning total. */
+ for (let score of this.state.scores.scores) {
+ const player = this.players.find(p => p.name === score.player);
+ if (player.score)
+ player.score += score.score;
+ else
+ player.score = score.score;
+
+ /* And broadcast that new score out. */
+ this.broadcast_event('player-update', player.info_json());
+ }
+
+ /* Now that we're done with the active prompt, we remove it from
+ * the list of prompts and also remove any prompts that received
+ * no votes. This keeps the list of prompts clean.
+ */
+ const active_id = this.state.active_prompt.id;
+ this.state.prompts =
+ this.state.prompts.filter(
+ p => p.id !== active_id && p.votes.length > 0
+ );
+
+ this.state.active_prompt = null;
+ this.state.players_answered = [];
+ this.state.players_answering = new Set();
+ this.state.answering_idle = false;
+ this.state.end_answers = new Set();
+ this.state.ambiguities = null;
+ this.state.players_judged = [];
+ this.state.players_judging = new Set();
+ this.state.judging_idle = false;
+ this.state.end_judging = new Set();
+ this.state.scores = null;
+
+ this.answers = [];
+ if (this.answering_idle_timer) {
+ clearTimeout(this.answering_idle_timer);
+ }
+ this.answering_idle_timer = 0;
+ this.answering_start_time_ms = 0;
+ if (this.judging_idle_timer) {
+ clearTimeout(this.judging_idle_timer);
+ }
+ this.judging_idle_timer = 0;
+ this.judging_start_time_ms = 0;
+ this.equivalencies = {};
+
+ this.broadcast_event_object('game-state', this.state);
+ }
+
+ add_prompt(items, prompt_string) {
+ if (items > MAX_PROMPT_ITEMS)
+ return {
+ valid: false,
+ message: `Maximum number of items is ${MAX_PROMPT_ITEMS}`
+ };
+
+ const prompt = new Prompt(this.next_prompt_id, items, prompt_string);
+ this.next_prompt_id++;
+
+ this.state.prompts.push(prompt);
+
+ this.broadcast_event_object('prompt', prompt);
+
+ return {
+ valid: true,
+ id: prompt.id
+ };
+ }
+
+ /* Returns true if vote toggled, false for player or prompt not found */
+ toggle_vote(prompt_id, session_id) {
+ const player = this.players_by_session[session_id];
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt || ! player)
+ return false;
+
+ prompt.toggle_vote(player.name);
+
+ this.broadcast_event_object('prompt', prompt);
+
+ return true;
+ }
+
+ /* Returns true on success, false for prompt not found. */
+ start(prompt_id) {
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt)
+ return false;
+
+ /* Ignore any start request that comes in while a prompt is
+ * already being played. */
+ if (this.state.active_prompt)
+ return false;
+
+ this.state.active_prompt = prompt;
+
+ this.broadcast_event_object('start', prompt);
+
+ return true;
+ }
+
+ receive_answer(prompt_id, session_id, answers) {
+ const player = this.players_by_session[session_id];
+ if (! player)
+ return { valid: false, message: "Player not found" };
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt)
+ return { valid: false, message: "Prompt not found" };
+
+ if (prompt !== this.state.active_prompt)
+ return { valid: false, message: "Prompt no longer active" };
+
+ /* Save the complete answers for our own use later. */
+ this.answers.push({
+ player: player,
+ answers: answers
+ });
+
+ /* Update state (to be sent out to any future clients) */
+ this.state.players_answering.delete(player.name);
+ this.state.players_answered.push(player.name);
+
+ /* And notify all players that this player has answered. */
+ this.broadcast_event_object('player-answered', player.name);
+
+ /* If no players are left in the answering list then we don't need
+ * to wait for the answering_idle_timer to fire, because a person
+ * who isn't there obviously can't be typing. So we can broadcast
+ * the idle event right away. Note that we do this only if the
+ * answering phase has been going for a while to avoid the case of
+ * the first player being super fast and emptying the
+ * players_answering list before anyone else even got in.
+ */
+ if (this.state.players_answering.size === 0 &&
+ ((Date.now() - this.answering_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
+ {
+ this.broadcast_event_object('answering-idle', true);
+ }
+
+ return { valid: true };
+ }
+
+ receive_answering(prompt_id, session_id) {
+ const player = this.players_by_session[session_id];
+ if (! player)
+ return { valid: false, message: "Player not found" };
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt)
+ return { valid: false, message: "Prompt not found" };
+
+ if (prompt !== this.state.active_prompt)
+ return { valid: false, message: "Prompt no longer active" };
+
+ if (this.answering_idle_timer) {
+ clearTimeout(this.answering_idle_timer);
+ this.ansering_idle_timer = 0;
+ }
+ if (! this.state.answering_idle) {
+ this.answering_idle_timer = setTimeout(() => {
+ this.state.answering_idle = true;
+ this.broadcast_event_object('answering-idle', true);
+ }, PHASE_IDLE_TIMEOUT * 1000);
+ }
+
+ if (this.answering_start_time_ms === 0)
+ this.answering_start_time_ms = Date.now();
+
+ /* Notify all players that this player is actively answering. */
+ this.state.players_answering.add(player.name);
+ this.broadcast_event_object('player-answering', player.name);
+
+ return { valid: true };
+ }
+
+ /* Returns true if vote toggled, false for player or prompt not found */
+ toggle_end_answers(prompt_id, session_id) {
+ const player = this.players_by_session[session_id];
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt || ! player)
+ return false;
+
+ if (this.state.end_answers.has(player.name)) {
+ this.state.end_answers.delete(player.name);
+ this.broadcast_event_object('unvote-end-answers', player.name);
+ } else {
+ this.state.end_answers.add(player.name);
+ this.broadcast_event_object('vote-end-answers', player.name);
+ }
+
+ return true;
+ }
+
+ perform_judging() {
+ const word_map = {};
+
+ for (let a of this.answers) {
+ for (let word of a.answers) {
+ const key = this.canonize(word);
+ word_map[key] = word;
+ }
+ }
+
+ this.state.ambiguities = Object.values(word_map).sort((a,b) => {
+ return a.toLowerCase().localeCompare(b.toLowerCase());
+ });
+
+ if (this.judging_start_time_ms === 0) {
+ this.judging_start_time_ms = Date.now();
+ }
+
+ this.broadcast_event_object('ambiguities', this.state.ambiguities);
+ }
+
+ receive_judged(prompt_id, session_id, word_groups) {
+ const player = this.players_by_session[session_id];
+ if (! player)
+ return { valid: false, message: "Player not found" };
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt)
+ return { valid: false, message: "Prompt not found" };
+
+ if (prompt !== this.state.active_prompt)
+ return { valid: false, message: "Prompt no longer active" };
+
+ /* Each player submits some number of groups of answers that
+ * should be considered equivalent. The server expands that into
+ * the set of pair-wise equivalencies that are expressed. The
+ * reason for that is so that the server can determine which
+ * pair-wise equivalencies have majority support.
+ */
+ for (let group of word_groups) {
+
+ for (let i = 0; i < group.length - 1; i++) {
+ for (let j = i + 1; j < group.length; j++) {
+ let eq = [group[i], group[j]];
+
+ /* Put the two words into a reliable order so that we don't
+ * miss a pair of equivalent equivalencies just because they
+ * happen to be in the opposite order. */
+ if (eq[0].localeCompare(eq[1]) > 0) {
+ eq = [group[j], group[i]];
+ }
+
+ const key=`${this.canonize(eq[0])}:${this.canonize(eq[1])}`;
+
+ const exist = this.equivalencies[key];
+ if (exist) {
+ exist.count++;
+ } else {
+ this.equivalencies[key] = {
+ count: 1,
+ words: eq
+ };
+ }
+
+ }
+ }
+ }
+
+ /* Update state (to be sent out to any future clients) */
+ this.state.players_judging.delete(player.name);
+ this.state.players_judged.push(player.name);
+
+ /* And notify all players this this player has judged. */
+ this.broadcast_event_object('player-judged', player.name);
+
+ /* If no players are left in the judging list then we don't need
+ * to wait for the judging_idle_timer to fire, because a person
+ * who isn't there obviously can't be judging. So we can broadcast
+ * the idle event right away. Note that we do this only if the
+ * judging phase has been going for a while to avoid the case of
+ * the first player being super fast and emptying the
+ * players_judging list before anyone else even got in.
+ */
+ if (this.state.players_judging.size === 0 &&
+ ((Date.now() - this.judging_start_time_ms) / 1000) > PHASE_MINIMUM_TIME)
+ {
+ this.broadcast_event_object('judging-idle', true);
+ }
+
+ return { valid: true };
+ }
+
+ receive_judging(prompt_id, session_id) {
+
+ const player = this.players_by_session[session_id];
+ if (! player)
+ return { valid: false, message: "Player not found" };
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt)
+ return { valid: false, message: "Prompt not found" };
+
+ if (prompt !== this.state.active_prompt)
+ return { valid: false, message: "Prompt no longer active" };
+
+ if (this.judging_idle_timer) {
+ clearTimeout(this.judging_idle_timer);
+ this.judging_idle_timer = 0;
+ }
+ if (! this.state.judging_idle) {
+ this.judging_idle_timer = setTimeout(() => {
+ this.state.judging_idle = true;
+ this.broadcast_event_object('judging-idle', true);
+ }, PHASE_IDLE_TIMEOUT * 1000);
+ }
+
+ /* Notify all players this this player is actively judging. */
+ this.state.players_judging.add(player.name);
+ this.broadcast_event_object('player-judging', player.name);
+
+ return { valid: true };
+ }
+
+ /* Returns true if vote toggled, false for player or prompt not found */
+ toggle_end_judging(prompt_id, session_id) {
+ const player = this.players_by_session[session_id];
+
+ const prompt = this.state.prompts.find(p => p.id === prompt_id);
+ if (! prompt || ! player)
+ return false;
+
+ if (this.state.end_judging.has(player.name)) {
+ this.state.end_judging.delete(player.name);
+ this.broadcast_event_object('unvote-end-judging', player.name);
+ } else {
+ this.state.end_judging.add(player.name);
+ this.broadcast_event_object('vote-end-judging', player.name);
+ }
+
+ return true;
+ }
+
+ canonize(word) {
+ return word.trim().toLowerCase();
+ }
+
+ compute_scores() {
+ const word_submitters = {};
+
+ /* Perform a (non-strict) majority ruling on equivalencies,
+ * dropping all that didn't get enough votes. */
+ const quorum = Math.floor((this.players.length + 1)/2);
+ const agreed_equivalencies = Object.values(this.equivalencies).filter(
+ eq => eq.count >= quorum);
+
+ /* And with that agreed set of equivalencies, construct the full
+ * groups. */
+ const word_maps = {};
+
+ for (let e of agreed_equivalencies) {
+ const word0_canon = this.canonize(e.words[0]);
+ const word1_canon = this.canonize(e.words[1]);
+ let group = word_maps[word0_canon];
+ if (! group)
+ group = word_maps[word1_canon];
+ if (! group)
+ group = { words: [], players: new Set()};
+
+ if (! word_maps[word0_canon]) {
+ word_maps[word0_canon] = group;
+ group.words.push(e.words[0]);
+ }
+
+ if (! word_maps[word1_canon]) {
+ word_maps[word1_canon] = group;
+ group.words.push(e.words[1]);
+ }
+ }
+
+ /* Now go through answers from each player and add the player
+ * to the set corresponding to each word group. */
+ for (let a of this.answers) {
+ for (let word of a.answers) {
+ const word_canon = this.canonize(word);
+ /* If there's no group yet, this is a singleton word. */
+ if (word_maps[word_canon]) {
+ word_maps[word_canon].players.add(a.player);
+ } else {
+ const group = { words: [word], players: new Set() };
+ group.players.add(a.player);
+ word_maps[word_canon] = group;
+ }
+ }
+ }
+
+ /* Now that we've assigned the players to these word maps, we now
+ * want to collapse the groups down to a single array of
+ * word_groups.
+ *
+ * The difference between "word_maps" and "word_groups" is that
+ * the former has a property for every word that maps to a group,
+ * (so if you iterate over the keys you will see the same group
+ * multiple times). In contrast, iterating over"word_groups" will
+ * have you visit each group only once. */
+ const word_groups = Object.entries(word_maps).filter(
+ entry => entry[0] === this.canonize(entry[1].words[0]))
+ .map(entry => entry[1]);
+
+ /* Now, go through each word group and assign the scores out to
+ * the corresponding players.
+ *
+ * Note: We do this by going through the word groups, (as opposed
+ * to the list of words from the players again), specifically to
+ * avoid giving a player points for a wrod group twice (in the
+ * case where a player submits two different words that the group
+ * ends up judging as equivalent).
+ */
+ this.players.forEach(p => p.round_score = 0);
+ for (let group of word_groups) {
+ group.players.forEach(p => p.round_score += group.players.size);
+ }
+
+ const scores = this.players.map(p => {
+ return {
+ player: p.name,
+ score: p.round_score
+ };
+ });
+
+ scores.sort((a,b) => {
+ return b.score - a.score;
+ });
+
+ /* Put the word groups into a form the client can consume.
+ */
+ const words_submitted = word_groups.map(
+ group => {
+ return {
+ word: group.words.join('/'),
+ players: Array.from(group.players).map(p => p.name)
+ };
+ }
+ );
+
+ words_submitted.sort((a,b) => {
+ return b.players.length - a.players.length;
+ });
+
+ /* Put this round's scores into the game state object so it will
+ * be sent to any new clients that join. */
+ this.state.scores = {
+ scores: scores,
+ words: words_submitted
+ };
+
+ /* And broadcast the scores to all connected clients. */
+ this.broadcast_event_object('scores', this.state.scores);
}
}
this.votes = [];
}
- add_vote(player_name) {
+ toggle_vote(player_name) {
if (this.votes.find(v => v === player_name))
- return;
-
- this.votes.push(player_name);
+ this.votes = this.votes.filter(v => v !== player_name);
+ else
+ this.votes.push(player_name);
}
}
router.post('/prompts', (request, response) => {
const game = request.game;
- const prompt = new Prompt(game.next_prompt_id,
- request.body.items,
- request.body.prompt);
- game.next_prompt_id++;
+ const result = game.add_prompt(request.body.items, request.body.prompt);
- game.state.prompts.push(prompt);
-
- game.broadcast_event_object('prompt', prompt);
+ response.json(result);
});
router.post('/vote/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ if (game.toggle_vote(prompt_id, request.session.id))
+ response.send('');
+ else
+ response.sendStatus(404);
+});
+
+router.post('/start/:prompt_id([0-9]+)', (request, response) => {
const game = request.game;
- const player = game.players_by_session[request.session.id];
+ const prompt_id = parseInt(request.params.prompt_id, 10);
- prompt = game.state.prompts.find(p => p.id === prompt_id);
- if (! prompt || ! player) {
+ if (game.start(prompt_id))
+ response.send('');
+ else
response.sendStatus(404);
- return;
- }
+});
- prompt.add_vote(player.name);
+router.post('/answer/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
+ const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ const result = game.receive_answer(prompt_id,
+ request.session.id,
+ request.body.answers);
+ response.json(result);
+
+ /* If every registered player has answered, then there's no need to
+ * wait for anything else. */
+ if (game.state.players_answered.length >= game.players.length)
+ game.perform_judging();
+});
+
+router.post('/answering/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
+ const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ const result = game.receive_answering(prompt_id,
+ request.session.id);
+ response.json(result);
+});
- game.broadcast_event_object('prompt', prompt);
+router.post('/end-answers/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
+ const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ if (game.toggle_end_answers(prompt_id, request.session.id))
+ response.send('');
+ else
+ response.sendStatus(404);
+
+ /* The majority rule here includes all players that have answered as
+ * well as all that have started typing. */
+ const players_involved = (game.state.players_answered.length +
+ game.state.players_answering.size);
+
+ if (game.state.end_answers.size > players_involved / 2)
+ game.perform_judging();
+});
+
+router.post('/judged/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
+ const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ const result = game.receive_judged(prompt_id,
+ request.session.id,
+ request.body.word_groups);
+ response.json(result);
+
+ /* If every registered player has judged, then there's no need to
+ * wait for anything else. */
+ if (game.state.players_judged.length >= game.players.length)
+ game.compute_scores();
+});
+
+router.post('/judging/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
+ const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ const result = game.receive_judging(prompt_id,
+ request.session.id);
+ response.json(result);
+});
+
+router.post('/end-judging/:prompt_id([0-9]+)', (request, response) => {
+ const game = request.game;
+ const prompt_id = parseInt(request.params.prompt_id, 10);
+
+ if (game.toggle_end_judging(prompt_id, request.session.id))
+ response.send('');
+ else
+ response.sendStatus(404);
+
+ if (game.state.end_judging.size > (game.state.players_answered.length / 2))
+ game.compute_scores();
+});
+
+router.post('/reset', (request, response) => {
+ const game = request.game;
+ game.reset();
- response.sendStatus(200);
+ response.send('');
});
Empathy.meta = {