fixed interval error

This commit is contained in:
Wenszel 2023-11-04 20:10:17 +01:00
parent b9ec78bc25
commit ae9ebcc246
4 changed files with 17211 additions and 22450 deletions

View File

@ -3,49 +3,50 @@ const { getPawnPositionAfterMove } = require('../utils/functions');
module.exports = (io, socket) => { module.exports = (io, socket) => {
const req = socket.request; const req = socket.request;
/*
Function responsible for drawing number in range from 1 to 6 and returning it to the player const getRoom = async () => {
if current player can move with drawed number allow the player to make a move return await RoomModel.findOne({ _id: req.session.roomId }).exec();
else skip player's turn };
*/
const rollDiceNumber = async () => { const updateRoom = async room => {
const rolledNumber = Math.ceil(Math.random() * 6); return await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec();
let room = await RoomModel.findOne({ _id: req.session.roomId }).exec(); };
room.rolledNumber = rolledNumber;
await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec(); const sendToPlayersRolledNumber = rolledNumber => {
io.to(req.session.roomId.toString()).emit('game:roll', rolledNumber); io.to(req.session.roomId.toString()).emit('game:roll', rolledNumber);
const isPossible = await canPlayerMoveAnyPawn(req.session.roomId, req.session.color, rolledNumber); };
if (!isPossible) {
room = changeMovingPlayer(room); const sendToPlayersData = room => {
await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec();
io.to(req.session.roomId.toString()).emit('room:data', JSON.stringify(room)); io.to(req.session.roomId.toString()).emit('room:data', JSON.stringify(room));
};
const rollDice = async () => {
const rolledNumber = Math.ceil(Math.random() * 6);
sendToPlayersRolledNumber(rolledNumber);
let room = await updateRoom({ rolledNumber: rolledNumber });
if (!canPlayerMove(room, rolledNumber)) {
room = changeMovingPlayer(room);
await updateRoom(room);
sendToPlayersData(room);
} }
}; };
/*
Function responsible for check if any pawn of the player can move const canPlayerMove = (room, rolledNumber) => {
if he cannot move, his turn will be skipped
Player's pawn can move if:
1) (if player's pawn is in base) if the rolled number is 1,6
2) (if player's pawn is near finish line) if the move does not go beyond the win line
Returns boolean
*/
const canPlayerMoveAnyPawn = async (roomId, playerColor, rolledNumber) => {
let isMovePossible = false; let isMovePossible = false;
const room = await RoomModel.findOne({ _id: roomId.toString() }).exec(); const playerPawns = room.pawns.filter(pawn => pawn.color === req.session.color);
const playerPawns = room.pawns.filter(pawn => pawn.color === playerColor);
// Checking each player's pawn
for (const pawn of playerPawns) { for (const pawn of playerPawns) {
// Checking the first condition // (if player's pawn is in base) if the rolled number is 1,6
if (pawn.position === pawn.basePos && (rolledNumber === 6 || rolledNumber === 1)) { if (pawn.position === pawn.basePos && (rolledNumber === 6 || rolledNumber === 1)) {
isMovePossible = true; isMovePossible = true;
} }
// Checking the second condition // (if player's pawn is near finish line) if the move does not go beyond the win line
if (pawn.position !== getPawnPositionAfterMove(rolledNumber, pawn) && pawn.position !== pawn.basePos) { if (pawn.position !== getPawnPositionAfterMove(rolledNumber, pawn) && pawn.position !== pawn.basePos) {
isMovePossible = true; isMovePossible = true;
} }
} }
return isMovePossible; return isMovePossible;
}; };
const isMoveValid = async (pawn, room) => { const isMoveValid = async (pawn, room) => {
if (req.session.color !== pawn.color) { if (req.session.color !== pawn.color) {
return false; return false;
@ -56,47 +57,39 @@ module.exports = (io, socket) => {
} }
return true; return true;
}; };
/*
Function responsible for skipping a player's turn, if he did not move within the allotted time
Function is used in timeouts that start after a player's move or after skipping his turn
*/
const skipPlayerTurn = async () => { const skipPlayerTurn = async () => {
let room = await RoomModel.findOne({ _id: req.session.roomId }).exec(); let room = await getRoom();
room = changeMovingPlayer(room); room = changeMovingPlayer(room);
await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec(); await updateRoom(room);
io.to(req.session.roomId.toString()).emit('room:data', JSON.stringify(room)); sendToPlayersData(room);
}; };
/*
Function responsible for moving the pawn by the number of spots that have been drawn
Props: pawnId - Id which is needed to find a pawn in the board. Id is the only thing that distinguishes pawns of the same color.
*/
const movePawn = async ({ pawnId }) => { const movePawn = async ({ pawnId }) => {
let room = await RoomModel.findOne({ _id: req.session.roomId }).exec(); let room = await getRoom();
const indexOfMovedPawn = room.pawns.findIndex(pawn => pawn._id == pawnId); const indexOfPawn = room.pawns.findIndex(pawn => pawn._id == pawnId);
const newPositionOfMovedPawn = getPawnPositionAfterMove(room.rolledNumber, room.pawns[indexOfMovedPawn]); if (!isMoveValid(room.pawns[indexOfPawn], room)) return;
if (!isMoveValid(room.pawns[indexOfMovedPawn], room)) return; const newPositionOfMovedPawn = getPawnPositionAfterMove(room.rolledNumber, room.pawns[indexOfPawn]);
room.pawns[indexOfMovedPawn].position = newPositionOfMovedPawn; room.pawns[indexOfPawn].position = newPositionOfMovedPawn;
// Looking for pawns in the same position as the new position of the pawn room = beatPawns(newPositionOfMovedPawn, room);
const pawnsInTheSamePosition = room.pawns.filter(pawn => pawn.position === newPositionOfMovedPawn); room = changeMovingPlayer(room);
// Each pawn in this position is checked to see if it has the same color as the pawn that has now moved to this position, if so, it is moved to the base (captured) await updateRoom(room);
sendToPlayersData(room);
};
const beatPawns = (position, room) => {
const pawnsInTheSamePosition = room.pawns.filter(pawn => pawn.position === position);
pawnsInTheSamePosition.forEach(pawn => { pawnsInTheSamePosition.forEach(pawn => {
if (pawn.color !== req.session.color) { if (pawn.color !== req.session.color) {
const index = room.pawns.findIndex(i => i._id === pawn._id); const index = room.pawns.findIndex(i => i._id === pawn._id);
room.pawns[index].position = room.pawns[index].basePos; room.pawns[index].position = room.pawns[index].basePos;
} }
}); });
room = changeMovingPlayer(room); return room;
await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec();
io.to(req.session.roomId.toString()).emit('room:data', JSON.stringify(room));
}; };
/*
Function responsible for changing the currently moving player in room object.
It changes the value of nowMoving for both players and sets a new turn-end time and erases the currently drawn number.
The function is used as an auxiliary function in other functions because many of them perform the operation of changing the currently moving player.
Args: room (object) from mongoDB
Returns: room object after changes
*/
const changeMovingPlayer = room => { const changeMovingPlayer = room => {
if (room.timeoutID) clearTimeout(room.timeoutID);
const playerIndex = room.players.findIndex(player => player.nowMoving === true); const playerIndex = room.players.findIndex(player => player.nowMoving === true);
room.players[playerIndex].nowMoving = false; room.players[playerIndex].nowMoving = false;
if (playerIndex + 1 === room.players.length) { if (playerIndex + 1 === room.players.length) {
@ -106,11 +99,11 @@ module.exports = (io, socket) => {
} }
room.nextMoveTime = Date.now() + 15000; room.nextMoveTime = Date.now() + 15000;
room.rolledNumber = null; room.rolledNumber = null;
setTimeout(skipPlayerTurn, 15000); room.timeoutID = setTimeout(skipPlayerTurn, 15000);
return room; return room;
}; };
socket.on('game:roll', rollDiceNumber); socket.on('game:roll', rollDice);
socket.on('game:move', movePawn); socket.on('game:move', movePawn);
socket.on('game:skip', skipPlayerTurn); socket.on('game:skip', skipPlayerTurn);
}; };

View File

@ -7,6 +7,7 @@ var RoomSchema = new Schema({
started: { type: Boolean, default: false }, started: { type: Boolean, default: false },
full: { type: Boolean, default: false }, full: { type: Boolean, default: false },
nextMoveTime: Number, nextMoveTime: Number,
timeoutID: Number,
rolledNumber: Number, rolledNumber: Number,
players: [ players: [
{ {

39703
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,7 +14,7 @@
"react-dom": "^17.0.1", "react-dom": "^17.0.1",
"react-loading": "^2.0.3", "react-loading": "^2.0.3",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "4.0.3", "react-scripts": "^5.0.1",
"socket.io": "^4.5.1", "socket.io": "^4.5.1",
"socket.io-client": "^4.5.1", "socket.io-client": "^4.5.1",
"web-vitals": "^1.1.0" "web-vitals": "^1.1.0"