Merge pull request #3 from Wenszel/dev

Enhancements: Implementing Pawn Movement on Player Turn Miss, Updating Pawn Images
This commit is contained in:
Wiktor Smaga 2023-11-12 14:14:17 +01:00 committed by GitHub
commit 1f61445bc2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 17371 additions and 22536 deletions

2
.gitignore vendored
View File

@ -1,6 +1,4 @@
backend/node_modules
backend/credentials.js
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules

2
backend/credentials.js Normal file
View File

@ -0,0 +1,2 @@
// Write your own mongoDBatlas credentials here
module.exports = '';

View File

@ -1,116 +1,88 @@
const RoomModel = require('../schemas/room');
const Room = require('../schemas/room');
const { getPawnPositionAfterMove } = require('../utils/functions');
module.exports = (io, socket) => {
const req = socket.request;
/*
Function responsible for drawing number in range from 1 to 6 and returning it to the player
if current player can move with drawed number allow the player to make a move
else skip player's turn
*/
const rollDiceNumber = async () => {
const handleMovePawn = async pawnId => {
const room = await getRoom();
const pawn = room.getPawn(pawnId);
if (isMoveValid(pawn, room)) {
const newPositionOfMovedPawn = getPawnPositionAfterMove(room.rolledNumber, pawn);
room.changePositionOfPawn(pawn, newPositionOfMovedPawn);
room.beatPawns(newPositionOfMovedPawn, req.session.color);
handleChangeOfPlayer(room);
}
};
const handleRollDice = async () => {
const rolledNumber = rollDice();
const room = await updateRoom({ rolledNumber: rolledNumber });
if (!canPlayerMove(room, rolledNumber)) {
handleChangeOfPlayer(room);
}
};
const rollDice = () => {
const rolledNumber = Math.ceil(Math.random() * 6);
let room = await RoomModel.findOne({ _id: req.session.roomId }).exec();
room.rolledNumber = rolledNumber;
await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec();
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);
await RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room).exec();
io.to(req.session.roomId.toString()).emit('room:data', JSON.stringify(room));
}
sendToPlayersRolledNumber(rolledNumber);
return rolledNumber;
};
/*
Function responsible for check if any pawn of the player can move
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;
const room = await RoomModel.findOne({ _id: roomId.toString() }).exec();
const playerPawns = room.pawns.filter(pawn => pawn.color === playerColor);
// Checking each player's pawn
const canPlayerMove = (room, rolledNumber) => {
const playerPawns = room.getPlayerPawns(req.session.color);
for (const pawn of playerPawns) {
// Checking the first condition
if (pawn.position === pawn.basePos && (rolledNumber === 6 || rolledNumber === 1)) {
isMovePossible = true;
}
// Checking the second condition
if (pawn.position !== getPawnPositionAfterMove(rolledNumber, pawn) && pawn.position !== pawn.basePos) {
isMovePossible = true;
}
if (pawn.canMove(rolledNumber)) return true;
}
return isMovePossible;
return false;
};
const isMoveValid = async (pawn, room) => {
const isMoveValid = (pawn, room) => {
if (req.session.color !== pawn.color) {
return false;
}
currentlyMovingPlayer = room.players.filter(player => player.nowMoving === true);
if (req.session.playerId !== currentlyMovingPlayer._id) {
if (req.session.playerId !== room.getCurrentlyMovingPlayer()._id.toString()) {
return false;
}
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 () => {
let room = await RoomModel.findOne({ _id: req.session.roomId }).exec();
room = changeMovingPlayer(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 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 }) => {
let room = await RoomModel.findOne({ _id: req.session.roomId }).exec();
const indexOfMovedPawn = room.pawns.findIndex(pawn => pawn._id == pawnId);
const newPositionOfMovedPawn = getPawnPositionAfterMove(room.rolledNumber, room.pawns[indexOfMovedPawn]);
if (!isMoveValid(room.pawns[indexOfMovedPawn], room)) return;
room.pawns[indexOfMovedPawn].position = newPositionOfMovedPawn;
// Looking for pawns in the same position as the new position of the pawn
const pawnsInTheSamePosition = room.pawns.filter(pawn => pawn.position === newPositionOfMovedPawn);
// 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)
pawnsInTheSamePosition.forEach(pawn => {
if (pawn.color !== req.session.color) {
const index = room.pawns.findIndex(i => i._id === pawn._id);
room.pawns[index].position = room.pawns[index].basePos;
}
});
room = changeMovingPlayer(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 playerIndex = room.players.findIndex(player => player.nowMoving === true);
room.players[playerIndex].nowMoving = false;
if (playerIndex + 1 === room.players.length) {
room.players[0].nowMoving = true;
} else {
room.players[playerIndex + 1].nowMoving = true;
}
room.nextMoveTime = Date.now() + 15000;
room.rolledNumber = null;
setTimeout(skipPlayerTurn, 15000);
return room;
const handleChangeOfPlayer = async room => {
room.changeMovingPlayer();
room.timeoutID = setTimeout(makeRandomMove, 15000, room);
await updateRoom(room);
};
socket.on('game:roll', rollDiceNumber);
socket.on('game:move', movePawn);
socket.on('game:skip', skipPlayerTurn);
const makeRandomMove = async room => {
if (room.rolledNumber === null) room.rolledNumber = rollDice();
const pawnsThatCanMove = room.getPawnsThatCanMove()
if (pawnsThatCanMove.length > 0) {
const randomPawn = pawnsThatCanMove[Math.floor(Math.random() * pawnsThatCanMove.length)];
room.movePawn(randomPawn);
}
await handleChangeOfPlayer(room);
};
Room.watch().on('change', async () => {
sendToPlayersData(await getRoom());
});
const getRoom = async () => {
return await Room.findOne({ _id: req.session.roomId }).exec();
};
const updateRoom = async room => {
return await Room.findOneAndUpdate({ _id: req.session.roomId }, room).exec();
};
const sendToPlayersRolledNumber = rolledNumber => {
io.to(req.session.roomId).emit('game:roll', rolledNumber);
};
const sendToPlayersData = room => {
io.to(req.session.roomId).emit('room:data', JSON.stringify(room));
};
socket.on('game:roll', handleRollDice);
socket.on('game:move', handleMovePawn);
};

View File

@ -70,8 +70,8 @@ module.exports = (io, socket) => {
req.session.reload(err => {
if (err) return socket.disconnect();
// Saving session data
req.session.roomId = room._id;
req.session.playerId = room.players[0]._id;
req.session.roomId = room._id.toString();
req.session.playerId = room.players[0]._id.toString();
req.session.color = room.players[0].color;
req.session.save();
// Sending data to the user, after which player will be redirected to the game
@ -108,8 +108,8 @@ module.exports = (io, socket) => {
req.session.reload(err => {
if (err) return socket.disconnect();
// Saving session data
req.session.roomId = room._id;
req.session.playerId = updatedRoom.players[updatedRoom.players.length - 1]._id;
req.session.roomId = room._id.toString();
req.session.playerId = updatedRoom.players[updatedRoom.players.length - 1]._id.toString();
req.session.color = colors[updatedRoom.players.length - 1];
req.session.save();
socket.join(room._id.toString());

View File

@ -28,7 +28,7 @@ module.exports = (io, socket) => {
}
room.nextMoveTime = Date.now() + 15000;
RoomModel.findOneAndUpdate({ _id: req.session.roomId }, room, function (err, updatedRoom) {
io.to(req.session.roomId.toString()).emit('room:data', JSON.stringify(updatedRoom));
io.to(req.session.roomId).emit('room:data', JSON.stringify(updatedRoom));
});
});
}

24
backend/schemas/pawn.js Normal file
View File

@ -0,0 +1,24 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { getPawnPositionAfterMove } = require('../utils/functions');
const PawnSchema = new Schema({
color: String,
basePos: Number,
position: Number,
});
PawnSchema.methods.canMove = function (rolledNumber) {
if (this.position === this.basePos && (rolledNumber === 6 || rolledNumber === 1)) {
return true;
}
// (if player's pawn is near finish line) if the move does not go beyond the win line
if (this.position !== getPawnPositionAfterMove(rolledNumber, this) && this.position !== this.basePos) {
return true;
}
return false;
};
module.exports = PawnSchema;

12
backend/schemas/player.js Normal file
View File

@ -0,0 +1,12 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PlayerSchema = new Schema({
name: String,
color: String,
ready: { type: Boolean, default: false },
nowMoving: { type: Boolean, default: false },
});
module.exports = PlayerSchema;

View File

@ -1,30 +1,76 @@
var mongoose = require('mongoose');
const mongoose = require('mongoose');
const { getPawnPositionAfterMove } = require('../utils/functions');
const Schema = mongoose.Schema;
const PawnSchema = require('./pawn');
const PlayerSchema = require('./player');
var Schema = mongoose.Schema;
var RoomSchema = new Schema({
const RoomSchema = new Schema({
createDate: Date,
started: { type: Boolean, default: false },
full: { type: Boolean, default: false },
nextMoveTime: Number,
timeoutID: Number,
rolledNumber: Number,
players: [
{
name: String,
color: String,
ready: { type: Boolean, default: false },
nowMoving: { type: Boolean, default: false },
},
],
pawns: [
{
color: String,
basePos: Number,
position: Number,
},
],
players: [PlayerSchema],
pawns: [PawnSchema],
});
var RoomModel = mongoose.model('RoomModel', RoomSchema);
RoomSchema.methods.beatPawns = function (position, attackingPawnColor) {
const pawnsOnPosition = this.pawns.filter(pawn => pawn.position === position);
pawnsOnPosition.forEach(pawn => {
if (pawn.color !== attackingPawnColor) {
const index = this.getPawnIndex(pawn._id);
this.pawns[index].position = this.pawns[index].basePos;
}
});
};
RoomSchema.methods.changeMovingPlayer = function () {
const playerIndex = this.players.findIndex(player => player.nowMoving === true);
this.players[playerIndex].nowMoving = false;
if (playerIndex + 1 === this.players.length) {
this.players[0].nowMoving = true;
} else {
this.players[playerIndex + 1].nowMoving = true;
}
this.nextMoveTime = Date.now() + 15000;
this.rolledNumber = null;
if (this.timeoutID) clearTimeout(this.timeoutID);
};
RoomSchema.methods.movePawn = function (pawn) {
const newPositionOfMovedPawn = getPawnPositionAfterMove(this.rolledNumber, pawn);
this.changePositionOfPawn(pawn, newPositionOfMovedPawn);
this.beatPawns(newPositionOfMovedPawn, pawn.color);
};
RoomSchema.methods.getPawnsThatCanMove = function () {
const movingPlayer = this.getCurrentlyMovingPlayer();
const playerPawns = this.getPlayerPawns(movingPlayer.color);
return playerPawns.filter(pawn => pawn.canMove(this.rolledNumber));
}
RoomSchema.methods.changePositionOfPawn = function (pawn, newPosition) {
const pawnIndex = this.getPawnIndex(pawn._id);
this.pawns[pawnIndex].position = newPosition;
};
RoomSchema.methods.getPawnIndex = function (pawnId) {
return this.pawns.findIndex(pawn => pawn._id.toString() === pawnId.toString());
};
RoomSchema.methods.getPawn = function (pawnId) {
return this.pawns.find(pawn => pawn._id.toString() === pawnId.toString());
};
RoomSchema.methods.getPlayerPawns = function (color) {
return this.pawns.filter(pawn => pawn.color === color);
};
RoomSchema.methods.getCurrentlyMovingPlayer = function () {
return this.players.find(player => player.nowMoving === true);
};
const RoomModel = mongoose.model('Room', RoomSchema);
module.exports = RoomModel;

39547
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-loading": "^2.0.3",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-scripts": "^5.0.1",
"socket.io": "^4.5.1",
"socket.io-client": "^4.5.1",
"web-vitals": "^1.1.0"

View File

@ -1,7 +1,11 @@
import React, { useEffect, useRef, useState, useContext, useCallback } from 'react';
import { PlayerDataContext, SocketContext } from '../../App';
import positions from './positions';
import bluePawn from '../../images/pawns/blue-pawn.png';
import greenPawn from '../../images/pawns/green-pawn.png';
import yellowPawn from '../../images/pawns/yellow-pawn.png';
import redPawn from '../../images/pawns/red-pawn.png';
import greyPawn from '../../images/pawns/grey-pawn.png';
const Map = ({ pawns, nowMoving, rolledNumber }) => {
const context = useContext(PlayerDataContext);
const socket = useContext(SocketContext);
@ -9,10 +13,25 @@ const Map = ({ pawns, nowMoving, rolledNumber }) => {
const paintPawn = (context, x, y, color) => {
const circle = new Path2D();
circle.arc(x, y, 12, 0, 2 * Math.PI);
context.strokeStyle = 'black';
context.stroke(circle);
context.fillStyle = color;
context.fill(circle);
const image = new Image();
switch (color) {
case 'green':
image.src = greenPawn;
break;
case 'blue':
image.src = bluePawn;
break;
case 'red':
image.src = redPawn;
break;
case 'yellow':
image.src = yellowPawn;
break;
case 'grey':
image.src = greyPawn;
break;
}
context.drawImage(image, x - 17, y - 14, 35, 30);
return circle;
};
@ -59,9 +78,10 @@ const Map = ({ pawns, nowMoving, rolledNumber }) => {
y = event.clientY - rect.top;
for (const pawn of pawns) {
if (ctx.isPointInPath(pawn.circle, x, y)) {
socket.emit('game:move', { pawnId: pawn._id });
socket.emit('game:move', pawn._id);
}
}
setHintPawn(null);
}
};
const getHintPawnPosition = pawn => {
@ -170,21 +190,12 @@ const Map = ({ pawns, nowMoving, rolledNumber }) => {
image.onload = function () {
ctx.drawImage(image, 0, 0);
pawns.forEach((pawn, index) => {
if (nowMoving && rolledNumber && pawn.color === context.color && checkIfPawnCanMove(pawn)) {
pawns[index].circle = paintPawn(
ctx,
positions[pawn.position].x,
positions[pawn.position].y,
'white'
);
} else {
pawns[index].circle = paintPawn(
ctx,
positions[pawn.position].x,
positions[pawn.position].y,
pawn.color
);
}
pawns[index].circle = paintPawn(
ctx,
positions[pawn.position].x,
positions[pawn.position].y,
pawn.color
);
});
if (hintPawn) {
paintPawn(ctx, positions[hintPawn.position].x, positions[hintPawn.position].y, hintPawn.color);
@ -201,6 +212,9 @@ const Map = ({ pawns, nowMoving, rolledNumber }) => {
socket.on('game:move', () => {
setHintPawn(null);
});
socket.on('game:roll', () => {
setHintPawn(null);
});
}, [socket]);
return (
<canvas

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB