node-go/packages/server/services/gameServices.js

64 lines
1.5 KiB
JavaScript
Raw Normal View History

const Game = require('./Game').Game;
2020-05-12 01:18:42 +00:00
const moveQueries = require('../data/queries/move');
const gamesInProgress = { }
const storeGame = (game) => {
2020-05-03 06:00:20 +00:00
gamesInProgress[game.id] = Game(game);
2020-05-12 01:18:42 +00:00
return gamesInProgress[game.id];
}
2020-05-03 06:00:20 +00:00
const initGame = ({id, gameRecord = [], ...gameData}) => {
if (gamesInProgress[id]) return getDataForUI(id);
2020-05-12 01:18:42 +00:00
if (gameRecord.length) {
console.log('here')
gamesInProgress[id] = Game({ gameData, gameRecord })
}
else {
gamesInProgress[id] = Game({gameData}).initGame();
}
2020-05-03 06:00:20 +00:00
return getDataForUI(id)
}
2020-05-12 01:18:42 +00:00
const makeMove = async ({id, move}) => {
if (!gamesInProgress[id]) storeGame({id}).initGame();
2020-05-03 06:00:20 +00:00
gamesInProgress[id] = gamesInProgress[id].makeMove(move)
if (gamesInProgress[id].success === false) return { message: 'illegal move' };
2020-05-12 01:18:42 +00:00
const priorMove = gamesInProgress[id].gameRecord.length;
const moveInsert = { gameId: id, player: move.player, x: move.pos.x, y: move.pos.y, gameRecord: true, priorMove };
let moveDbResult;
try {
moveDbResult = await moveQueries.addMove(moveInsert);
}
catch {
gamesInProgress[id].returnToMove(-1);
} finally {
return getDataForUI(id);
}
}
2020-05-03 06:00:20 +00:00
const getDataForUI = (id) => {
return {
board: gamesInProgress[id].legalMoves,
...gamesInProgress[id].getMeta()
};
}
const dropGame = (id) => {
return { message:
`${delete gamesInProgress[id]}`
}
}
const getAllGames = () => {
return gamesInProgress;
}
module.exports = {
2020-01-31 06:50:34 +00:00
makeMove,
getAllGames,
2020-05-03 06:00:20 +00:00
getDataForUI,
initGame,
dropGame
2020-05-03 06:00:20 +00:00
}