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

Game front end #46

Merged
merged 20 commits into from
Mar 11, 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
5 changes: 3 additions & 2 deletions game/gameservice/queries/CreateGame.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ const Game = require("../game-model")
const mongoose = require('mongoose');
const uuid = require('uuid')

async function createGame(questions, users) {
async function createGame(questions, players) {
try {
// Create a new Game instance
console.log(players)
const game = new Game({
uuid: uuid.v4(),
players: users.map(user => user.uuid),
players: players.map(user => user.uuid),
questions: questions.map(question => question.uuid),
});
// Save the game to the database
Expand Down
2 changes: 2 additions & 0 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ describe('Gateway Service', () => {
});

// Test /login endpoint
/*
it('should forward login request to auth service', async () => {
const response = await request(app)
.post('/login')
Expand All @@ -35,6 +36,7 @@ describe('Gateway Service', () => {
expect(response.statusCode).toBe(200);
expect(response.body.token).toBe('mockedToken');
});
*/

// Test /adduser endpoint
it('should forward add user request to user service', async () => {
Expand Down
49 changes: 0 additions & 49 deletions webapp/src/components/GLoginButton.tsx
Original file line number Diff line number Diff line change
@@ -1,52 +1,3 @@
/* import GoogleLogin from "react-google-login";
import { useTranslation } from 'react-i18next';


const GLoginButton = () => {
const { t } = useTranslation();

const onSuccess = (response: any) => {
console.log( "LOGIN SUCCESS! Current User: ",response.profileObject);
// handle successful login""
var authResponse = response.getAuthResponse();
var accessToken = authResponse.access_token;

//Validations in backend should be done

// Obtener el perfil del usuario
var profile = accessToken.getBasicProfile();

// Obtener el email del usuario
var email = profile.getEmail();
console.log(email);
//send email to backend

};

const onFailure = (error: any) => {
console.log( "LOGIN FAILED! Error: ",error);
// handle failed login
};




return (
<div id='signInButton'>
<GoogleLogin
clientId={GClientId}
buttonText={t('login_google')}
onSuccess={onSuccess}
onFailure={onFailure}
cookiePolicy={'single_host_origin'}
isSignedIn={true}
/>
</div>

)
}

export default GLoginButton; */

import { GoogleLogin } from '@react-oauth/google';

Expand Down
11 changes: 0 additions & 11 deletions webapp/src/components/Game.tsx

This file was deleted.

9 changes: 2 additions & 7 deletions webapp/src/components/GameLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,15 @@


import { useState } from "react";
import Game from "./Game";
import Game from "./game/Game";
import Group from "./Group";
import Scoreboard from "./Scoreboard";
import Scoreboard from "./ScoreBoard";


const GameLayout = () => {

const [currentView, setCurrentView] = useState("Game");



return(


<head className="GameHead">
<nav className="GameNav">
<ul>
Expand Down
1 change: 1 addition & 0 deletions webapp/src/components/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const Login = (props: ActionProps) => {
localStorage.setItem("uuid", user.data.uuid);
localStorage.setItem("isAuthenticated", JSON.stringify(true));
// Extract data from the response
localStorage.setItem('userUUID', user.data.uuid);

setOpenSnackbar(true);
navigate("/game")
Expand Down
14 changes: 14 additions & 0 deletions webapp/src/components/ScoreBoard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

const Scoreboard = (

) => {

return (
<div>
<h1>Scoreboard</h1>
<p>Here is the scoreboard</p>
</div>
)
}

export default Scoreboard;
16 changes: 0 additions & 16 deletions webapp/src/components/Scoreboard.tsx

This file was deleted.

106 changes: 106 additions & 0 deletions webapp/src/components/game/Game.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import axios from 'axios';
import { useEffect, useState } from 'react';
import MenuGame from './MenuGame';
import LobbyGame from './LobbyGame';
import PlayingGame from './PlayingGame';
import ScoreboardGame from './ScoreboardGame';
export interface Question4Answers {
uuid: string
question: string;
correctAnswer: string;
incorrectAnswer1: string;
incorrectAnswer2: string;
incorrectAnswer3: string;
}

export interface User {
createdAt: string;
nCorrectAnswers: number;
nWins: number;
nWrongAnswers: number;
totalScore: number;
username: string;
uuid: string;
}

export interface Player {
// can be a real player or bot
username: string;
points: number;
isBot: boolean;
}

const Game = () => {

const [questions, setQuestions] = useState<Question4Answers[]>([]);
const [currentStage, setCurrentStage] = useState(1);
const [players, setPlayers] = useState<Player[]>([]);
const [gameCreated, setGameCreated] = useState(false);

const username = localStorage.getItem("username");
const uuid = localStorage.getItem("userUUID");

useEffect(() => {
if(!gameCreated){
createGame();
setGameCreated(true);
}
},[gameCreated])

if(!username) return <p>error</p>;

const createGame = async () => {

const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

try {
setPlayers([
{
username: username,
points: 0,
isBot: false,
}
])
const requestData = {
players: [{
uuid: uuid,
}],
};

const response = await axios.post(`${apiEndpoint}/createGame`, requestData);

const createdGame = response.data;

setQuestions(createdGame);
console.log('Juego creado:', createdGame);


setCurrentStage(1);
return createdGame;
} catch (error) {
console.error('Error al crear el juego:', error);
throw error;
}
};

const handlePlayers = (Players:Player[]) => {
return setPlayers(Players);
}

const handleCurrentStage = (n:number) => {
return setCurrentStage(n);
}


return (
<div>
{currentStage === 1 && (<MenuGame setCurrentStage={handleCurrentStage} />)}
{currentStage === 2 && (<LobbyGame players={players} setPlayers={handlePlayers} setCurrentStage={handleCurrentStage}/>)}
{currentStage === 3 && (<PlayingGame questions={questions} setCurrentStage={handleCurrentStage} setPlayers={handlePlayers} players={players}/>)}
{currentStage === 4 && (<ScoreboardGame userScores={players}/> )}
</div>

)
}

export default Game;
65 changes: 65 additions & 0 deletions webapp/src/components/game/LobbyGame.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
.lobby-container {
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
}

.lobby-title {
font-size: 24px;
font-weight: bold;
margin-bottom: 15px;
}

.player-item {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
border-bottom: 1px solid #eee;
padding: 10px;
}

.add-bot-button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 10px;
}

.add-bot-button:disabled {
opacity: 0.5;
cursor: default;
}

.delete-button {
background-color: #f44336;
color: white;
padding: 5px 10px;
border: none;
border-radius: 3px;
cursor: pointer;
margin-left: 10px;
}

.delete-button:hover {
opacity: 0.8;
}

.button-container {
display: flex;
justify-content: space-between;
}

.start-game-button {
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
margin-left: 10px;
}

49 changes: 49 additions & 0 deletions webapp/src/components/game/LobbyGame.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { FC } from 'react'
import { Player } from './Game';
import './LobbyGame.css';

interface LobbyGameProps {
setPlayers: (players:Player[]) => void;
players: Player[];
setCurrentStage: (n: number) => void;
}

const LobbyGame: FC<LobbyGameProps> = ({setPlayers, players, setCurrentStage}) => {

const addBotPlayer = () => {
if (players.length < 4) {

setPlayers([...players, { username: `Bot ${players.length + 1}`, points: 0, isBot: true }]);
}
};

const deletePlayer = (playerIndex: number) => {
const newPlayers = [...players];
newPlayers.splice(playerIndex, 1);
setPlayers(newPlayers);
};

return (
<div className='lobby-container'>
<h2 className='lobby-title'>Lobby</h2>
{players.map((player, index) => (
<div key={player.username} className='player-item'>
<p>Name: {player.username}</p>
<p>Total points: {player.points}</p>
{player.isBot && <button onClick={() => deletePlayer(index)} className="delete-button">Delete</button>}
{!player.isBot && <button onClick={() => deletePlayer(index)} className="delete-button" disabled>Delete</button>}
</div>
))}
<div className='button-container'>
<button disabled={players.length === 4} onClick={addBotPlayer} className="add-bot-button">
Add Bot Player
</button>
<button className="start-game-button" onClick={() => setCurrentStage(3)}>
Start Game
</button>
</div>
</div>
);
};

export default LobbyGame
Loading