Game, suite et presque fin ?

This commit is contained in:
batche
2022-12-19 20:58:46 +01:00
parent 27a4bfae7a
commit dbd95089a8
14 changed files with 384 additions and 238 deletions

View File

@@ -1,4 +1,5 @@
NODE_ENV=development
WEBSITE_HOST=transcendance
POSTGRES_USER=postgres
POSTGRES_PASSWORD=9pKpKEgiamxwk5P7Ggsz
POSTGRES_DB=transcendance_db

View File

@@ -14,6 +14,7 @@ import { GameModule } from './game/game.module';
AuthenticationModule,
PassportModule.register({ session: true }),
FriendshipsModule,
GameModule,
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: 'postgres',
@@ -27,7 +28,6 @@ import { GameModule } from './game/game.module';
//avec une classe pour le module
synchronize: true,
}),
GameModule,
],
controllers: [AppController],
providers: [AppService],

View File

@@ -1,11 +1,12 @@
import { IsBoolean, IsInt, IsNotEmpty, IsNumber, IsString } from "class-validator";
import { IsBoolean, IsEmpty, IsInt, IsNotEmpty, IsNumber, IsString } from "class-validator";
import { IsNull } from "typeorm";
export class GrantTicketDto {
@IsString()
@IsNotEmpty()
playerOneUsername : string
@IsString()
playerTwousername : string
playerTwoUsername : string
@IsNumber()
gameOptions : number
@IsBoolean()

View File

@@ -1,17 +1,15 @@
import { IsBase64, IsBoolean, IsNotEmpty, IsNumber, IsString } from "class-validator";
import { IsBase64, IsBoolean, IsEmpty, IsNotEmpty, IsNumber, IsString } from "class-validator";
export class ValidateTicketDto {
@IsString()
@IsNotEmpty()
playerOneUsername : string
@IsString()
playerTwousername : string
playerTwoUsername : string
@IsNumber()
gameOptions : number
@IsBoolean()
isGameIsWithInvitation : boolean
@IsNumber()
numberOfRegisteredUser : number
@IsBase64()
@IsNotEmpty()
token : string

View File

@@ -8,13 +8,15 @@ export class TokenGame {
@Column()
playerOneUsername : string
@Column({nullable: true})
playerTwousername : string
playerTwoUsername : string
@Column()
gameOptions : number
@Column()
isGameIsWithInvitation : boolean
@Column({default: 0, nullable: true})
numberOfRegisteredUser : number
@Column({default : false})
isSecondUserAcceptedRequest : boolean
@Column()
token : string
}

View File

@@ -10,8 +10,7 @@ import { GameService } from './game.service';
@Controller('game')
export class GameController {
constructor (private readonly gameService : GameService,
private readonly userService : UsersService) { }
constructor (private readonly gameService : GameService) { }
@Post('ticket')
@UseGuards(AuthenticateGuard)
@@ -22,10 +21,20 @@ export class GameController {
if (grantTicketDto.playerOneUsername != user.username)
return new HttpException('You can\'t request a game for another person.', 403 )
else if (user.status !== "connected")
return new HttpException('You must not be in game...', 403 )
return new HttpException('You must not be in game...', HttpStatus.FORBIDDEN )
return this.gameService.generateToken(user, grantTicketDto);
}
@Get('requested')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async requestIfAnotherUserHasRespondToquestForGame(@Req() req, @Body('playerTwoUsername') body)
{
const user : User = req.user;
return this.gameService.requestIfAnotherUserHasRespondToquestForGame(user, body);
}
//N'est valable que pour le game-serveur.
@Post('gameServer/validate')
async validateTicket(@Body() validateTicketDto : ValidateTicketDto, @Req() request)
@@ -38,12 +47,19 @@ export class GameController {
@Post('decline')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async declineInvitation(@Body() validateTicketDto : ValidateTicketDto, @Req() req)
async declineInvitation(@Body('token') token, @Req() req)
{
const user : User = req.user;
if (user.username !== validateTicketDto.playerTwousername)
return new HttpException("This cannot be done", HttpStatus.FORBIDDEN);
return this.gameService.declineInvitation(validateTicketDto);
return this.gameService.declineInvitation(user, token);
}
@Post('accept')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async acceptInvitation(@Body('token') token, @Req() req)
{
const user : User = req.user;
return this.gameService.acceptInvitation(user, token);
}
@Get('invitations')

View File

@@ -1,14 +1,17 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Friendship } from 'src/friendship/entities/friendship.entity';
import { FriendshipService } from 'src/friendship/friendship.service';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import { Game } from './entity/game.entity';
import { TokenGame } from './entity/tokenGame.entity';
import { GameController } from './game.controller';
import { GameService } from './game.service';
@Module({
imports: [TypeOrmModule.forFeature([TokenGame, User])],
imports: [TypeOrmModule.forFeature([TokenGame, User, Game, Friendship])],
controllers: [GameController],
providers: [GameService, UsersService]
providers: [GameService, UsersService, FriendshipService]
})
export class GameModule {}

View File

@@ -8,6 +8,7 @@ import { GrantTicketDto } from './dto/grantTicket.dto';
import { Game } from './entity/game.entity';
import { ValidateTicketDto } from './dto/validateTicket.dto';
import { TokenGame } from './entity/tokenGame.entity';
import { UsersService } from 'src/users/users.service';
@Injectable()
export class GameService {
@@ -18,6 +19,7 @@ export class GameService {
private readonly userRepository : Repository<User>,
@InjectRepository(TokenGame)
private readonly tokenGameRepository : Repository<TokenGame>,
private readonly userService : UsersService
) { }
async encryptToken(toEncrypt : string) : Promise<string> {
@@ -35,38 +37,28 @@ export class GameService {
async generateToken(user : User, grantTicketDto : GrantTicketDto)
{
if (grantTicketDto.isGameIsWithInvitation === true)
if (user.status === "In Game")
return new HttpException("You can't play two games", HttpStatus.FORBIDDEN);
else if (grantTicketDto.isGameIsWithInvitation === true)
{
let secondUser : User;
(user.username === grantTicketDto.playerOneUsername) ?
secondUser = await this.userRepository.findOneBy({username : grantTicketDto.playerTwousername}) :
secondUser = await this.userRepository.findOneBy({username : grantTicketDto.playerOneUsername})
const secondUser : Partial<User> = await this.userService.findOneByUsername(user.id.toString(), grantTicketDto.playerTwoUsername)
if (!secondUser)
return new HttpException("The requested second player does not exist", HttpStatus.NOT_FOUND);
const encryptedTextToReturn = await this.encryptToken(user.username + '_' + secondUser.username + '_'
+ grantTicketDto.gameOptions + '_' + grantTicketDto.isGameIsWithInvitation + '_' + new Date())
const validateTicketDto : ValidateTicketDto = new ValidateTicketDto();
validateTicketDto.playerOneUsername = grantTicketDto.playerOneUsername;
validateTicketDto.playerTwousername = grantTicketDto.playerTwousername;
validateTicketDto.numberOfRegisteredUser = 0;
validateTicketDto.isGameIsWithInvitation = grantTicketDto.isGameIsWithInvitation;
validateTicketDto.gameOptions = grantTicketDto.gameOptions;
validateTicketDto.token = encryptedTextToReturn;
const tok = this.tokenGameRepository.create(validateTicketDto);
const tok = this.tokenGameRepository.create(grantTicketDto);
tok.isSecondUserAcceptedRequest = false;
tok.numberOfRegisteredUser = 0;
tok.token = encryptedTextToReturn;
this.tokenGameRepository.save(tok);
return { token : encryptedTextToReturn };
}
else if (grantTicketDto.isGameIsWithInvitation === false) {
const encryptedTextToReturn = await this.encryptToken(user.username + '_'
+ grantTicketDto.gameOptions + '_' + grantTicketDto.isGameIsWithInvitation + '_' + new Date())
const validateTicketDto : ValidateTicketDto = new ValidateTicketDto();
validateTicketDto.playerOneUsername = grantTicketDto.playerOneUsername;
validateTicketDto.playerTwousername = "";
validateTicketDto.numberOfRegisteredUser = 0;
validateTicketDto.isGameIsWithInvitation = grantTicketDto.isGameIsWithInvitation;
validateTicketDto.gameOptions = grantTicketDto.gameOptions;
validateTicketDto.token = encryptedTextToReturn;
const tok = this.tokenGameRepository.create(validateTicketDto);
const tok = this.tokenGameRepository.create(grantTicketDto);
tok.numberOfRegisteredUser = 0;
tok.token = encryptedTextToReturn;
this.tokenGameRepository.save(tok);
return { token : encryptedTextToReturn };
}
@@ -74,51 +66,64 @@ export class GameService {
}
async validateToken(validateTicketDto : ValidateTicketDto) {
let tokenGame : TokenGame;
if (validateTicketDto.isGameIsWithInvitation === true)
{
tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.where('tokenGame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokenGame.playerTwousername = :playerTwousername', {playerTwousername : validateTicketDto.playerTwousername})
.andWhere('tokenGame.gameOption = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokenGame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: validateTicketDto.isGameIsWithInvitation})
.andWhere('tokenGame.token = :token', {token : validateTicketDto.token})
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : validateTicketDto.playerTwoUsername})
.andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: true})
.andWhere('tokengame.isSecondUserAcceptedRequest = :choice', {choice : true})
.andWhere('tokengame.token = :token', {token : validateTicketDto.token})
.getOne();
if (tokenGame)
{
tokenGame.numberOfRegisteredUser++;
if (tokenGame.numberOfRegisteredUser === 2)
{
this.tokenGameRepository.remove(tokenGame)
const userOne : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerOneUsername})
.getOne();
userOne.status = "In Game";
this.userRepository.save(userOne);
const userTwo : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerTwoUsername})
.getOne();
userTwo.status = "In Game";
this.userRepository.save(userTwo);
}
return true;
}
}
else
else if (validateTicketDto.isGameIsWithInvitation === false)
{
tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.where('tokenGame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokenGame.gameOption = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokenGame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: validateTicketDto.isGameIsWithInvitation})
.andWhere('tokenGame.token = :token', {token : validateTicketDto.token})
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: false})
.andWhere('tokengame.token = :token', {token : validateTicketDto.token})
.getOne();
}
if (tokenGame)
tokenGame.numberOfRegisteredUser++;
if (tokenGame && tokenGame.isGameIsWithInvitation === false)
{
this.tokenGameRepository.remove(tokenGame)
this.userRepository.update(tokenGame.playerOneUsername, {status : "In Game"})
return true;
}
else if (tokenGame && tokenGame.isGameIsWithInvitation === true)
{
if (tokenGame.numberOfRegisteredUser === 2)
if (tokenGame)
{
this.tokenGameRepository.remove(tokenGame)
this.userRepository.update(tokenGame.playerOneUsername, {status : "In Game"})
this.userRepository.update(tokenGame.playerTwousername, {status : "In Game"})
console.log("USERNAME : " + tokenGame.playerOneUsername)
const user : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerOneUsername})
.getOne();
user.status = "In Game";
this.userRepository.save(user);
return true;
}
return true;
}
return false;
}
async findInvitations(user : User) {
const game = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokenGame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.where('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokengame.isGameIsWithInvitation = :invit', {invit : true})
.andWhere('tokengame.isSecondUserAcceptedRequest = :choice', {choice : false})
.getMany();
if (!game)
return new HttpException( "No invitations !", HttpStatus.NOT_FOUND);
@@ -126,25 +131,57 @@ export class GameService {
for (const gameToken of game) {
partialGame.push({
playerOneUsername : gameToken.playerOneUsername,
playerTwousername : gameToken.playerTwousername,
playerTwoUsername : gameToken.playerTwoUsername,
gameOptions : gameToken.gameOptions,
isGameIsWithInvitation : gameToken.isGameIsWithInvitation,
token : gameToken.token,
});
}
return partialGame;
}
async declineInvitation(validateTicketDto : ValidateTicketDto)
async declineInvitation(user : User, token : string)
{
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.where('tokenGame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokenGame.playerTwousername = :playerTwousername', {playerTwousername : validateTicketDto.playerTwousername})
.andWhere('tokenGame.gameOption = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokenGame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: validateTicketDto.isGameIsWithInvitation})
.andWhere('tokenGame.token = :token', {token : validateTicketDto.token})
if (user.status === "In Game")
return new HttpException("You must finish your game before decline.", HttpStatus.FORBIDDEN)
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokengame.token = :token', {token : token})
.getOne();
return this.tokenGameRepository.remove(tokenGame);
if (tokenGame)
return this.tokenGameRepository.remove(tokenGame);
return new HttpException("Invitation not found !", HttpStatus.NOT_FOUND)
}
async acceptInvitation(user : User, token : string)
{
if (user.status === "In Game")
return new HttpException("You must finish your game before accept.", HttpStatus.FORBIDDEN)
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.andWhere('tokenGame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokenGame.token = :token', {token : token})
.getOne();
if (tokenGame)
{
tokenGame.isSecondUserAcceptedRequest = true;
this.tokenGameRepository.save(tokenGame)
return HttpStatus.OK
}
return new HttpException("Invitation not found !", HttpStatus.NOT_FOUND)
}
async requestIfAnotherUserHasRespondToquestForGame(user : User, token : string) {
if (user.status === "In Game")
return new HttpException("You can't do that.", HttpStatus.BAD_REQUEST)
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.andWhere('tokenGame.token = :token', {token : token})
.andWhere('tokenGame.isSecondUserAcceptedRequest = :isSecondUserAcceptedRequest', {isSecondUserAcceptedRequest : true})
.getOne();
if (tokenGame && tokenGame.isSecondUserAcceptedRequest === true)
return {isSecondUserAcceptedRequest : true}
else if (tokenGame && tokenGame.isSecondUserAcceptedRequest === false)
return {isSecondUserAcceptedRequest : false}
else if (!tokenGame)
return new HttpException("Not Found", HttpStatus.NOT_FOUND)
}
}

View File

@@ -85,7 +85,7 @@ export class UsersController {
const user = await this.usersService.update(req.user.id, usersUpdateDto);
if (user.isEnabledTwoFactorAuth === false && user.isTwoFactorAuthenticated === true)
this.usersService.setIsTwoFactorAuthenticatedWhenLogout(user.id);
console.log ("Enbale 2FA " + user.isEnabledTwoFactorAuth + " Is authenticated " + user.isTwoFactorAuthenticated);
console.log ("Enable 2FA " + user.isEnabledTwoFactorAuth + " Is authenticated " + user.isTwoFactorAuthenticated);
if (user.isEnabledTwoFactorAuth === true && user.isTwoFactorAuthenticated === false)
{
response.status(201).send('2FA redirect')

View File

@@ -4,12 +4,9 @@ import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { CreateUsersDto } from './dto/create-users.dto';
import { UpdateUsersDto } from './dto/update-users.dto';
import { Friendship } from '../friendship/entities/friendship.entity';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { UserStats } from './entities/userStat.entities';
import { FriendshipService } from 'src/friendship/friendship.service';
import { stringify } from 'querystring';
// On va devoir sûrement trouver un moyen plus simple pour passer l'id, sûrement via des pipes
// ou des interceptors, mais pour l'instant on va faire comme ça.
@Injectable()

View File

@@ -2,7 +2,7 @@
// routing
// may not need {link} here
import Router, { link, replace } from "svelte-spa-router";
import { primaryRoutes } from "./routes/primaryRoutes.js";
import { primaryRoutes } from "./routes/primaryRoutes.js";
// import primaryRoutes from "./routes/primaryRoutes.svelte";
const conditionsFailed = (event) => {

View File

@@ -1,106 +0,0 @@
<script lang="ts">
// import { initDom } from "../game/client/pong.js";
import {onMount} from 'svelte';
onMount(() => {
// initDom();
})
</script>
<body>
<div id="div_game_options">
<fieldset>
<legend>game options</legend>
<div>
<input type="checkbox" id="multi_balls" name="multi_balls">
<label for="multi_balls">multiples balls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls">
<label for="moving_walls">moving walls</label>
</div>
<div>
<label>sound :</label>
<input type="radio" id="sound_on" name="sound_selector" checked>
<label for="sound_on">on</label>
<input type="radio" id="sound_off" name="sound_selector">
<label for="sound_off">off</label>
</div>
<div>
<button id="play_pong_button">PLAY</button>
</div>
</fieldset>
</div>
<div id="div_game_instructions">
<h2>--- keys ---</h2>
<p>move up: 'w' or 'up arrow'</p>
<p>move down: 's' OR 'down arrow'</p>
<p>grid on/off: 'g'</p>
</div>
<div id="canvas_container">
<!-- <p> =) </p> -->
</div>
<!-- <script src="http://localhost:8080/js/pong.js" type="module" defer></script> -->
</body>
<style>
@font-face {
font-family: "Bit5x3";
src: url("/fonts/Bit5x3.woff2") format("woff2"),
url("/fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
body {
margin: 0;
background-color: #222425;
}
#canvas_container {
margin-top: 20px;
text-align: center;
/* border: dashed rgb(245, 245, 245) 5px; */
/* max-height: 80vh; */
/* overflow: hidden; */
}
#div_game_instructions {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: large;
}
#div_game_options {
margin-top: 20px;
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: x-large;
}
#div_game_options fieldset {
max-width: 50vw;
width: auto;
margin: 0 auto;
}
#div_game_options fieldset div {
padding: 10px;
}
#play_pong_button {
font-family: "Bit5x3";
color: rgb(245, 245, 245);
background-color: #333333;
font-size: x-large;
padding: 10px;
}
canvas {
background-color: #333333;
max-width: 75vw;
/* max-height: 100vh; */
width: 80%;
}
</style>

View File

@@ -1,39 +1,153 @@
<script lang="ts">
import { onMount } from "svelte";
import * as enumeration from './shared_js/enums'
import * as constants from './client/constants'
import { initPong, initGc, initMatchOptions, initStartFunction } from './client/global'
import { GameArea } from './client/class/GameArea';
import { GameComponentsClient } from './client/class/GameComponentsClient';
import { handleInput } from './client/handleInput';
import {gameLoop} from './client/gameLoop'
import { gameLoop } from './client/gameLoop'
import { drawLoop } from './client/draw';
import {countdown} from './client/utils'
import { countdown } from './client/utils'
import { initWebSocket } from './client/ws';
import { initAudio } from './client/audio';
import { pong, gc} from './client/global'
import Header from '../../pieces/Header.svelte';
let user;
let optionsAreNotSet = true
let sound = false;
let multi_balls = false;
let moving_walls = false;
let matchOption : enumeration.MatchOptions = enumeration.MatchOptions.noOption;
let invite_someone = false;
let allUsers;
let playerTwoUsername;
let showInvitations = false;
let showGameOption = true;
let isThereAnyInvitation = false;
let invitations;
let showError = false;
let showWaitPage = false;
let waitingMessage = "Please wait..."
let errorMessageWhenAttemptingToGetATicket;
let token = ""
let responseToCheckIfOtherUserHasAnswered;
let isSecondPlayerAnsweredYes = false;
let isSecondPlayerRefused = false;
let isSomethingWentWrong = true;
onMount( async() => {
user = await fetch('http://transcendance:8080/api/v2/user')
.then( (x) => x.json() );
allUsers = await fetch('http://transcendance:8080/api/v2/user/all')
.then( x => x.json() );
})
// En async au cas où pour la suite mais apriori inutile, les check se feront sûrement au onMount
const init = async() => {
optionsAreNotSet = false
showWaitPage = true
console.log("Player two username " + playerTwoUsername)
if (multi_balls === true)
matchOption |= enumeration.MatchOptions.multiBalls
if (moving_walls === true )
matchOption |= enumeration.MatchOptions.movingWalls
initAudio(sound)
initMatchOptions(matchOption)
optionsAreNotSet = false
initPong(new GameArea())
initGc(new GameComponentsClient(matchOption, pong.ctx))
initStartFunction(start)
initWebSocket(matchOption)
const res = await fetch("http://transcendance:8080/api/v2/game/ticket", {
method : "POST",
headers : {'Content-Type': 'application/json'},
body : JSON.stringify({
playerOneUsername : user.username,
playerTwoUsername : playerTwoUsername,
gameOptions : matchOption,
isGameIsWithInvitation : invite_someone
})
})
.then(x => x.json())
.catch(error => {
console.log(error)
})
if (res.status === 403 || res.status === 404 || res.status === 500)
{
errorMessageWhenAttemptingToGetATicket = res.message;
showError = true;
setTimeout(() => {
showError = false;
showWaitPage = false
optionsAreNotSet = true
playerTwoUsername = "";
matchOption = 0;
token = ""
}, 5000)
return ;
}
if (invite_someone === true)
{
token = res.token;
waitingMessage = `Waiting for ${playerTwoUsername}'s answer !`
let intervalId = setInterval(checkIfOtherUserIsReady , 1000 * 1);
let timeOutId = setTimeout(()=> {
showError = true;
errorMessageWhenAttemptingToGetATicket = "The second player took too much time to answer"
showWaitPage = false
optionsAreNotSet = true
isSecondPlayerAnsweredYes = false
playerTwoUsername = "";
matchOption = 0;
token = ""
clearInterval(intervalId)
isSomethingWentWrong = true
}, 1000 * 60 * 3)
if (isSecondPlayerAnsweredYes === true)
{
clearTimeout(timeOutId)
isSomethingWentWrong = false;
}
else if (isSecondPlayerRefused === true)
{
clearTimeout(timeOutId)
}
}
if (isSomethingWentWrong === false)
{
initAudio(sound)
initMatchOptions(matchOption)
initPong(new GameArea())
initGc(new GameComponentsClient(matchOption, pong.ctx))
initStartFunction(start)
initWebSocket(matchOption)
}
}
async function checkIfOtherUserIsReady(token : string) {
responseToCheckIfOtherUserHasAnswered = await fetch("http://transcendance:8080/api/v2/game/pending",{
method : "POST",
headers : { 'Content-Type': 'application/json'},
body : JSON.stringify({
token : token
})
})
const data = await responseToCheckIfOtherUserHasAnswered.json();
if (data.isSecondUserAcceptedRequest === true)
isSecondPlayerAnsweredYes = true
if (data.status === 404 || data.status === 403)
{
isSecondPlayerRefused = true
errorMessageWhenAttemptingToGetATicket = data.message;
}
}
function start() : void {
@@ -54,47 +168,121 @@
pong.deleteKey(e.key);
});
pong.handleInputInterval = window.setInterval(handleInput, constants.handleInputIntervalMS);
// pong.handleInputInterval = window.setInterval(sendLoop, c.sendLoopIntervalMS);
pong.gameLoopInterval = window.setInterval(gameLoop, constants.gameLoopIntervalMS);
pong.drawLoopInterval = window.setInterval(drawLoop, constants.drawLoopIntervalMS);
}
const showOptions = () => {
showGameOption = true
showInvitations = false
}
const showInvitation = async() => {
showGameOption = false;
showInvitations = true;
invitations = await fetch("http://transcendance:8080/api/v2/game/invitations")
.then(x => x.json())
}
const rejectInvitation = async() => {
await fetch("http://transcendance:8080/api/v2/game/decline",{
method: "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
})
})
}
const acceptInvitation = async() => {
await fetch("http://transcendance:8080/api/v2/game/accept",{
method: "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
})
})
}
</script>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<Header />
<body>
<div id="preload_font">.</div>
{#if optionsAreNotSet}
<form on:submit|preventDefault={init}>
<div id="div_game_options">
<fieldset>
<legend>game options</legend>
<div>
<input type="checkbox" id="multi_balls" name="multi_balls" bind:checked={multi_balls}>
<label for="multi_balls">Multiples balls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls" bind:checked={moving_walls}>
<label for="moving_walls">Moving walls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls" bind:checked={sound}>
<label for="moving_walls">Sound</label>
</div>
<div>
<button id="play_pong_button" >PLAY</button>
</div>
</fieldset>
{#if showError === true}
<div id="error_notification" >
<p>{errorMessageWhenAttemptingToGetATicket}</p>
</div>
</form>
<div id="div_game_instructions">
<h2>--- keys ---</h2>
<p>move up: 'w' or 'up arrow'</p>
<p>move down: 's' OR 'down arrow'</p>
<p>grid on/off: 'g'</p>
</div>
{/if}
{#if showWaitPage === true}
<fieldset>
<legend>Connecting to the game...</legend>
<div id="div_game">
<p>{waitingMessage}</p>
</div>
</fieldset>
{/if}
{#if optionsAreNotSet}
{#if showGameOption === true}
<form on:submit|preventDefault={init}>
<div id="div_game">
<button id="pong_button" on:click={showInvitation}>Show invitations</button>
<fieldset>
<legend>game options</legend>
<div>
<input type="checkbox" id="multi_balls" name="multi_balls" bind:checked={multi_balls}>
<label for="multi_balls">Multiples balls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls" bind:checked={moving_walls}>
<label for="moving_walls">Moving walls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls" bind:checked={sound}>
<label for="moving_walls">Sound</label>
</div>
<div>
<input type="checkbox" id="invite_someone" name="moving_walls" bind:checked={invite_someone}>
<label for="moving_walls">Invite a friend</label>
</div>
{#if invite_someone === true}
<select bind:value={playerTwoUsername}>
{#each allUsers as user }
<option value={user.username}>{user.username}</option>
{/each}
</select>
{/if}
<div>
<button id="pong_button" >PLAY</button>
</div>
</fieldset>
</div>
</form>
{/if}
{#if showInvitations}
<div id="div_game">
<button id="pong_button" on:click={showOptions}>Play a Game</button>
<fieldset>
<legend>Current invitation(s)</legend>
{#if isThereAnyInvitation}
{#each invitations as invitation }
<div>
{invitation.playerOneUsername} has invited you to play a pong !
<button id="pong_button" on:click={acceptInvitation}>V</button>
<button id="pong_button" on:click={rejectInvitation}>X</button>
</div>
{/each}
{/if}
{#if isThereAnyInvitation ===false}
<p>Currently, no one asked to play with you.</p>
<button id="pong_button" on:click={showInvitation}>Reload</button>
{/if}
</fieldset>
</div>
{/if}
{/if}
<div id="canvas_container">
@@ -128,21 +316,29 @@ body {
/* max-height: 80vh; */
/* overflow: hidden; */
}
#div_game_options {
#div_game {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: x-large;
}
#div_game_options fieldset {
#error_notification {
text-align: center;
display: block;
font-family: "Bit5x3";
color: rgb(143, 19, 19);
font-size: x-large;
}
#div_game fieldset {
max-width: 50vw;
width: auto;
margin: 0 auto;
}
#div_game_options fieldset div {
#div_game fieldset div {
padding: 10px;
}
#play_pong_button {
#pong_button {
font-family: "Bit5x3";
color: rgb(245, 245, 245);
background-color: #333333;

View File

@@ -24,6 +24,7 @@
<img src="/img/potato_logo.png" alt="Potato Pong Logo" on:click={() => (push('/'))}>
<h1>Potato Pong</h1>
<nav>
<button on:click={() => (push('/game'))}>Game</button>
{#if $location !== '/profile'}
<button on:click={() => (push('/profile'))}>My Profile</button>
{:else if $location === '/profile'}