Le multijoueur fonctionne enfin. Mise à jour des scores. Et de la partie.

This commit is contained in:
batche
2022-12-21 15:22:07 +01:00
parent d6da8bf70b
commit cc797d1118
11 changed files with 218 additions and 124 deletions

View File

@@ -240,9 +240,9 @@ export class GameSession {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
id: this.id, gameServerIdOfTheMatch: this.id,
scoreLeft: gc.scoreLeft, playerOneUsernameResult: gc.scoreLeft,
scoreRight: gc.scoreRight, playerTwoUsernameResult: gc.scoreRight,
}) })
}); });

View File

@@ -168,7 +168,7 @@ function privateMatchmaking(player: ClientPlayer)
const maxPlayersNumber = 2; const maxPlayersNumber = 2;
privateMatchmakingMap.set(player.id, player); privateMatchmakingMap.set(player.id, player);
const matchOptions = player.matchOptions; const matchOptions = player.matchOptions;
console.log(player)
const token = player.token; const token = player.token;
const compatiblePlayers: ClientPlayer[] = []; const compatiblePlayers: ClientPlayer[] = [];
for (const [id, client] of privateMatchmakingMap) for (const [id, client] of privateMatchmakingMap)
@@ -254,6 +254,8 @@ async function playerReadyConfirmationListener(this: WebSocket, data: string)
gameOptions: gameSession.matchOptions, gameOptions: gameSession.matchOptions,
playerOneUsername: (<ClientPlayer>gameSessionPlayersIterator.next().value).username, playerOneUsername: (<ClientPlayer>gameSessionPlayersIterator.next().value).username,
playerTwoUsername: (<ClientPlayer>gameSessionPlayersIterator.next().value).username, playerTwoUsername: (<ClientPlayer>gameSessionPlayersIterator.next().value).username,
playerOneUsernameResult : 0,
playerTwoUsernameResult : 0
}) })
}); });

View File

@@ -12,4 +12,8 @@ export class CreateGameDto {
playerOneUsername : string playerOneUsername : string
@IsString() @IsString()
playerTwoUsername : string playerTwoUsername : string
@IsNumber()
playerTwoUsernameResult : number
@IsNumber()
playerOneUsernameResult : number
} }

View File

@@ -1,15 +1,5 @@
import { OmitType } from "@nestjs/mapped-types";
import { IsBoolean, IsNotEmpty, IsNumber, IsString } from "class-validator"; import { IsBoolean, IsNotEmpty, IsNumber, IsString } from "class-validator";
import { CreateGameDto } from "./createGame.dto";
export class UpdateGameDto { export class UpdateGameDto extends OmitType(CreateGameDto, ['playerOneUsername', 'playerTwoUsername', 'gameOptions'] as const){}
@IsString()
@IsNotEmpty()
gameServerIdOfTheMatch : string
@IsNumber()
@IsNotEmpty()
playerOneUsernameResult : number
@IsNumber()
@IsNotEmpty()
playerTwoUsernameResult : number
@IsBoolean()
isMatchIsFinished : boolean
}

View File

@@ -17,7 +17,7 @@ export class Game {
@Column({default : 0, nullable : true}) @Column({default : 0, nullable : true})
playerTwoUsernameResult : number playerTwoUsernameResult : number
@Column() @Column({unique : true})
gameServerIdOfTheMatch: string gameServerIdOfTheMatch: string
@Column({default: false, nullable : true}) //éric pourra trouver un meilleur mot : ongoing ? @Column({default: false, nullable : true}) //éric pourra trouver un meilleur mot : ongoing ?

View File

@@ -7,6 +7,7 @@ import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service'; import { UsersService } from 'src/users/users.service';
import { CreateGameDto } from './dto/createGame.dto'; import { CreateGameDto } from './dto/createGame.dto';
import { GrantTicketDto } from './dto/grantTicket.dto'; import { GrantTicketDto } from './dto/grantTicket.dto';
import { UpdateGameDto } from './dto/updateGame.dto';
import { ValidateTicketDto } from './dto/validateTicket.dto'; import { ValidateTicketDto } from './dto/validateTicket.dto';
import { TokenGame } from './entity/tokenGame.entity'; import { TokenGame } from './entity/tokenGame.entity';
import { GameService } from './game.service'; import { GameService } from './game.service';
@@ -78,9 +79,19 @@ export class GameController {
@Post('gameserver/creategame') @Post('gameserver/creategame')
async createGame(@Body() creategameDto : CreateGameDto) async createGame(@Body() creategameDto : CreateGameDto)
{ {
console.log("On est dans create game")
console.log(creategameDto)
return this.gameService.createGame(creategameDto); return this.gameService.createGame(creategameDto);
} }
@Post('gameserver/updategame')
async updateGame(@Body() updateGameDto : UpdateGameDto)
{
console.log("On est dans update game")
console.log(updateGameDto)
return this.gameService.updateGame(updateGameDto);
}
} }

View File

@@ -10,6 +10,7 @@ import { ValidateTicketDto } from './dto/validateTicket.dto';
import { TokenGame } from './entity/tokenGame.entity'; import { TokenGame } from './entity/tokenGame.entity';
import { UsersService } from 'src/users/users.service'; import { UsersService } from 'src/users/users.service';
import { CreateGameDto } from './dto/createGame.dto'; import { CreateGameDto } from './dto/createGame.dto';
import { UpdateGameDto } from './dto/updateGame.dto';
@Injectable() @Injectable()
export class GameService { export class GameService {
@@ -68,6 +69,8 @@ export class GameService {
} }
async validateToken(validateTicketDto : ValidateTicketDto) { async validateToken(validateTicketDto : ValidateTicketDto) {
console.log("On valide le token pour : ")
console.log(validateTicketDto)
if (validateTicketDto.isGameIsWithInvitation === true) if (validateTicketDto.isGameIsWithInvitation === true)
{ {
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame') const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
@@ -138,6 +141,7 @@ export class GameService {
token : gameToken.token, token : gameToken.token,
}); });
} }
console.log("Il y a des invitations !")
return partialGame; return partialGame;
} }
@@ -145,6 +149,7 @@ export class GameService {
{ {
// if (user.status === "In Game") // if (user.status === "In Game")
// return new HttpException("You must finish your game before decline.", HttpStatus.FORBIDDEN) // return new HttpException("You must finish your game before decline.", HttpStatus.FORBIDDEN)
console.log("On décline l'invitation")
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame') const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username}) .andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokengame.token = :token', {token : token}) .andWhere('tokengame.token = :token', {token : token})
@@ -158,6 +163,7 @@ export class GameService {
{ {
// if (user.status === "In Game") // if (user.status === "In Game")
// return new HttpException("You must finish your game before accept.", HttpStatus.FORBIDDEN) // return new HttpException("You must finish your game before accept.", HttpStatus.FORBIDDEN)
console.log("On accepte l'invitation")
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame') const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.andWhere('tokenGame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username}) .andWhere('tokenGame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokenGame.token = :token', {token : token}) .andWhere('tokenGame.token = :token', {token : token})
@@ -190,11 +196,43 @@ export class GameService {
async createGame(creategameDto : CreateGameDto) async createGame(creategameDto : CreateGameDto)
{ {
const game = this.gameRepository.create(creategameDto) const game = this.gameRepository.create(creategameDto)
game.isMatchIsFinished = false;
this.gameRepository.save(game); this.gameRepository.save(game);
if (!game) if (!game)
return HttpStatus.INTERNAL_SERVER_ERROR return HttpStatus.INTERNAL_SERVER_ERROR
console.log("200 retourné pour la création de partie") console.log("200 retourné pour la création de partie")
return HttpStatus.OK return HttpStatus.OK
} }
async updateGame(updateGameDto : UpdateGameDto) {
const game = await this.gameRepository.preload(
{gameServerIdOfTheMatch : updateGameDto.gameServerIdOfTheMatch,
...updateGameDto}
)
if (!game)
throw new HttpException(`The game could not be updated.`,HttpStatus.NOT_FOUND);
game.isMatchIsFinished = true;
this.userRepository.save(game);
const playerOne = await this.userRepository.findOneBy({username : game.playerOneUsername})
const playerTwo = await this.userRepository.findOneBy({username : game.playerTwoUsername})
if (!playerOne || !playerTwo)
return new HttpException("Internal Server Error. Impossible to update the database", HttpStatus.INTERNAL_SERVER_ERROR);
if (game.playerOneUsernameResult === game.playerTwoUsernameResult)
{
this.userService.incrementDraws(playerOne.id)
this.userService.incrementDraws(playerTwo.id)
}
else if (game.playerOneUsernameResult < game.playerTwoUsernameResult)
{
this.userService.incrementDefeats(playerOne.id)
this.userService.incrementVictories(playerTwo.id)
}
else
{
this.userService.incrementVictories(playerOne.id)
this.userService.incrementDefeats(playerTwo.id)
}
return HttpStatus.OK
}
} }

View File

@@ -2,7 +2,7 @@
// et de les mettre comme optionnelles. De plus on peut hériter // et de les mettre comme optionnelles. De plus on peut hériter
// des décorateurs de la classe parente (par exemple @IsString()). // des décorateurs de la classe parente (par exemple @IsString()).
import { OmitType, PartialType } from "@nestjs/mapped-types"; import { OmitType } from "@nestjs/mapped-types";
import { CreateUsersDto } from "./create-users.dto"; import { CreateUsersDto } from "./create-users.dto";
export class UpdateUsersDto extends OmitType(CreateUsersDto, ['fortyTwoId', 'email', 'image_url', 'status'] as const){} export class UpdateUsersDto extends OmitType(CreateUsersDto, ['fortyTwoId', 'email', 'image_url', 'status'] as const){}

View File

@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount, onDestroy } from "svelte";
import * as enumeration from './shared_js/enums' import * as enumeration from './shared_js/enums'
import * as constants from './client/constants' import * as constants from './client/constants'
import { initPong, initGc, initMatchOptions, initStartFunction } from './client/global' import { initPong, initGc, initMatchOptions, initStartFunction } from './client/global'
@@ -14,7 +14,9 @@
import { initAudio } from './client/audio'; import { initAudio } from './client/audio';
import { pong, gc} from './client/global' import { pong, gc} from './client/global'
import Header from '../../pieces/Header.svelte'; import Header from '../../pieces/Header.svelte';
import { push } from "svelte-spa-router"; import { fade, fly } from 'svelte/transition'
//user's stuff //user's stuff
let user; let user;
@@ -36,10 +38,10 @@
let showInvitations = false; let showInvitations = false;
let showGameOption = true; let showGameOption = true;
let showError = false; let showError = false;
let showCanvas = false;
let isThereAnyInvitation = false; let isThereAnyInvitation = false;
let invitations; let invitations = [];
let waitingMessage = "Please wait..." let waitingMessage = "Please wait..."
let errorMessageWhenAttemptingToGetATicket = ""; let errorMessageWhenAttemptingToGetATicket = "";
@@ -51,10 +53,13 @@
.then( x => x.json() ); .then( x => x.json() );
}) })
const init = async() => { onDestroy( async() => {
})
const initGame = async() => {
optionsAreNotSet = false optionsAreNotSet = false
showWaitPage = true showWaitPage = true
console.log("Player two username " + playerTwoUsername)
if (multi_balls === true) if (multi_balls === true)
matchOption |= enumeration.MatchOptions.multiBalls matchOption |= enumeration.MatchOptions.multiBalls
if (moving_walls === true ) if (moving_walls === true )
@@ -71,11 +76,10 @@
}) })
}) })
const responseFromServer = await responseWhenGrantToken; const responseFromServer = await responseWhenGrantToken;
console.log("Response.ok : " + responseFromServer.ok ) const responseInjson = await responseFromServer.json();
console.log("//") const token : string = responseInjson.token;
const responseInjson = await responseFromServer.json()
showWaitPage = false showWaitPage = false
if (!responseFromServer.ok || !responseInjson.token) if (!responseFromServer.ok)
{ {
errorMessageWhenAttemptingToGetATicket = responseInjson.message; errorMessageWhenAttemptingToGetATicket = responseInjson.message;
showError = true; showError = true;
@@ -87,25 +91,37 @@
matchOption = 0; matchOption = 0;
}, 5000) }, 5000)
} }
else else if (token)
{ {
const token = responseInjson.token (sound === "off") ? initAudio(true) : initAudio(false);
console.log("Token === " + token)
if (sound === "off") {
initAudio(true);
}
else if (sound === "on") {
initAudio(false);
}
initMatchOptions(matchOption) initMatchOptions(matchOption)
initPong(new GameArea()) initPong(new GameArea())
initGc(new GameComponentsClient(matchOption, pong.ctx)) initGc(new GameComponentsClient(matchOption, pong.ctx))
initStartFunction(start) initStartFunction(start)
console.log("Avant init websocket") isSomeoneIsIvited ?
initWebSocket(matchOption, token, user.username, true, playerTwoUsername) :
initWebSocket(matchOption, token, user.username) initWebSocket(matchOption, token, user.username)
} }
} }
const initGameForPrivateParty = async(invitation : any) => {
optionsAreNotSet = false
showWaitPage = true
console.log("invitation : ")
console.log(invitation)
if (invitation.token)
{
initMatchOptions(matchOption)
initPong(new GameArea())
initGc(new GameComponentsClient(matchOption, pong.ctx))
initStartFunction(start)
showWaitPage = false
initWebSocket(matchOption, invitation.token, invitation.playerOneUsername, true, user.username)
}
}
function start() : void { function start() : void {
gc.text1.pos.assign(constants.w*0.5, constants.h*0.75); gc.text1.pos.assign(constants.w*0.5, constants.h*0.75);
countdown(constants.matchStartDelay/1000, (count: number) => { countdown(constants.matchStartDelay/1000, (count: number) => {
@@ -138,28 +154,38 @@
showInvitations = true; showInvitations = true;
invitations = await fetch("http://transcendance:8080/api/v2/game/invitations") invitations = await fetch("http://transcendance:8080/api/v2/game/invitations")
.then(x => x.json()) .then(x => x.json())
console.log(...invitations) invitations.length !== 0 ? isThereAnyInvitation = true : isThereAnyInvitation = false
} }
const rejectInvitation = async() => { const rejectInvitation = async(invitation) => {
await fetch("http://transcendance:8080/api/v2/game/decline",{ await fetch("http://transcendance:8080/api/v2/game/decline",{
method: "POST", method: "POST",
headers: { 'Content-Type': 'application/json'}, headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ body: JSON.stringify({
token : invitation.token
})
}) })
}) .then(x => x.json())
} .catch(error => console.log(error))
showInvitation()
}
const acceptInvitation = async() => { const acceptInvitation = async(invitation : any) => {
await fetch("http://transcendance:8080/api/v2/game/accept",{ await fetch("http://transcendance:8080/api/v2/game/accept",{
method: "POST", method: "POST",
headers: { 'Content-Type': 'application/json'}, headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ body: JSON.stringify({
token : invitation.token
})
})
.then(x => x.json())
.catch(error => {
console.log(error)
}) })
}) showInvitation()
} initGameForPrivateParty(invitation)
}
</script> </script>
@@ -169,90 +195,100 @@
<div id="preload_font">.</div> <div id="preload_font">.</div>
{#if showError === true} {#if showError === true}
<div id="div_game"> <div id="div_game" in:fly="{{ y: 10, duration: 1000 }}">
<fieldset> <fieldset>
<legend>Error</legend> <legend>Error</legend>
<p>{errorMessageWhenAttemptingToGetATicket}</p> <p>{errorMessageWhenAttemptingToGetATicket}</p>
<button id="pong_button">Retry</button> <button id="pong_button">Retry</button>
</fieldset> </fieldset>
</div> </div>
{/if} {/if}
{#if optionsAreNotSet} {#if showWaitPage === true}
{#if showGameOption === true} <div id="div_game" in:fly="{{ y: 10, duration: 1000 }}">
<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>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label>sound :</label>
<input type="radio" id="sound_on" name="sound_selector" bind:group={sound} value="on">
<label for="sound_on">on</label>
<input type="radio" id="sound_off" name="sound_selector" bind:group={sound} value="off">
<label for="sound_off">off</label>
</div>
<div>
<input type="checkbox" id="isSomeoneIsIvited" name="moving_walls" bind:checked={isSomeoneIsIvited}>
<label for="moving_walls">Invite a friend</label>
</div>
{#if isSomeoneIsIvited === 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">
{#if showWaitPage === true}
<div id="div_game">
<fieldset> <fieldset>
<legend>Connecting to the game...</legend> <legend>Connecting to the game...</legend>
<p>{waitingMessage}</p> <p>{waitingMessage}</p>
</fieldset> </fieldset>
</div> </div>
{/if} {/if}
<canvas id="gameArea"></canvas>
</div>
{#if optionsAreNotSet}
{#if showGameOption === true}
<div id="game_option">
<form on:submit|preventDefault={() => initGame()}>
<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>
<p>sound :</p>
<input type="radio" id="sound_on" name="sound_selector" bind:group={sound} value="on">
<label for="sound_on">on</label>
<input type="radio" id="sound_off" name="sound_selector" bind:group={sound} value="off">
<label for="sound_off">off</label>
</div>
<div>
<input type="checkbox" id="isSomeoneIsIvited" bind:checked={isSomeoneIsIvited}>
<label for="moving_walls">Invite a friend</label>
</div>
{#if isSomeoneIsIvited === 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>
</div>
{/if}
{#if showInvitations}
<div id="invitations_options" in:fly="{{ y: 10, duration: 1000 }}">
<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(invitation)}>V</button>
<button id="pong_button" on:click={() => rejectInvitation(invitation)}>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>
</div>
{/if}
{/if}
<div id="canvas_container">
<!-- <p> =) </p> -->
</div>
</body> </body>
@@ -284,6 +320,14 @@ body {
/* max-height: 80vh; */ /* max-height: 80vh; */
/* overflow: hidden; */ /* overflow: hidden; */
} }
#users_name {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: x-large;
}
#div_game { #div_game {
text-align: center; text-align: center;
font-family: "Bit5x3"; font-family: "Bit5x3";

View File

@@ -9,10 +9,13 @@ export class GameArea {
canvas: HTMLCanvasElement; canvas: HTMLCanvasElement;
ctx: CanvasRenderingContext2D; ctx: CanvasRenderingContext2D;
constructor() { constructor() {
this.canvas = document.getElementById("gameArea"); this.canvas = document.createElement("canvas");
this.ctx = this.canvas.getContext("2d") as CanvasRenderingContext2D; this.ctx = this.canvas.getContext("2d") as CanvasRenderingContext2D;
this.canvas.width = c.CanvasWidth; this.canvas.width = c.CanvasWidth;
this.canvas.height = c.CanvasWidth / c.CanvasRatio; this.canvas.height = c.CanvasWidth / c.CanvasRatio;
let container = document.getElementById("canvas_container");
if (container)
container.insertBefore(this.canvas, container.childNodes[0]);
} }
addKey(key: string) { addKey(key: string) {
key = key.toLowerCase(); key = key.toLowerCase();

View File

@@ -34,6 +34,8 @@ export const clientInfoSpectator = new ClientInfoSpectator(); // WIP, could refa
export function initWebSocket(options: en.MatchOptions, token: string, username: string, privateMatch = false, playerTwoUsername?: string) export function initWebSocket(options: en.MatchOptions, token: string, username: string, privateMatch = false, playerTwoUsername?: string)
{ {
socket = new WebSocket(wsUrl, "json"); socket = new WebSocket(wsUrl, "json");
console.log("Infos from ws.ts : options => " + options + " token => " + token + " username => " + username + " priavte match => " + privateMatch
+ " player two => " + playerTwoUsername)
socket.addEventListener("open", (event) => { socket.addEventListener("open", (event) => {
if (privateMatch) { if (privateMatch) {
socket.send(JSON.stringify( new ev.ClientAnnouncePlayer(options, token, username, privateMatch, playerTwoUsername) )); socket.send(JSON.stringify( new ev.ClientAnnouncePlayer(options, token, username, privateMatch, playerTwoUsername) ));