Skip to content

Commit

Permalink
merge game_front
Browse files Browse the repository at this point in the history
  • Loading branch information
a-boring-man committed Apr 19, 2023
2 parents eb7e098 + 8693135 commit f693d9f
Show file tree
Hide file tree
Showing 17 changed files with 405 additions and 333 deletions.
4 changes: 2 additions & 2 deletions front/react_project/src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ button:hover {

.App {
background-color: var(--prim-color);
/* background: url(./assets/background1.png) no-repeat center center fixed;
background-size: cover; */
background: url(./assets/trianglyfy5.png) no-repeat center center fixed;
background-size: cover;
display: flex;
/* background-color: rgb(75, 29, 138); */
/* border: 2px black dotted; */
Expand Down
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added front/react_project/src/assets/trianglyfy1.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added front/react_project/src/assets/trianglyfy2.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added front/react_project/src/assets/trianglyfy3.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added front/react_project/src/assets/trianglyfy4.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added front/react_project/src/assets/trianglyfy5.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
150 changes: 89 additions & 61 deletions front/react_project/src/components/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ interface ball {
}

interface gameState {
BallPosition: ball[],
paddleOne: { x: number, y: number },
paddleTwo: { x: number, y: number }
BallPosition: ball[] | null,
paddleOne: { x: number, y: number } | null,
paddleTwo: { x: number, y: number } | null
}

interface MatchState {
Expand Down Expand Up @@ -52,6 +52,8 @@ interface Players {

const Game: React.FC = () => {
const canvasRef = useRef<HTMLCanvasElement>(null);
let clearGame: boolean = false;
// const [clearGame, setClearGame] = useState<boolean>(false);
// const [startGame, setStartGame] = useState<boolean>(false);
const [waitMatch, setWaitMatch] = useState<boolean>(false); // A init à false
const {socketGame, disconnectGame} = React.useContext(SocketContext);
Expand Down Expand Up @@ -149,6 +151,7 @@ const Game: React.FC = () => {
setMatchInProgress(true);
setButtonReady(true);
ready = true;
clearGame = false;
setPlayers(prevPlayers => {
return {
...prevPlayers!,
Expand All @@ -167,17 +170,20 @@ const Game: React.FC = () => {
}
setButtonReady(false);
ready = false;
setGameState(gameState);
setGameState((prevState) => ({
...prevState,
BallPosition: gameState.BallPosition.map((ball) => ({
x: ball.x / (16 / 9),
y: ball.y,
r: ball.r
})),
paddleOne: { x: gameState.paddleOne.x / (16 / 9), y: gameState.paddleOne.y },
paddleTwo: { x: gameState.paddleTwo.x / (16 / 9), y: gameState.paddleTwo.y }
}));
// setGameState(gameState);
if (clearGame === false) {
setGameState((prevState) => ({
...prevState,
BallPosition: gameState.BallPosition!.map((ball) => ({
x: ball.x / (16 / 9),
y: ball.y,
r: ball.r
})),
paddleOne: { x: gameState.paddleOne!.x / (16 / 9), y: gameState.paddleOne!.y },
paddleTwo: { x: gameState.paddleTwo!.x / (16 / 9), y: gameState.paddleTwo!.y }
}));

}
});

socketGame.on('Match_Update', (matchUpdate: MatchState) => {
Expand All @@ -198,6 +204,17 @@ const Game: React.FC = () => {
setCountdown(3);
setPlayerReady(false)
ready = false;
clearGame = true;
// setClearGame(true);
// const canvas = canvasRef.current;
// const context = canvas!.getContext("2d")!;
// console.log('context', context);
// context.clearRect(0, 0, gameWidth, gameHeight);
setGameState({
BallPosition: null,
paddleOne: null,
paddleTwo: null
})
})
}
}, [socketGame]);
Expand Down Expand Up @@ -248,9 +265,8 @@ const Game: React.FC = () => {
}
};


const [gameWidth, setGameWidth] = useState<number>(window.innerWidth * 0.8);
const [gameHeight, setGameHeight] = useState<number>(window.innerWidth * 0.8 / (16 / 9));
const [gameWidth, setGameWidth] = useState<number>(window.innerWidth * 0.8 * 0.8);
const [gameHeight, setGameHeight] = useState<number>(window.innerWidth * 0.8 * 0.8 / (16 / 9));
// Handle windows resizing
useEffect(() => {
function handleResize() {
Expand All @@ -264,9 +280,10 @@ const Game: React.FC = () => {
}, []);

// Get css colors variables to use it in the canva
const style = getComputedStyle(document.documentElement);
const ballColor = style.getPropertyValue('--ball-color');
const secondaryColor = style.getPropertyValue('--secondary-color');
const styleColor = getComputedStyle(document.documentElement);
const ballColor = styleColor.getPropertyValue('--ball-color');
const thirdColor = styleColor.getPropertyValue('--third-color');
const fourthColor = styleColor.getPropertyValue('--fourth-color');

useEffect(() => {
let paddleWidth: number = gameWidth * 0.014;
Expand All @@ -276,18 +293,22 @@ const Game: React.FC = () => {
const context = canvas.getContext("2d")!;
if (context) {
context.clearRect(0, 0, gameWidth, gameHeight);
if (gameState.BallPosition != null && gameState.paddleOne != null && gameState.paddleTwo != null) {
gameState!.BallPosition!.forEach((ball) => {
context.beginPath();
context.arc(ball.x * gameWidth, ball.y * gameHeight, ball.r * gameHeight, 0, Math.PI * 2);
context.fillStyle = ballColor;
context.fill();
context.stroke()
})

context.fillStyle = thirdColor;
context.fillRect(gameState!.paddleOne!.x * gameWidth, gameState!.paddleOne!.y * gameHeight - paddleHeight / 2, paddleWidth, paddleHeight);
context.fillStyle = fourthColor;
context.fillRect(gameState!.paddleTwo!.x * gameWidth - paddleWidth, gameState!.paddleTwo!.y * gameHeight - paddleHeight / 2, paddleWidth, paddleHeight);

gameState!.BallPosition.forEach((ball) => {
context.beginPath();
context.arc(ball.x * gameWidth, ball.y * gameHeight, ball.r * gameHeight, 0, Math.PI * 2);
context.fillStyle = ballColor;
context.fill();
context.stroke()
})
}

context.fillStyle = secondaryColor;
context.fillRect(gameState!.paddleOne.x * gameWidth, gameState!.paddleOne.y * gameHeight - paddleHeight / 2, paddleWidth, paddleHeight);
context.fillRect(gameState!.paddleTwo.x * gameWidth - paddleWidth, gameState!.paddleTwo.y * gameHeight - paddleHeight / 2, paddleWidth, paddleHeight);
}
}
}, [gameState, gameWidth]);
Expand All @@ -300,41 +321,48 @@ const Game: React.FC = () => {
<div id='Game' onKeyDown={handleKeyDown} onKeyUp={handleKeyUp}>
{/* <h1>Game Page</h1> */}
<MatchsInProgress socket={socketGame} />
<div id="gamePanel">
{matchInProgress ?
<div id="players">
<div className="player">
<div>{players?.player1_login}</div>
<div>{players?.player1_score}</div>
</div>
<div id="separator"></div>
<div className="player">
<div>{players?.player2_score}</div>
<div>{players?.player2_login}</div>
</div>
</div>
: null}
<div id="gameField">
{matchInProgress || waitMatch ?
null
:
<div id="gameSelector">
{/* <h2>Select your opponent</h2>
<SearchUserBar /> */}
<h2>Select your game</h2>
<div id="gameButtons">
<button className={`gameButton ${waitMatch || matchInProgress ? "locked" : ""}`} onClick={launchClassic}>CLASSIC</button>
<button className={`gameButton ${waitMatch || matchInProgress ? "locked" : ""}`} onClick={launchGame}>SUPER</button>
<div id="gameContainer">
<div id="gamePanel">
{matchInProgress ?
<div id="players">
<div className="player">
<div>{players?.player1_login}</div>
<div>{players?.player1_score}</div>
</div>
<div id="separator"></div>
<div className="player">
<div>{players?.player2_score}</div>
<div>{players?.player2_login}</div>
</div>
</div>
: null}
<div id="gameField">
<canvas ref={canvasRef} tabIndex={0} width={gameWidth} height={gameHeight}></canvas>
{matchInProgress || waitMatch ?
null
:
<div id="gameSelector">
{/* <h2>Select your opponent</h2>
<SearchUserBar /> */}
<h2>Select your game</h2>
<div id="gameButtons">
<button className={`gameButton ${waitMatch || matchInProgress ? "locked" : ""}`} onClick={launchClassic}>CLASSIC</button>
<button className={`gameButton ${waitMatch || matchInProgress ? "locked" : ""}`} onClick={launchGame}>SUPER</button>
</div>
</div>

}
{waitMatch ? <div id="waitingMsg">Waiting for a worthy opponnent ...</div> : null}
{buttonReady ? <button id="readyButton" className="notReady" onClick={informReady}>{playerReady ? "Game will start soon !" : "READY ?"}</button> : null}
{timer ? <div ref={countDownDiv} id="countDown">{countdown}</div> : null}
<canvas ref={canvasRef} tabIndex={0} width={gameWidth} height={gameHeight}></canvas>
}
{waitMatch ? <div id="waitingMsg">Waiting for a worthy opponnent ...</div> : null}
{buttonReady ? <button id="readyButton" className="notReady" onClick={informReady}>{playerReady ? "Game will start soon !" : "READY ?"}</button> : null}
{timer ? <div ref={countDownDiv} id="countDown">{countdown}</div> : null}
</div>
{/* <button onClick={TEST}>TEST</button> */}
</div>
<div id="instructions">
<h2>Instructions</h2>
<div>Classic : Le pong originel</div>
<div>Super : Super mode</div>
</div>
{/* <button onClick={TEST}>TEST</button> */}
</div>
</div>
)
Expand Down
27 changes: 24 additions & 3 deletions front/react_project/src/components/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,31 @@ interface PageElement {
hit: boolean,
}

const darkenColor = function (color: string, percent: number) {
const match = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)$/);
if (!match) {
throw new Error('Invalid color string');
}

const r = parseInt(match[1]);
const g = parseInt(match[2]);
const b = parseInt(match[3]);
const a = match[4] ? parseFloat(match[4]) : 1;

const darkenedR = Math.round(r * (1 - percent / 100));
const darkenedG = Math.round(g * (1 - percent / 100));
const darkenedB = Math.round(b * (1 - percent / 100));

return `rgba(${darkenedR}, ${darkenedG}, ${darkenedB}, ${a})`;
};

const DarkenColor = function (stringColor: string, percent: number) {
let r: number = parseInt(stringColor.substring(2, 4), 16) * percent / 100;
let g: number = parseInt(stringColor.substring(4, 6), 16) * percent / 100;
let b: number = parseInt(stringColor.substring(6, 8), 16) * percent / 100;
let alpha: number = parseInt(stringColor.substring(8, 10), 16);

return (`#${Math.round(r).toString(16).padStart(2, '0')}${Math.round(g).toString(16).padStart(2, '0')}${Math.round(b).toString(16).padStart(2, '0')}`);
return (`#${Math.round(r).toString(16).padStart(2, '0')}${Math.round(g).toString(16).padStart(2, '0')}${Math.round(b).toString(16).padStart(2, '0')}${alpha.toString(16).padStart(2, '0')}`);
}

const style = getComputedStyle(document.documentElement);
Expand Down Expand Up @@ -61,7 +80,7 @@ const BallContainer = (props: BallContainerProps) => {
const updateBalls = (balls: BallProps[], CONTAINER_HEIGHT: number, CONTAINER_WIDTH: number, pageElements: { element: DOMRect | null, hit: boolean }[]) => {
const gravity = 0.01;
const frottement = 0.998;
const restitution = 0.98;
const restitution = 0.93;

for (let i = 0; i < balls.length; i++) {
const ball = balls[i];
Expand All @@ -83,6 +102,8 @@ const updateBalls = (balls: BallProps[], CONTAINER_HEIGHT: number, CONTAINER_WID
if (ball.vy > 1.5) {
pageElements[j].hit = true;
}
if (ball.vy < 0.12)
ball.vy = 0;
ball.vy *= -restitution;
ball.y += ball.vy;
}
Expand Down Expand Up @@ -313,7 +334,7 @@ const Home: React.FC = () => {
<div id="title">

<div>
<h1 ref={h1_title} onMouseEnter={onHoverTitle} onMouseLeave={mouseLeave} className="navLink" >ft_transcendance</h1>
<h1 ref={h1_title} onMouseEnter={onHoverTitle} onMouseLeave={mouseLeave} className="navLink" >ft_transcendence</h1>
<div className="shadow"></div>
</div>
</div>
Expand Down
32 changes: 21 additions & 11 deletions front/react_project/src/components/MatchsInProgress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import "../styles/MatchInProgress.scss"
import React, { useState, useEffect } from 'react'
import { Socket } from 'socket.io-client'
import { DefaultEventsMap } from "@socket.io/component-emitter";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCircle } from "@fortawesome/free-solid-svg-icons";


interface MatchState {
Expand All @@ -29,10 +31,15 @@ const MatchsInProgress: React.FC<inProgressProps> = (props) => {

const [matchs, setMatchs] = useState<MatchState[]>([
{player1_login: "JOUEUR1", player2_login: "JOUEUR2", player1_score: 3, player2_score: 1, super_game_mode: false, game_has_started: true},
{player1_login: "Roger", player2_login: "Connard", player1_score: 2, player2_score: 0, super_game_mode: false, game_has_started: true},
{player1_login: "Michellangelloooooooooooooooooooooooooooooooooooooiiiiii", player2_login: "Oui", player1_score: 0, player2_score: 10, super_game_mode: false, game_has_started: true},
{player1_login: "Rorger", player2_login: "Conrnard", player1_score: 2, player2_score: 0, super_game_mode: false, game_has_started: true},
// {player1_login: "Roger", player2_login: "Connard", player1_score: 2, player2_score: 0, super_game_mode: false, game_has_started: true},
// {player1_login: "Michellangelloooooooooooooooooooooooooooooooooooooiiiiii", player2_login: "Michellangelloooooooooooooooooooooooooooooooooooooiiiiiifez", player1_score: 0, player2_score: 10, super_game_mode: false, game_has_started: true},
// {player1_login: "Michellangelloooooooooooiiiiii", player2_login: "Oui", player1_score: 0, player2_score: 10, super_game_mode: false, game_has_started: true},
{player1_login: "Michellangeiiii", player2_login: "Ouiii", player1_score: 0, player2_score: 10, super_game_mode: false, game_has_started: true},
]);



// useEffect(() => {
// console.log("display matchs", matchs);
// }, [matchs])
Expand Down Expand Up @@ -70,12 +77,14 @@ const MatchsInProgress: React.FC<inProgressProps> = (props) => {
console.log('match end', matchEnd);
setMatchs(matchs.filter(match => match.player1_login !== matchEnd.player1_login));
})



}
}, [props.socket]);

const watchMatch = (event: React.MouseEvent<HTMLDivElement>) => {
// console.log("event", event.currentTarget.attributes);
// console.log("je veux voir le match de ", event.currentTarget.getAttribute('data-key'));
props.socket.emit('Spectator_Request', {player1_login: event.currentTarget.getAttribute('data-key')} )
}

return (
<div id="matchsInProgress">
Expand All @@ -92,17 +101,18 @@ const MatchsInProgress: React.FC<inProgressProps> = (props) => {

matchs.map((match: MatchState) => {
return (
<div className="match" key={match.player1_login}>
<div>{match.player1_login}</div>
<div>{match.player1_score}</div>
<div>{match.player2_score}</div>
<div>{match.player2_login}</div>
<div className="match" key={match.player1_login} data-key={match.player1_login} onClick={watchMatch}>
<div><span>{match.player1_login}</span></div>
<div><span>{match.player1_score}</span></div>
<div className="watchMatch">Watch in direct<FontAwesomeIcon icon={faCircle} className="redDot"/></div>
<div><span>{match.player2_score}</span></div>
<div><span>{match.player2_login}</span></div>
</div>
)
})
:
<div id="noMatch">
No Match in progress
<p>No Match in progress</p>
</div>
}
</div>
Expand Down
10 changes: 5 additions & 5 deletions front/react_project/src/services/account.service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ let uploadAvatar = (file: string) => {
}
// Fonction qui check si user est connecté. Et que le token n'est pas expiré
let isLogged = () => {
let token = localStorage.getItem('token');
let token = sessionStorage.getItem('token');
if (token !== null) {
let decodedToken: JwtPayload = accountService.readPayload()!;
if (decodedToken === null || decodedToken === undefined || ( decodedToken.exp !== undefined && decodedToken.exp < Date.now() / 1000)) {
Expand All @@ -39,16 +39,16 @@ let generateToken = (login: string) => {
return Axios.post('auth/generateToken', {login});
}
let saveToken = (token: string) => {
localStorage.setItem('token', token);
sessionStorage.setItem('token', token);
}
//get token from local storage
let getToken = () => {
return localStorage.getItem('token');
return sessionStorage.getItem('token');
}
// Lorsqu'un user se logOut, une requete est envoyée au back pour l'en informer et le token est enlevé de localStorage
// Lorsqu'un user se logOut, une requete est envoyée au back pour l'en informer et le token est enlevé de sessionStorage
let logout = () => {
Axios.post('/auth/logout');
localStorage.removeItem('token');
sessionStorage.removeItem('token');
}
// Fonction qui decrypt le JWT et retourne un objet contenant les infos cryptées dans le JWT (id, login, date expiration du token etc..)
let readPayload = () => {
Expand Down

0 comments on commit f693d9f

Please sign in to comment.