Skip to content

Commit

Permalink
fix notification throw in front ,finish game invitation from profile (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sedeve authored Nov 14, 2023
2 parents 3bf1381 + 0cd0b2d commit b2fe64a
Show file tree
Hide file tree
Showing 13 changed files with 625 additions and 182 deletions.
2 changes: 2 additions & 0 deletions backend/code/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { GameModule } from './game/game.module';
import { LeaderBoardModule } from './leaderboard/leaderboard.module';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { APP_GUARD } from '@nestjs/core';
import { GatewaysModule } from './gateways/gateways.module';

@Module({
imports: [
Expand All @@ -34,6 +35,7 @@ import { APP_GUARD } from '@nestjs/core';
limit: 1000000,
},
]),
GatewaysModule,
],
controllers: [AppController],
providers: [
Expand Down
10 changes: 10 additions & 0 deletions backend/code/src/game/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export class Game {
const newPos = this.p1PaddleY * scale2;
// let scale_y = player2.h / this.h;
// let center = this.paddleHeight * scale_y;

if (p2PaddleY - player2.h / 6 / 6 < 0) {
p2PaddleY = 0;
} else if (p2PaddleY + player2.h / 6 > player2.h) {
Expand Down Expand Up @@ -71,6 +72,7 @@ export class Game {
// let scale_y = player1.h / this.h;

// let center = this.paddleHeight * scale_y;

if (p1PaddleY - player1.h / 6 / 6 < 0) {
p1PaddleY = 0;
} else if (p1PaddleY + player1.h / 6 > player1.h) {
Expand Down Expand Up @@ -108,6 +110,7 @@ export class Game {
private async loop() {
if (this.closeGame) return;
console.log('loop');

if (
this.x + this.dx + this.ballSize / 2 >= this.w ||
this.x + this.dx - this.ballSize / 2 <= 0
Expand Down Expand Up @@ -161,6 +164,7 @@ export class Game {

console.log(this.x);
console.log(this.y);

// const forwardx = this.x + this.dx;
// const forwardy = this.y + this.dy
// if (forwardx > this.) {
Expand All @@ -173,6 +177,7 @@ export class Game {
parseFloat((this.p2Res.w / this.p2Res.h).toFixed(1)) !== 1.9
) {
this.p1socket.emit('screen Error');

this.emitGameEnd('p1Leave');
this.p1socket.emit('lose', 'trying cheat');
this.p2socket.emit('win', 'you win other player try to cheat');
Expand All @@ -198,6 +203,7 @@ export class Game {
parseFloat((this.p2Res.w / this.p2Res.h).toFixed(1)) !== 1.9
) {
this.p1socket.emit('screen Error');

this.emitGameEnd('p2Leave');
this.p1socket.emit('win', 'you win other player try to cheat');
this.p2socket.emit('lose', 'trying cheat');
Expand Down Expand Up @@ -228,6 +234,7 @@ export class Game {

for (let i = 0; i < 6; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000));

this.server.to(this.gameid).emit('timer', timer);
timer -= 1000;
}
Expand All @@ -254,6 +261,7 @@ export class Game {
console.log(p2Data);
this.server.emit('players', [p1Data, p2Data]);
console.log('newfunc');

setInterval(() => {
this.frames -= 1;
}, 2000);
Expand Down Expand Up @@ -358,6 +366,7 @@ export class Game {
this.x = this.w / 2;
this.y = this.h / 2;
this.ballSize = this.w / 42;

this.dx = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
this.dy = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
this.p1PaddleY = this.h / 2;
Expand All @@ -376,6 +385,7 @@ export class Game {
private y: number = this.h / 2;
private gap: number = this.w / 100;
private ballSize: number = this.w / 42;

private dx: number = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
private dy: number = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
private p1PaddleY: number = this.h / 2;
Expand Down
154 changes: 132 additions & 22 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { PrismaService } from 'src/prisma/prisma.service';
import { Game } from 'src/game/game';
import { $Enums, Notification } from '@prisma/client';
import * as crypto from 'crypto';
import { UsersService } from 'src/users/users.service';

interface GameInvite {
inviter: string;
opponentId: string;
gameMode: string;
client: Socket;
gameId: string;
}

@WebSocketGateway(3004, {
cors: {
Expand All @@ -24,33 +34,15 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
constructor(
private prisma: PrismaService,
private readonly eventEmitter: EventEmitter2,
private readonly usersService: UsersService,
) {}

@WebSocketServer() private server: Server;
private games_map = new Map<string, Game>();
private game_invites = new Set<GameInvite>();
async handleConnection(client: Socket) {
const userId = client.data.user.sub;
// const rooms = this.prisma.roomMember.findMany({
// where: {
// userId: userId,
// },
// select: {
// room: {
// select: {
// id: true,
// name: true,
// },
// },
// },
// });
// rooms.then((rooms) => {
// rooms.forEach((room) => {
// client.join(`Room:${room.room.id}`);
// console.log(`Room:${room.room.id}`);
// });
// });
client.join(`User:${userId}`);

const frienduserIds = await this.prisma.friend.findMany({
where: {
OR: [
Expand Down Expand Up @@ -162,7 +154,6 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
is_banned: true,
},
});

roomMembers = roomMembers.filter(
(member) =>
member.userId !== message.authorId &&
Expand Down Expand Up @@ -209,12 +200,126 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
// getPlayers() {
// this.server.emit("players",[this.p1Data ,this.p2Data])
// }
private async checkIfCanInvite(userId: string) {
const opententSockets = await this.server
.in(`User:${userId}`)
.fetchSockets();
if (opententSockets.length === 0) {
return { error: 'offline' };
}
for await (const socket of opententSockets) {
if (socket.data.user?.inGame) {
return { error: 'already in game' };
}
}
const invite = Array.from(this.game_invites).find(
(invite) => invite.opponentId === userId || invite.inviter === userId,
);
if (invite) {
return { error: 'already Invited or Inviting to a game' };
}
return { error: null };
}

@SubscribeMessage('inviteToGame')
async handleInviteToGameEvent(client: Socket, data: any) {
const [inviter, opponent] = await Promise.all([
this.checkIfCanInvite(client.data.user.sub),
this.checkIfCanInvite(data.opponentId),
]);

if (inviter.error || opponent.error) {
return {
error: inviter.error ? `You are ${inviter.error}` : opponent.error,
};
}

const gameId = crypto.randomBytes(16).toString('hex');
this.server.to(`User:${data.opponentId}`).emit('invitedToGame', {
inviterId: client.data.user.sub,
gameId,
});
this.game_invites.add({
inviter: client.data.user.sub,
gameMode: data.gameMode,
client,
gameId,
opponentId: data.opponentId,
});
return { error: null, gameId };
}

@SubscribeMessage('acceptGame')
async handleAcceptGameEvent(client: Socket, data: any) {
const game_invite = Array.from(this.game_invites).find(
(invite) => invite.gameId === data.gameId,
);
//TODO: check if user is already in queue
// check if already has an active invite from anyone
// check if he is already on game || save if user is in game by saving it in the data of socket
// check if user is offline
if (!game_invite) {
client.emit('game.declined', {
gameId: data.gameId,
});
return;
}
this.game_invites.delete(game_invite);
this.server.to(`User:${data.inviterId}`).emit('game.accepted', {
accepter: client.data.user.sub,
});

const invterData = await this.usersService.getUserById(data.inviterId);
const opponentData = await this.usersService.getUserById(
client.data.user.sub,
);

// launch the game
this.eventEmitter.emit('game.launched', [
{
socket: game_invite.client,
userData: invterData,
},
{
socket: client,
userData: opponentData,
},
]);
}

@SubscribeMessage('declineGame')
async handleDeclineGameEvent(client: Socket, data: any) {
const game_invite = Array.from(this.game_invites).find(
(invite) => invite.gameId === data.gameId,
);
if (!game_invite) {
return;
}

this.game_invites.delete(game_invite);

if (game_invite.inviter === client.data.user.sub) {
console.log('declined by inviter');
this.server.to(`User:${game_invite.opponentId}`).emit('game.declined', {
decliner: client.data.user.sub,
gameId: data.gameId,
});
} else {
console.log('decliner is the opponent');
this.server.to(`User:${game_invite.inviter}`).emit('game.declined', {
decliner: client.data.user.sub,
gameId: data.gameId,
});
}
}

@OnEvent('game.launched')
async handleGameLaunchedEvent(clients: any) {
const game_channel = `Game:${clients[0].socket.id}:${clients[1].socket.id}`;
const game_channel = crypto.randomBytes(16).toString('hex');
console.log(game_channel);
clients.forEach((client: any) => {
client.socket.join(game_channel);
client.socket.data.user.inGame = true;
});
const new_game = new Game(this.eventEmitter, this.server);

Expand All @@ -235,6 +340,11 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
console.log(data);
this.server.to(data.gameid).emit('game.end', data);
console.log(data);
const sockets = await this.server.in(data.gameid).fetchSockets();

for await (const socket of sockets) {
socket.data.user.inGame = false;
}
if (data.resign === 0) {
await this.prisma.match.create({
data: {
Expand Down
7 changes: 7 additions & 0 deletions backend/code/src/gateways/gateways.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { UsersModule } from 'src/users/users.module';

@Module({
imports: [UsersModule],
})
export class GatewaysModule {}
8 changes: 4 additions & 4 deletions backend/code/src/profile/profile.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ export class ProfileService {
wonMatches === 0
? null
: wonMatches >= 100
? 2
: Math.floor(Math.log10(wonMatches));
? 2
: Math.floor(Math.log10(wonMatches));

return new ProfileDto({ ...user, achievement }, false);
}
Expand Down Expand Up @@ -58,8 +58,8 @@ export class ProfileService {
wonMatches === 0
? null
: wonMatches >= 100
? 2
: Math.floor(Math.log10(wonMatches));
? 2
: Math.floor(Math.log10(wonMatches));
return new ProfileDto({ ...user, achievement }, true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ export const getBlockedCall = async (
}

}


2 changes: 1 addition & 1 deletion frontend/code/src/Components/Game/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,4 +170,4 @@ export const Game = () => {
</div>

)
}
}
Loading

0 comments on commit b2fe64a

Please sign in to comment.