Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

80 crea nuova partita automaticamente #99

Merged
merged 8 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 52 additions & 1 deletion Scoprimi/src/components/finalresults/FinalResults.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { FinalResultData } from '../../ts/types';
import { useLocation, useNavigate } from 'react-router-dom';
import { socket } from '../../ts/socketInit';
import { SocketEvents } from '../../../../Server/src/MiddleWare/SocketEvents';
import { useSession } from '../../contexts/SessionContext';
import Alert from '../common/Alert';

const defaultHeights = [
'7vh',
Expand All @@ -14,6 +18,7 @@ const defaultColors = [
'#cd7f32', // Bronzo
];


function getPodiumStats(sameScore1And2, sameScore1And3, sameScore2And3, positionsArray) {
let podiumArray = [...positionsArray];

Expand All @@ -36,6 +41,44 @@ const FinalResults: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const { finalResults } = location.state as { finalResults: FinalResultData };
const { currentPlayer, setCurrentLobby, currentPlayerImage, currentLobby } = useSession();
const [showAlert, setShowAlert] = useState<boolean>(false);

function TODOREMATCH() {
socket.emit(SocketEvents.SET_NEXT_GAME, { code: currentLobby, playerName: currentPlayer, image: currentPlayerImage });
}

useEffect(() => {
socket.on(SocketEvents.PLAYER_CAN_JOIN, (data) => {
if (data.canJoin) {
setCurrentLobby(data.lobbyCode);
navigate('/lobby');
} else {
setShowAlert(true);
}
});

return () => {
socket.off(SocketEvents.PLAYER_CAN_JOIN);
};
}, [navigate, setCurrentLobby]);

useEffect(() => {
socket.on(SocketEvents.RETURN_NEWGAME, (data: { lobbyCode: string }) => {
// TODO
const datatoSend = {
lobbyCode: data.lobbyCode,
playerName: currentPlayer,
image: currentPlayerImage,
};
socket.emit(SocketEvents.REQUEST_TO_JOIN_LOBBY, datatoSend);
});

return () => {
socket.off(SocketEvents.RETURN_NEWGAME);
};
}, [currentPlayer, currentPlayerImage]);


// Ordinamento con tipizzazione
const sortedResults = Object.entries(finalResults)
Expand Down Expand Up @@ -68,6 +111,7 @@ const FinalResults: React.FC = () => {

return (
<>
<Alert text='Sei già in questa lobby' show={showAlert} onHide={() => setShowAlert(false)} />
<div id="gameOverMessage" className="paginator">
<h2 className="">Classifica</h2>

Expand Down Expand Up @@ -147,12 +191,19 @@ const FinalResults: React.FC = () => {
</table>
</div>


<button
className="my-btn mt-3 my-bg-puss"
onClick={() => navigate('/')}
>
Torna alla homepage
</button>
<button
className='my-btn mt-3 my-bg-puss'
onClick={TODOREMATCH}
>
Gioca ancora
</button>
</div>
</>
);
Expand Down
5 changes: 0 additions & 5 deletions Scoprimi/src/components/game/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
const [isPhoto, setIsPhoto] = useState<boolean>(false);
const [selectedPlayer, setSelectedPlayer] = useState<string>('');

const [pages, setPages] = useState<any>();

Check warning on line 50 in Scoprimi/src/components/game/Game.tsx

View workflow job for this annotation

GitHub Actions / build (ubuntu-latest, 20.x)

Unexpected any. Specify a different type

const [isWho, setIsWho] = useState<boolean>(false);

Expand All @@ -72,8 +72,6 @@

useEffect(() => {
socket.on(SocketEvents.SEND_QUESTION, (data: { question: Question, players: string[], images: { [key: string]: string }, selectedPlayer: string }) => {
console.log('questions: ');
console.log(data.question.images);
setClicked(false);
setIsTimerActive(true);
setQuestion(data.question.text);
Expand All @@ -100,7 +98,6 @@

useEffect(() => {
socket.on(SocketEvents.PLAYERS_WHO_VOTED, (data: { players: { [key: string]: string } }) => {
console.log(Object.keys(data.players));
setPlayersWhoVoted(Object.keys(data.players));
});
return () => {
Expand All @@ -114,7 +111,6 @@
playerImages: { [key: string]: string },
mostVotedPerson: string,
}) => {
console.log('Madonna sburra');
setVoteRecap(data.voteRecap);
setPlayerImages(data.playerImages);
setMostVotedPerson(data.mostVotedPerson);
Expand All @@ -124,7 +120,6 @@

socket.on(SocketEvents.GAME_OVER, (data: { playerScores: PlayerScores, playerImages: PlayerImages }) => {
setQuestion('');
setCurrentLobby(null);
setPlayers([]);
socket.emit(SocketEvents.LEAVE_ROOM, { playerName: currentPlayer, LobbyCode: currentLobby });

Expand Down
3 changes: 0 additions & 3 deletions Scoprimi/src/components/lobby/Lobby.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ const Lobby: React.FC = () => {

useEffect(() => {
const handleVisibilityChange = () => {
console.log('dentro alla funzione');
if (!document.hidden) {

const data = {
Expand Down Expand Up @@ -55,7 +54,6 @@ const Lobby: React.FC = () => {
useEffect(() => {
document.title = `Lobby - ${currentLobby}`;
socket.emit(SocketEvents.REQUEST_RENDER_LOBBY, currentLobby, (data: Game) => {
console.log('Received data:', data);
setGame(data);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
setIsReady(data.players[currentPlayer!].isReadyToGame);
Expand Down Expand Up @@ -106,7 +104,6 @@ const Lobby: React.FC = () => {
const handleRemovePlayer = (playerName: string) => {
console.log('Admin is removing the player:', playerName);
socket.emit(SocketEvents.REMOVE_PLAYER, { playerName, currentLobby });
console.log('Io sono il giocatore: ', currentPlayer);
};

const handleCancelLeave = () => {
Expand Down
2 changes: 0 additions & 2 deletions Scoprimi/src/components/newGame/NewGameModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,9 @@ const NewGameModal: React.FC<NewGameModalProps> = ({ isOpen, onClose, playerName

useEffect(() => {
if (isOpen) {
console.log('Modal aperto per il giocatore:', playerName);
socket.emit(SocketEvents.REQUEST_CATEGORIES);

socket.on(SocketEvents.SEND_GENRES, (data: { genres: string[] }) => {
console.log('Categorie ricevute: ', data.genres);
setCategories(data.genres);
setSelectedCategories(new Array(data.genres.length).fill(false));
});
Expand Down
2 changes: 0 additions & 2 deletions Server/src/API/questions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export const setupUpload = (app: Express) => {
};

app.post('/upload', authMiddleware, upload.single('file'), async (req: Request, res: Response) => {
console.log('eccoci');
const tempPath = req.file?.path;
const targetPath = join(__dirname, '../questions.json');

Expand All @@ -48,7 +47,6 @@ export const setupUpload = (app: Express) => {
await rename(tempPath, targetPath);
const data = await readFile(targetPath, 'utf8');
AllQuestions = JSON.parse(data);
console.log(AllQuestions);
res.status(200).json({ message: 'File aggiornato con successo' });
} catch (err) {
console.error('Errore durante il salvataggio del file', err);
Expand Down
1 change: 1 addition & 0 deletions Server/src/MiddleWare/SocketEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ export enum SocketEvents {
SEND_GENRES = 'SEND_GENRES',
ENDGAMEWRAPPER = 'ENDGAMEWRAPPER',
READY_FOR_PODIUM = 'READY_FOR_PODIUM',
SET_NEXT_GAME = 'set_next_game',
}
6 changes: 6 additions & 0 deletions Server/src/data/Game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { Question, QuestionMode } from "./Question.js";
export class Game {
// Lobby code
public lobbyCode: string;
// List of Game Modes
public gamesGenre: QuestionGenre[]
// Indicates whether the game has started
public isGameStarted: boolean;
// List of players
Expand All @@ -23,6 +25,8 @@ export class Game {
public creationTime: number;
// Admin of the lobby (can start the game / remove a player from the lobby)
public admin: string;
// nextGame
public nextGame: string | undefined;

/**
* Creates an instance of the game.
Expand All @@ -31,6 +35,7 @@ export class Game {
*/
constructor(lobbyCode: string, admin: string) {
this.lobbyCode = lobbyCode;
this.gamesGenre = [];
this.isGameStarted = false;
this.players = {};
this.numOfVoters = 0;
Expand All @@ -39,6 +44,7 @@ export class Game {
this.iterator = this.createIterator();
this.creationTime = Date.now();
this.admin = admin;
this.nextGame = undefined;
}

/**
Expand Down
Loading