"use strict"; const express = require("express"), crypto = require("crypto"), { readFile, writeFile } = require("fs").promises; let gameDB; require("../db/games").then(function(db) { gameDB = db; }); const router = express.Router(); function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } const assetData = { tiles: [ { type: "wood", y: 0. / 4. }, { type: "wood", y: 1. / 4. }, { type: "wood", y: 2. / 4. }, { type: "wood", y: 3. / 4. }, { type: "wheat", y: 0. / 4. }, { type: "wheat", y: 1. / 4. }, { type: "wheat", y: 2. / 4. }, { type: "wheat", y: 3. / 4. }, { type: "stone", y: 0. / 4. }, { type: "stone", y: 1. / 4. }, { type: "stone", y: 2. / 4. }, { type: "sheep", y: 0. / 4. }, { type: "sheep", y: 1. / 4. }, { type: "sheep", y: 2. / 4. }, { type: "sheep", y: 3. / 4. }, { type: "brick", y: 0. / 4. }, { type: "brick", y: 1. / 4. }, { type: "brick", y: 2. / 4. }, { type: "robber", y: 0 } ], pips: [ { roll: 7, pips: 0, y: 3. / 6., x: 0. / 6. }, { roll: 5, pips: 4, y: 0. / 6., x: 0. / 6. }, { roll: 2, pips: 1, y: 0. / 6., x: 1. / 6. }, { roll: 6, pips: 5, y: 0. / 6., x: 2. / 6. }, { roll: 3, pips: 2, y: 0. / 6., x: 3. / 6. }, { roll: 8, pips: 5, y: 0. / 6., x: 4. / 6. }, { roll: 10, pips: 3, y: 0. / 6., x: 5. / 6. }, { roll: 9, pips: 4, y: 1. / 6., x: 0. / 6. }, { roll: 12, pips: 1, y: 1. / 6., x: 1. / 6. }, { roll: 11, pips: 2, y: 1. / 6., x: 2. / 6. }, { roll: 4, pips: 3, y: 1. / 6., x: 3. / 6. }, { roll: 8, pips: 5, y: 1. / 6., x: 4. / 6. }, { roll: 10, pips: 3, y: 1. / 6., x: 5. / 6. }, { roll: 9, pips: 4, y: 2. / 6., x: 0. / 6. }, { roll: 4, pips: 3, y: 2. / 6., x: 1. / 6. }, { roll: 5, pips: 4, y: 2. / 6., x: 2. / 6. }, { roll: 6, pips: 6, y: 2. / 6., x: 3. / 6. }, { roll: 3, pips: 2, y: 2. / 6., x: 4. / 6. }, { roll: 11, pips: 2, y: 2. / 6., x: 5. / 6. } ], borders: [ { file: 'borders-1.6.png', left: "sheep", right: "bank" }, { file: 'borders-2.1.png', center: "sheep" }, { file: 'borders-3.2.png', left: "wheat", right: "bank" }, { file: 'borders-4.3.png', center: "wood" }, { file: 'borders-5.4.png', left: "sheep", right: "bank" }, { file: 'borders-6.5.png', center: "bank" } ], developmentCards: [] }; for (let i = 0; i < 14; i++) { assetData.developmentCards.push("knight"); } for (let i = 0; i < 6; i++) { assetData.developmentCards.push("progress"); } for (let i = 0; i < 5; i++) { assetData.developmentCards.push("victoryPoint"); } const games = {}; const roll = (game, session) => { let message; const player = session.player, name = session.name ? session.name : "Unnamed"; switch (game.state) { case "lobby": return `Rolling dice in the lobby is not allowed!`; case "game-order": if (player.order) { retrun = `Player ${name} already rolled for order.`; } player.order = game.dice[0]; message = `${name} rolled ${game.dice[0]} for play order.`; game.chat.push({ date: Date.now(), message: message }); break; case "in-game": game.dice = [ Math.ceil(Math.random() * 6), Math.ceil(Math.random() * 6) ]; message = `${name} rolled ${game.dice[0] + game.dice[1]}.`; game.chat.push({ date: Date.now(), message: message }); return; default: return `Invalid game state (${game.state}) in roll.`; } }; const getPlayer = (game, color) => { if (!game) { return { roads: 15, cities: 4, settlements: 5, points: 0, status: "Not active", lastActive: 0, order: 0 }; } return game.players[color]; }; const getSession = (game, session) => { if (!game.sessions) { game.sessions = {}; } /* If this session is not yet in the game, * add it and set the player's name */ if (!(session in game.sessions)) { game.sessions[session] = { name: undefined, player: undefined }; } return game.sessions[session]; }; const loadGame = async (id) => { if (/^\.|\//.exec(id)) { return undefined; } if (id in games) { return games[id]; } let game = await readFile(`games/${id}`) .catch(() => { return; }); if (!game) { game = createGame(id); } else { try { game = JSON.parse(game); } catch (error) { console.error(error, game); return null; } } /* Reconnect session player colors to the player objects */ for (let id in game.sessions) { const session = game.sessions[id]; if (session.color && session.color in game.players) { session.player = game.players[session.color]; } else { session.color = undefined; session.player = undefined; } } games[id] = game; return game; }; const adminActions = (game, action, value) => { switch (action) { case "kick": let color; switch (value) { case 'orange': color = 'O'; break; case 'red': color = 'R'; break; case 'blue': color = 'B'; break; case 'white': color = 'W'; break; } if (!color) { return `Unable to find player ${value}` } const player = game.players[color]; for (let id in game.sessions) { const session = game.sessions[id]; if (session.player !== player) { continue; } console.log(`Kicking ${value} from ${game.id}.`); const name = session.name ? `${session.name} (${color})` : color; game.chat.push({ date: Date.now(), message: `${name} has been kicked from game.` }); session.player = undefined; return; } return `Unable to find active session for ${color} (${value})`; default: return `Invalid admin action ${action}.`; } }; const setPlayerName = (game, session, name) => { if (session.color) { return `You cannot change your name while you are in game.`; } /* Check to ensure name is not already in use */ if (game && name) for (let key in game.sessions) { const tmp = game.sessions[key]; if (tmp.name && tmp.name.toLowerCase() === name.toLowerCase()) { return `${name} is already taken.`; } } const old = session.name ? session.name : "Unknown"; let message; session.name = name; if (name) { message = `${old} is now known as ${name}.`; } else { message = `${old} no longer has a name.`; } game.chat.push({ date: Date.now(), message: message }); } const setPlayerColor = (game, session, color) => { if (!game) { return `No game found`; } const name = session.name, player = session.player; /* Selecting the same color is a NO-OP */ if (session.color === color) { return; } if (player) { /* Deselect currently active player for this session */ player.status = 'Not active'; player.lastActive = 0; game.chat.push({ date: Date.now(), message: `${session.color} is no longer claimed.` }); session.player = undefined; session.color = undefined; } /* Verify the player has a name set */ if (!name) { return `You may only select a player when you have set your name.`; } /* If the player is not selecting a color, then return */ if (!color) { return; } /* Verify selection is valid */ if (!(color in game.players)) { return `An invalid player selection was attempted.`; } /* Verify selection is not already taken */ for (let key in game.sessions) { const tmp = game.sessions[key].player; if (tmp && tmp.color === color) { return `${game.sessions[key].name} already has ${color}`; } } /* All good -- set this player to requested selection */ session.player = getPlayer(game, color); session.player.status = `Active`; session.player.lastActive = Date.now(); session.color = color; game.chat.push({ date: Date.now(), message: `${color} is now '${session.name}'.` }); }; router.put("/:id/:action/:value?", async (req, res) => { const { action, id } = req.params, value = req.params.value ? req.params.value : ""; console.log(`PUT games/${id}/${action}/${value}`); const game = await loadGame(id); if (!game) { const error = `Game not found and cannot be created: ${id}`; return res.status(404).send(error); } let error; if ('private-token' in req.headers) { if (req.headers['private-token'] !== req.app.get('admin')) { error = `Invalid admin credentials.`; } else { error = adminActions(game, action, value); } return sendGame(req, res, game, error); } const session = getSession(game, req.session.id); switch (action) { case 'player-name': error = setPlayerName(game, session, value); return sendGame(req, res, game, error); case 'player-selected': error = setPlayerColor(game, session, value); return sendGame(req, res, game, error); } if (!session.player) { error = `Player must have an active color.`; return sendGame(req, res, game, error); } const name = session.name; switch (action) { case "roll": error = roll(game, session); break; case "shuffle": if (game.state !== "lobby") { error = `Game no longer in lobby (${game.state}). Can not shuffle board.`; } if (!error && game.turns > 0) { error = `Game already in progress (${game.turns} so far!) and cannot be shuffled.`; } if (!error) { shuffleBoard(game); const message = `${name} requested a new board.`; game.chat.push({ date: Date.now(), message: message }); console.log(message); } break case "state": const state = value; if (!state) { error = `Invalid state.`; } else if (state != game.state) { game.state = state; const message = `${name} set game state to ${state}.`; game.chat.push({ date: Date.now(), message: message }); } break; } return sendGame(req, res, game, error); }) router.get("/:id", async (req, res/*, next*/) => { const { id } = req.params; console.log("GET games/" + id); let game = await loadGame(id); if (game) { return sendGame(req, res, game) } game = createGame(id); return sendGame(req, res, game); }); router.put("/:id", (req, res/*, next*/) => { const { id } = req.params; console.log("PUT games/" + id); if (!(id in games)) { const error = `Game not found: ${req.params.id}`; return res.status(404).send(error); } const game = games[id], changes = req.body; for (let change in changes) { switch (change) { case "chat": console.log("Chat change."); game.chat.push({ from: changes.chat.player, date: Date.now(), message: changes.chat.message }); if (game.chat.length > 10) { game.chat.splice(0, game.chat.length - 10); } break; } } return sendGame(req, res, game); }); const sendGame = async (req, res, game, error) => { let active = 0; for (let color in game.players) { const player = game.players[color]; active += ((player.status && player.status != 'Not active') ? 1 : 0); } if (active < 2 && game.state != 'lobby' && game.state != 'invalid') { let message = "Insufficient players in game. Setting back to lobby." game.chat.push({ date: Date.now(), message: message }); console.log(message); game.state = 'lobby'; } let session; if (req.session) { session = getSession(game, req.session.id); session.lastActive = Date.now(); } else { session = { name: "command line" }; } /* Shallow copy game, filling its sessions with a shallow copy of sessions so we can then * delete the player field from them */ const reducedGame = Object.assign({}, game, { sessions: {} }); for (let id in game.sessions) { const reduced = Object.assign({}, game.sessions[id]); if (reduced.player) { delete reduced.player; } reducedGame.sessions[id] = reduced; } await writeFile(`games/${game.id}`, JSON.stringify(reducedGame, null, 2)) .catch((error) => { console.error(`Unable to write to games/${game.id}`); console.error(error); }); /* Do not send session-id as those are secrets */ const sessions = []; for (let id in reducedGame.sessions) { const reduced = reducedGame.sessions[id]; sessions.push(reduced); } const playerGame = Object.assign({}, reducedGame, { timestamp: Date.now(), status: error ? error : "success", name: session.name, color: session.color, sessions: sessions }); return res.status(200).send(playerGame); } const createGame = (id) => { id = id ? id : crypto.randomBytes(8).toString('hex'); const game = { startTime: Date.now(), turns: 0, state: "lobby", /* lobby, in-game, finished */ tiles: [], pips: [], borders: [], tokens: [], players: { R: getPlayer(), O: getPlayer(), B: getPlayer(), W: getPlayer() }, developmentCards: assetData.developmentCards.slice(), dice: [ 0, 0 ], sheep: 19, ore: 19, wool: 19, brick: 19, wheat: 19, longestRoad: null, largestArmy: null, chat: [ { date: Date.now(), message: `New game started for ${id}` } ], id: id }; games[game.id] = game; shuffleBoard(game); console.log(`New game created: ${game.id}`); return game; }; router.post("/:id?", (req, res/*, next*/) => { console.log("POST games/"); const { id } = req.params; if (id && id in games) { const error = `Can not create new game for ${id} -- it already exists.` console.error(error); return res.status(400).send(error); } const game = createGame(id); return sendGame(req, res, game); }); const shuffleBoard = (game) => { [ "tiles", "pips", "borders" ].forEach((field) => { game[field] = [] for (let i = 0; i < assetData[field].length; i++) { game[field].push(i); } /* Shuffle an array of indexes */ shuffle(game[field]); /* Convert from an index array to a full array */ for (let i = 0; i < assetData[field].length; i++) { game[field][i] = assetData[field][game[field][i]]; } }); shuffle(game.developmentCards) } /* return gameDB.sequelize.query("SELECT " + "photos.*,albums.path AS path,photohashes.hash,modified,(albums.path || photos.filename) AS filepath FROM photos " + "LEFT JOIN albums ON albums.id=photos.albumId " + "LEFT JOIN photohashes ON photohashes.photoId=photos.id " + "WHERE photos.id=:id", { replacements: { id: id }, type: gameDB.Sequelize.QueryTypes.SELECT, raw: true }).then(function(photos) { if (photos.length == 0) { return null; } */ if (0) { router.get("/*", (req, res/*, next*/) => { return gameDB.sequelize.query(query, { replacements: replacements, type: gameDB.Sequelize.QueryTypes.SELECT }).then((photos) => { }); }); } module.exports = router;