add socket send game_end message from FE

This commit is contained in:
sorrelbri 2020-06-20 16:25:09 -07:00
parent 0db13d2913
commit 52762475f7
9 changed files with 196 additions and 64 deletions

View file

@ -42,9 +42,9 @@ const Board = (props) => {
const posY = (i % boardSize) + 1; const posY = (i % boardSize) + 1;
const pointData = board[`${posX}-${posY}`]; const pointData = board[`${posX}-${posY}`];
const dotData = const dotData =
meta?.turn && pointData meta && meta.turn === 0
? game.turn || meta.turn ? meta?.territory[`${posX}-${posY}`]
: meta?.territory[`${posX}-${posY}`]; : game.turn || meta?.turn;
boardPoints.push( boardPoints.push(
<Point <Point
key={`${posX}-${posY}`} key={`${posX}-${posY}`}

View file

@ -10,16 +10,27 @@ const PlayerArea = ({
const { stones, player, rank, captures } = playerMeta; const { stones, player, rank, captures } = playerMeta;
const isTurn = const isTurn =
(stones === "black" && turn === 1) || (stones === "white" && turn === -1); (stones === "black" && turn === 1) || (stones === "white" && turn === -1);
const bowlAttributes = () => {
if (isTurn || turn === 0)
return {
"data-turn": true,
onClick: () => handlePassClick(stones),
};
return null;
};
const bowlText = () => {
if (isTurn) return "Pass?";
if (turn === 0) return "End Game?";
// return;
};
return ( return (
<div className={`player-container player-container--${stones}`}> <div className={`player-container player-container--${stones}`}>
<div <div
className={`player-container__bowl player-container__bowl--${stones}`} className={`player-container__bowl player-container__bowl--${stones}`}
{...(isTurn {...bowlAttributes()}
? { "data-turn": true, onClick: () => handlePassClick(stones) }
: null)}
> >
<p>Pass?</p> <p>{bowlText()}</p>
</div> </div>
<div <div
className={`player-container__name-space player-container__name-space--${stones}`} className={`player-container__name-space player-container__name-space--${stones}`}

View file

@ -46,6 +46,10 @@ const launch = (nsp, dispatch) => {
dispatch({ type: "GAMES", message: "GAME_RESIGN", body: data }); dispatch({ type: "GAMES", message: "GAME_RESIGN", body: data });
}); });
socket.on("game_end", (data) => {
dispatch({ type: "GAMES", message: "GAME_END", body: data });
});
return socket; return socket;
}; };

View file

@ -71,6 +71,14 @@ const Game = (props) => {
}; };
const handlePassClick = (player) => { const handlePassClick = (player) => {
if (state?.meta && state?.meta?.turn === 0) {
const action = {
type: "SOCKET",
message: "END_GAME",
body: { game, player },
};
return dispatch(action);
}
const action = { const action = {
type: "SOCKET", type: "SOCKET",
message: "PASS", message: "PASS",

View file

@ -8,58 +8,42 @@ export const gamesReducer = (state, action) => {
} }
case "JOIN_REQUEST": { case "JOIN_REQUEST": {
if (!Object.entries(state.user).length) { return joinRequest(state, action);
const errAction = {
type: "ERR",
message: "JOIN_GAME_ERROR",
body: { joinGameError: "user not logged in" },
};
return stateReducer(state, errAction);
}
const id = action.body;
return { ...state, joinGame: id };
} }
case "UPDATE_BOARD": { case "UPDATE_BOARD": {
const { return updateBoard(state, action);
gameRecord,
pass,
turn,
winner,
playerState,
territory,
} = action.body.meta;
return {
...state,
board: action.body.board,
meta: { gameRecord, pass, turn, winner, playerState, territory },
};
} }
case "GAME_RESIGN": { case "GAME_RESIGN": {
const { gameRecord, pass, turn, winner, playerState } = action.body; return gameResign(state, action);
return {
...state,
meta: { gameRecord, pass, turn, winner, playerState },
};
} }
case "SET_ACTIVE": { case "SET_ACTIVE": {
return { ...state, active: action.body }; return { ...state, active: action.body };
} }
case "GAME_END": {
console.log(action.body);
return state;
}
default: { default: {
return state; return state;
} }
} }
}; };
// parse ranks from db in K9 format to 9k format
function parseRank(rank) { function parseRank(rank) {
switch (rank[0]) { switch (rank[0]) {
// Dan ranks
case "D": case "D":
return `${rank.slice(1)}${rank[0].toLowerCase()}`; return `${rank.slice(1)}${rank[0].toLowerCase()}`;
// Kyu ranks
case "K": case "K":
return `${rank.slice(1)}${rank[0].toLowerCase()}`; return `${rank.slice(1)}${rank[0].toLowerCase()}`;
// Unranked
case "U": case "U":
return "?"; return "?";
default: default:
@ -82,3 +66,40 @@ function formatGames(action) {
return games; return games;
} }
function joinRequest(state, action) {
if (!Object.entries(state.user).length) {
const errAction = {
type: "ERR",
message: "JOIN_GAME_ERROR",
body: { joinGameError: "user not logged in" },
};
return stateReducer(state, errAction);
}
const id = action.body;
return { ...state, joinGame: id };
}
function updateBoard(state, action) {
const {
gameRecord,
pass,
turn,
winner,
playerState,
territory,
} = action.body.meta;
return {
...state,
board: action.body.board,
meta: { gameRecord, pass, turn, winner, playerState, territory },
};
}
function gameResign(state, action) {
const { gameRecord, pass, turn, winner, playerState } = action.body;
return {
...state,
meta: { gameRecord, pass, turn, winner, playerState },
};
}

View file

@ -46,6 +46,10 @@ export const socketReducer = (state, action) => {
return toggleTerritory(state, action); return toggleTerritory(state, action);
} }
case "END_GAME": {
return endGame(state, action);
}
default: default:
return state; return state;
} }
@ -92,3 +96,10 @@ function toggleTerritory(state, action) {
socket.emit("toggle_territory", { ...action.body }); socket.emit("toggle_territory", { ...action.body });
return state; return state;
} }
function endGame(state, action) {
console.log("end game");
const socket = state.socket;
socket.emit("end_game", { ...action.body });
return state;
}

View file

@ -1,48 +1,91 @@
const knex = require('../db'); const knex = require("../db");
const gameDetailSelect = [ const gameDetailSelect = [
'game.id', 'application', 'application_version', "game.id",
'board_size', 'komi', 'handicap', 'open', 'win_type', "application",
'player_black', 'player_black_rank', 'player_white', 'player_white_rank', "application_version",
'captures_black', 'captures_white', 'score', 'win_type', "board_size",
'description', 'event', 'round', 'name', 'room' "komi",
] "handicap",
"open",
"win_type",
"player_black",
"player_black_rank",
"player_white",
"player_white_rank",
"captures_black",
"captures_white",
"score",
"win_type",
"description",
"event",
"round",
"name",
"room",
];
const timeSettingSelect = [ const timeSettingSelect = [
'main_time', 'time_period', 'period_length', 'overtime', 'overtime_period', 'overtime_length' "main_time",
] "time_period",
"period_length",
"overtime",
"overtime_period",
"overtime_length",
];
const gameOverviewSelect = [ const gameOverviewSelect = [
'id', 'board_size', 'komi', 'handicap', 'open', 'win_type', "id",
'player_black', 'player_black_rank', 'player_white', 'player_white_rank' "board_size",
] "komi",
"handicap",
"open",
"win_type",
"player_black",
"player_black_rank",
"player_white",
"player_white_rank",
];
const findGameById = async function (gameId) { const findGameById = async function (gameId) {
const selection = gameDetailSelect.concat(timeSettingSelect); const selection = gameDetailSelect.concat(timeSettingSelect);
const game = await knex const game = await knex
.from('game') .from("game")
.select(selection) .select(selection)
.where({'game.id': gameId}) .where({ "game.id": gameId })
.leftJoin('time_setting', function() { this.on('time_setting.id', '=', 'game.time_setting')}) .leftJoin("time_setting", function () {
this.on("time_setting.id", "=", "game.time_setting");
});
return game[0]; return game[0];
} };
const findGameByRoom = async (roomId) => { const findGameByRoom = async (roomId) => {
const games = await knex('game') const games = await knex("game")
.where({'room': roomId}) .where({ room: roomId })
.select(gameOverviewSelect); .select(gameOverviewSelect);
return games; return games;
} };
const insertGame = async (game) => { const insertGame = async (game) => {};
} const endGame = async ({ id }) => {
const game = await knex(game).where({ id: id }).update(
{
win_type: winType,
score: score,
captures_black: capturesBlack,
captures_white: capturesWhite,
}
// ["id"]
);
return game;
};
module.exports = { module.exports = {
findGameById, findGameById,
findGameByRoom, findGameByRoom,
insertGame insertGame,
} endGame,
};

View file

@ -1,6 +1,6 @@
const Game = require("./Game").Game; const Game = require("./Game").Game;
const GameService = (moveQueries) => { const GameService = ({ moveQueries, gameQueries }) => {
const storeGame = (game) => { const storeGame = (game) => {
gamesInProgress[game.id] = Game(game); gamesInProgress[game.id] = Game(game);
return gamesInProgress[game.id]; return gamesInProgress[game.id];
@ -105,6 +105,18 @@ const GameService = (moveQueries) => {
gamesInProgress[id] = gamesInProgress[id].toggleTerritory(point); gamesInProgress[id] = gamesInProgress[id].toggleTerritory(point);
return this.getDataForUI(id); return this.getDataForUI(id);
}, },
async endGame({ id }) {
gamesInProgress[id] = gamesInProgress[id].endGame();
try {
if (gameQueries) {
// TODO add end game query
}
} catch (e) {
console.log(e);
}
return this.getDataForUI(id);
},
}; };
}; };

View file

@ -4,7 +4,11 @@ const io = socketIO({ cookie: false });
// const gameQueries = require('./data/queries/game'); // const gameQueries = require('./data/queries/game');
const moveQueries = require("./data/queries/move"); const moveQueries = require("./data/queries/move");
const gameServices = require("./services/gameServices")(moveQueries); const gameQueries = require("./data/queries/game");
const gameServices = require("./services/gameServices")({
moveQueries,
gameQueries,
});
io.on("connection", async (socket) => { io.on("connection", async (socket) => {
socket.emit("connected", { message: "socket connected" }); socket.emit("connected", { message: "socket connected" });
@ -110,6 +114,24 @@ io.on("connection", async (socket) => {
console.log(e); console.log(e);
} }
}); });
// END GAME
socket.on("end_game", async ({ user, game }) => {
const { id, room } = game;
const gameNsp = `game${id}`;
try {
const { board, ...meta } = await gameServices.endGame({ id });
socket.join(gameNsp, () => {
io.of(room).to(gameNsp).emit("end_game", { board, meta });
});
} catch (e) {
console.log(e);
} finally {
socket.join(gameNsp, () => {
io.of(room).to(gameNsp).emit("end_game", { board, meta });
});
}
});
}); });
}); });
}); });