Skip to content

Commit

Permalink
game logic and events fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
GuiMartinelli committed Jun 27, 2023
1 parent 5925a99 commit 52289ed
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
29 changes: 14 additions & 15 deletions backend/src/game/game.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
}

handleDisconnect(client: any) {
this.finishGame(client);
const gameId = this.finishGame(client);
client.leave(gameId);
this.gameServer.to(gameId).emit('gameAbandoned', this.gamesPlaying[gameId]);
console.log(`Client ${client.id} disconnected`);
}

Expand All @@ -47,26 +49,23 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
@SubscribeMessage('startGame')
startGame(client: any, gameId: string) {
const game = this.gamesPlaying[gameId];

console.log("started game", game)

this.gameService.updateBallPosition(game);
if (this.gameService.isPointScored(game)) {
this.gameService.addPoint(game);
this.gameService.restartBall(game);
}
if (this.gameService.isGameFinished(game)) {
this.gameServer
.to(gameId)
.emit('gameFinished', game);
this.gameServer.to(gameId).emit('gameFinished', game);
this.finishGame(client);
}
if (!game.finished) {
this.gameServer
.to(gameId)
.emit('updatedGame', game);
if (game.finished) {
return;
}

setTimeout( () => {
this.gameServer.to(gameId).emit('updatedGame', game);
console.log('started game', game);
setTimeout(() => {
this.startGame(client, gameId);
}, 1000 / 60);

Expand All @@ -78,7 +77,7 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
this.gameService.updatePlayerPosition(this.gamesPlaying[info.gameId], info);
}

private finishGame(client: any) {
private finishGame(client: any): string {
const gameId = Object.keys(this.gamesPlaying).find((gameId) => {
return (
this.gamesPlaying[gameId].player1.id === client.id ||
Expand All @@ -87,9 +86,9 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
});
if (gameId) {
this.gamesPlaying[gameId].finished = true;
this.gameServer
.to(gameId)
.emit('gameAbandoned', this.gamesPlaying[gameId]);
this.gamesPlaying.delete(gameId);
return gameId;
}
return null;
}
}
4 changes: 2 additions & 2 deletions backend/src/game/game.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ export class GameService {
}

isPointScored(gameDto: GameDto): boolean {
if (gameDto.ball.y + gameDto.ball.radius > gameDto.canvas.height) {
if (gameDto.ball.x + gameDto.ball.radius > gameDto.canvas.height) {
return true;
} else if (gameDto.ball.y - gameDto.ball.radius < 0) {
} else if (gameDto.ball.x - gameDto.ball.radius < 0) {
return true;
}
return false;
Expand Down

0 comments on commit 52289ed

Please sign in to comment.