Skip to content

Commit

Permalink
Handle user leaving in the middle of game (#298)
Browse files Browse the repository at this point in the history
* Remove unnecessary code

* Handle user leaving in the middle of game

* Hide start button when viewer

* Change direction name
  • Loading branch information
takumihara authored Mar 5, 2024
1 parent 34252ec commit 9d94503
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 39 deletions.
18 changes: 10 additions & 8 deletions backend/src/events/events.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ export class EventsGateway implements OnGatewayDisconnect {
this.emitUpdateStatusToRoomId(client, roomId, 'friend-left', {
playerNumber: this.players[roomId][client.id],
});
const opponent = getOpponent(this.players, roomId, client.id);
if (opponent) {
this.lostPoints[opponent] = 0;
}
removePlayer(this.players, roomId, client.id);
delete this.lostPoints[client.id];
}
Expand All @@ -185,32 +189,30 @@ export class EventsGateway implements OnGatewayDisconnect {
}

@UseGuards(UserGuardWs)
@SubscribeMessage('left')
async left(
@SubscribeMessage('up')
async up(
@MessageBody() data: string,
@ConnectedSocket() client: Socket,
): Promise<void> {
const roomId = client.handshake.query['game_id'] as string;
if (!isPlayer(this.players, roomId, client.id)) return;

this.logger.log(`left: ${client.id}`);

this.broadcastToRooms(client, 'left', {
this.broadcastToRooms(client, 'up', {
playerNumber: this.players[roomId][client.id],
});
return;
}

@UseGuards(UserGuardWs)
@SubscribeMessage('right')
async right(
@SubscribeMessage('down')
async down(
@MessageBody() data: string,
@ConnectedSocket() client: Socket,
): Promise<void> {
const roomId = client.handshake.query['game_id'] as string;
if (!isPlayer(this.players, roomId, client.id)) return;

this.broadcastToRooms(client, 'right', {
this.broadcastToRooms(client, 'down', {
playerNumber: this.players[roomId][client.id],
});
return;
Expand Down
4 changes: 2 additions & 2 deletions frontend/app/lib/hooks/game/useGameKeyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ export default function useGameKeyboard(getGame: () => PongGame) {
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key == "ArrowDown") {
game.setMovingDirection("right");
game.setMovingDirection("down");
} else if (event.key == "ArrowUp") {
game.setMovingDirection("left");
game.setMovingDirection("up");
}
};

Expand Down
37 changes: 21 additions & 16 deletions frontend/app/lib/hooks/game/useGameSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,23 @@ export default function useGameSocket(
setUserMode("viewer");
break;
case "friend-joined":
const { playerNumber, user } = payload;
const setter = getPlayerSetterFromPlayerNumber(playerNumber);
setter(user);
currentUser && setStartDisabled(false);
game.resetPlayerPosition();
{
const { playerNumber, user } = payload;
const setter = getPlayerSetterFromPlayerNumber(playerNumber);
setter(user);
currentUser && setStartDisabled(false);
game.resetPlayerPosition();
game.reset();
}
break;
case "friend-left":
{
const { playerNumber } = payload;
const setter = getPlayerSetterFromPlayerNumber(playerNumber);
setter(undefined);
setStartDisabled(true);
const game = getGame();
game.reset();
}
break;
case "joined-as-viewer":
Expand Down Expand Up @@ -169,19 +174,19 @@ export default function useGameSocket(
setStartDisabled(true);
};

const handleRight = ({ playerNumber }: HandleActionProps) => {
const handleDown = ({ playerNumber }: HandleActionProps) => {
if (userMode !== "player" && playerNumber == 1) {
game.movePlayer1Left();
game.movePlayer1Down();
} else {
game.movePlayer2Left();
game.movePlayer2Up();
}
};

const handleLeft = ({ playerNumber }: HandleActionProps) => {
const handleUp = ({ playerNumber }: HandleActionProps) => {
if (userMode !== "player" && playerNumber == 1) {
game.movePlayer1Right();
game.movePlayer1Up();
} else {
game.movePlayer2Right();
game.movePlayer2Down();
}
};

Expand Down Expand Up @@ -212,13 +217,13 @@ export default function useGameSocket(

const handleFinish = () => {
const game = getGame();
game.stop();
game.reset();
};

socket.on("connect", handleConnect);
socket.on("start", handleStart);
socket.on("right", handleRight);
socket.on("left", handleLeft);
socket.on("down", handleDown);
socket.on("up", handleUp);
socket.on("bounce", handleBounce);
socket.on("collide", handleCollide);
socket.on("update-status", handleUpdateStatus);
Expand All @@ -227,8 +232,8 @@ export default function useGameSocket(
return () => {
socket.off("connect", handleConnect);
socket.off("start", handleStart);
socket.off("right", handleRight);
socket.off("left", handleLeft);
socket.off("down", handleDown);
socket.off("up", handleUp);
socket.off("bounce", handleBounce);
socket.off("collide", handleCollide);
socket.off("update-status", handleUpdateStatus);
Expand Down
8 changes: 5 additions & 3 deletions frontend/app/pong/[id]/PongBoard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ export default function PongBoard({ id }: PongBoardProps) {
></canvas>
<div className="flex flex-col gap-4">
<div className="flex flex-wrap gap-2">
<Button onClick={start} disabled={startDisabled}>
Start
</Button>
{userMode === "player" && (
<Button onClick={start} disabled={startDisabled}>
Start
</Button>
)}
</div>
<PongInformationBoard
logs={logs}
Expand Down
27 changes: 17 additions & 10 deletions frontend/app/pong/[id]/PongGame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import {
TARGET_FRAME_MS,
} from "./const";

type setFunction<T> = (value: T | ((prevState: T) => T)) => void;
type movingDirectionType = "none" | "left" | "right";
type movingDirectionType = "none" | "up" | "down";
type onActionType = (action: string) => void;
type userModeType = "player" | "viewer";

Expand Down Expand Up @@ -121,16 +120,16 @@ export class PongGame {
this.elapsed = this.updatedAt === undefined ? 0 : now - this.updatedAt;
this.updatedAt = now;
if (this.userMode === "player") {
if (this.movingDirection === "left") {
if (this.movingDirection === "up") {
this.player1.clear(this.ctx);
this.player1.moveTop();
this.player1.draw(this.ctx);
this.onAction && this.onAction("left");
} else if (this.movingDirection === "right") {
this.onAction && this.onAction("up");
} else if (this.movingDirection === "down") {
this.player1.clear(this.ctx);
this.player1.moveDown();
this.player1.draw(this.ctx);
this.onAction && this.onAction("right");
this.onAction && this.onAction("down");
}
}
if (this.isPlaying) {
Expand Down Expand Up @@ -167,6 +166,14 @@ export class PongGame {
this.isPlaying = false;
};

reset = () => {
this.stop();
this.score = {
player1: 0,
player2: 0,
};
};

resetPlayerPosition = () => {
const color = this.player1.color;
this.player1 = this.initPlayer1(color);
Expand Down Expand Up @@ -200,25 +207,25 @@ export class PongGame {
return this.ball.bounceOffPaddle(this.player2);
};

movePlayer1Left = () => {
movePlayer1Up = () => {
this.player1.clear(this.ctx);
this.player1.moveTop();
this.player1.draw(this.ctx);
};

movePlayer1Right = () => {
movePlayer1Down = () => {
this.player1.clear(this.ctx);
this.player1.moveDown();
this.player1.draw(this.ctx);
};

movePlayer2Left = () => {
movePlayer2Up = () => {
this.player2.clear(this.ctx);
this.player2.moveTop();
this.player2.draw(this.ctx);
};

movePlayer2Right = () => {
movePlayer2Down = () => {
this.player2.clear(this.ctx);
this.player2.moveDown();
this.player2.draw(this.ctx);
Expand Down

0 comments on commit 9d94503

Please sign in to comment.