add checkMove hook to Game

This commit is contained in:
sorrelbri 2020-07-07 16:52:45 -07:00
parent 2a84644e12
commit cfec49845b
3 changed files with 46 additions and 2 deletions

View file

@ -244,11 +244,31 @@ const Game = ({ gameData = {}, gameRecord = [] } = {}) => {
};
},
checkMove: function ({ player, pos: { x, y } }) {
// if game is over
// TODO either change logic here or add additional method for handling moves off of record
if (this.pass > 1) {
return { ...this, success: false };
}
const point = this.boardState[`${x}-${y}`];
const isTurn =
(this.turn === 1 && player === "black") ||
(this.turn === -1 && player === "white");
if (isTurn) {
if (point.legal) {
return { ...this, success: true, move: { player, pos: { x, y } } };
}
}
return { ...this, success: false };
},
makeMove: function ({ player, pos: { x, y } }) {
if (this.pass > 1) {
return { ...this, success: false };
}
if (x === 0) return this.submitPass(player);
let game = this;
let success = false;
const point = game.boardState[`${x}-${y}`];

View file

@ -7,6 +7,29 @@ const GameService = ({ moveQueries, gameQueries }) => {
};
const gamesInProgress = {};
const storeMove = (gameId) => async ({ player, pos: { x, y } }) => {
let move = { player, pos: { x, y } };
try {
if (moveQueries) {
const { id } = await moveQueries.addMove({
gameId,
player,
x,
y,
gameRecord: true,
priorMove: null,
});
move.id = id;
move.success = true;
}
} catch (e) {
console.log(e);
move.success = false;
} finally {
return move;
}
};
return {
initGame({ id, gameRecord = [], ...gameData }) {
if (gamesInProgress[id]) return this.getDataForUI(id);
@ -31,6 +54,7 @@ const GameService = ({ moveQueries, gameQueries }) => {
return { message: "error restoring game" };
}
}
gamesInProgress[id] = await gamesInProgress[id].checkMove(move);
gamesInProgress[id] = gamesInProgress[id].makeMove(move);
if (gamesInProgress[id].success === false)
return { message: "illegal move" };

View file

@ -1,4 +1,4 @@
// TODO const someSocketLogic = require('./middleware/socketssockets/...');
// TODO const someSocketLogic = require('./middleware/sockets/...');
const socketIO = require("socket.io");
const io = socketIO({ cookie: false });
@ -24,6 +24,7 @@ io.on("connection", async (socket) => {
socket.on("connect_game", (data) => {
const game = `game-${data.game.id}`;
socket.join(game, async () => {
// TODO move this logic into game service
const gameData = await gameQueries.findGameById(data.game.id);
const convertWinType = (winType) => {
if (winType.includes("B")) return 1;
@ -51,7 +52,6 @@ io.on("connection", async (socket) => {
socket.on("make_move", async (data) => {
const { user, move, board, game, room } = data;
const gameNsp = `game-${data.game.id}`;
try {
const { board, message, ...meta } = await gameServices.makeMove({
id: data.game.id,