Skip to content

Commit

Permalink
score is now saved in gamestate. this allows an easy new game by givi…
Browse files Browse the repository at this point in the history
…ng the old scores as optional parameter in Game() constructor
  • Loading branch information
Teun van Dalen committed Nov 30, 2023
1 parent cfbc00a commit 65f6a08
Show file tree
Hide file tree
Showing 6 changed files with 88 additions and 74 deletions.
81 changes: 38 additions & 43 deletions client/src/components/host/EndHost.tsx
Original file line number Diff line number Diff line change
@@ -1,58 +1,53 @@
import { useEffect, useState } from "react";
import { getScore } from "../../service/SocketService";
import socket from "../../socket";
import { useState } from "react";
import { sendAnotherRound } from "../../service/SocketService";
import { useNameContext } from "../../context/NamesContext";

type ScoreDTO = Record<string, number>;
import { useRoom } from "../../context/RoomContext";

function EndHost() {

const { roomDTO } = useRoom();
const { nameMap } = useNameContext();
const [finalScore, setFinalScore] = useState<Record<string, number>>();

useEffect(() => {
socket.on('host:score', (scoreDTO: ScoreDTO) => {
setFinalScore(scoreDTO);
})

getScore();
const finalScore = roomDTO!.game!.score;

return () => {
socket.off('host:score');
}
}, [])
const handleAnotherRound = () => {
sendAnotherRound();
}

return (
<div className="container">
{!finalScore ?
<h2>Score is loading...</h2>
:
<table className="container table table-bordered w-50">
<thead className="table-success">
<tr>
<th>Player</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{Object.entries(finalScore).sort((a, b) => b[1] - a[1]).map(([playerID, score], index, array) => {
const reverseIndex = array.length - 1 - index;
return (
<tr key={playerID}>
<td>
<span className="caption-enter" style={{ animationDelay: `${reverseIndex * 1}s` }}>
{nameMap.get(playerID) || playerID}
</span>
</td>
<td>
<span className="caption-enter" style={{ animationDelay: `${reverseIndex * 1}s` }}>
{score}
</span>
</td>
</tr>)
})}
</tbody>
</table>
<div className="container text-center">
<table className="container table table-bordered w-50 mb-5">
<thead className="table-success">
<tr>
<th>Player</th>
<th>Score</th>
</tr>
</thead>
<tbody>
{Object.entries(finalScore).sort((a, b) => b[1] - a[1]).map(([playerID, score], index, array) => {
const reverseIndex = array.length - 1 - index;
return (
<tr key={playerID}>
<td>
<span className="caption-enter" style={{ animationDelay: `${reverseIndex * 1}s` }}>
{nameMap.get(playerID) || playerID}
</span>
</td>
<td>
<span className="caption-enter" style={{ animationDelay: `${reverseIndex * 1}s` }}>
{score}
</span>
</td>
</tr>)
})}
</tbody>
</table>

<button onClick={handleAnotherRound} className="btn btn-success">Play another round</button>
</div>
}
</div>
)
Expand Down
1 change: 1 addition & 0 deletions client/src/context/RoomContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type GameDTO = {
captions: Caption[];
votes: { [k: string]: Vote[] };
votingRound: number;
score: { [k: string]: number };
}

type RoomDTO = {
Expand Down
4 changes: 4 additions & 0 deletions client/src/service/SocketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,8 @@ export function sendVote(captionID: number) {

export function getScore() {
socket.emit('host:get-score', sessionStorage.getItem('roomID'));
}

export function sendAnotherRound() {
socket.emit('host:another-round', sessionStorage.getItem('roomID'));
}
50 changes: 29 additions & 21 deletions server/domain/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,38 @@ export class Game {
captions: Caption[];
votes: Map<number, Vote[]>;
votingRound: number;
score: Map<string, number>;

constructor(playerIDs: Set<string>) {
constructor(playerIDs: Set<string>, initialScores?: Map<string, number>) {
this.gamePhase = Phase.PHOTO_UPLOAD;
this.playerIDs = playerIDs;
this.photos = new Map<string, ArrayBuffer>();
this.captions = [];
this.votes = new Map<number, Vote[]>();
this.votingRound = 1;
this.score = new Map<string, number>();

const numberOfRounds = playerIDs.size;
for (let round = 1; round <= numberOfRounds; round++) {
this.votes.set(round, []);
this.initVotingRounds();

this.score = initialScores ? new Map(initialScores) : new Map();
if (!initialScores) {
this.initScore();
}

};

initVotingRounds() {
for (let round = 1; round <= this.playerIDs.size; round++) {
this.votes.set(round, []); //Same amount of voting rounds as amount of players
}
}

initScore() {
for (let player of this.playerIDs) {
this.score.set(player, 0);
}
}

getPlayers() {
return this.playerIDs;
}
Expand Down Expand Up @@ -146,6 +163,7 @@ export class Game {
const vote = { playerID, captionID };
if (!this.playerHasAlreadyVotedThisRound(playerID)) {
votes?.push(vote);
this.addPoint(caption.authorPlayerID);
}
}

Expand All @@ -167,22 +185,11 @@ export class Game {
return this.votingRound === this.votes.size + 1;
}

getScore() {
const scores: Record<string, number> = {};
this.playerIDs.forEach(playerID => {
scores[playerID] = 0;
});

this.votes.forEach((votesInRound) => {
votesInRound.forEach(vote => {
const caption = this.captions.find(caption => caption.ID === vote.captionID);
if (caption) {
scores[caption.authorPlayerID] += POINTS_PER_VOTE;
}
});
});

return scores;
addPoint(playerID: string) {
if (this.score.has(playerID)) {
let currentValue = this.score.get(playerID)!;
this.score.set(playerID, currentValue + POINTS_PER_VOTE);
}
}

getGameDTO() {
Expand All @@ -192,7 +199,8 @@ export class Game {
photos: Object.fromEntries(this.photos.entries()),
captions: this.captions,
votes: Object.fromEntries(this.votes.entries()),
votingRound: this.votingRound
votingRound: this.votingRound,
score: Object.fromEntries(this.score.entries()),
}
}

Expand Down
12 changes: 11 additions & 1 deletion server/domain/room.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Game, Phase } from "./game";
import { Game } from "./game";

export class Room {

Expand Down Expand Up @@ -50,4 +50,14 @@ export class Room {
return this.game ? true : false;
}

createNextGame() {
const score = this.game?.score;
if (score) {
this.game = new Game(this.playerIDs, score);
} else {
this.game = new Game(this.playerIDs);
}
this.datetime_created = Date.now();
}

}
14 changes: 5 additions & 9 deletions server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type GameDTO = {
captions: Caption[];
votes: { [k: string]: Vote[] };
votingRound: number;
score: { [k: string]: number };
}

type RoomDTO = {
Expand All @@ -52,10 +53,6 @@ type RoomDTO = {
game: GameDTO | undefined
}

type captionsForVotingDTO = {
owner: string,
captions: { authorPlayerID: string, captionText: string }[]
}

//Mongo DB for logging
import connectToDB from './database/setup';
Expand Down Expand Up @@ -249,12 +246,11 @@ io.on('connection', (socket_before) => {
}
})

socket.on('host:get-score', (roomID) => {
socket.on('host:another-round', (roomID) => {
const room = roomMap.get(roomID);
if (room && room.hasGame()) {
const game = room.game!;
const scoreDTO = game.getScore();
socket.emit('host:score', scoreDTO);
if (room && room.hasGame() && room.game!.gamePhase === Phase.END) {
room.createNextGame();
sendEveryoneRoomDTO(room);
}
})

Expand Down

0 comments on commit 65f6a08

Please sign in to comment.