Skip to content

Commit 907ba8d

Browse files
committed
api: Add disconnect
1 parent 091c453 commit 907ba8d

File tree

11 files changed

+240
-214
lines changed

11 files changed

+240
-214
lines changed

apps/duckguessr/api/services/game.ts

Lines changed: 97 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ const onGuess = async (
6868
user: player,
6969
personcode: string | null,
7070
): Promise<boolean> => {
71-
const { _socket, ...events } = gameServices;
71+
const { _socket } = gameServices;
7272
const currentRound = _socket.data.currentRound;
7373
console.log(
7474
`${user.username} is guessing ${JSON.stringify(personcode)} on round ${
@@ -82,7 +82,7 @@ const onGuess = async (
8282
personcode,
8383
}));
8484
if (guessResultsData) {
85-
events.playerGuessed(guessResultsData);
85+
gameServices.playerGuessed(guessResultsData);
8686
_socket.broadcast.emit("playerGuessed", {
8787
...guessResultsData,
8888
answer: null,
@@ -120,7 +120,7 @@ const getPlayersMissingRoundScore = async (currentRound: round) =>
120120
`;
121121

122122
const startRound = (socket: GameServices) => {
123-
const { _socket, ...events } = socket;
123+
const { _socket } = socket;
124124
const currentRound = socket._socket.data.currentRound;
125125
_socket.data.currentRoundEndTimeout = setTimeout(
126126
() => finishRound(socket),
@@ -133,7 +133,7 @@ const startRound = (socket: GameServices) => {
133133
"firstRoundWillStartSoon",
134134
currentRound.startedAt!,
135135
);
136-
events.firstRoundWillStartSoon(currentRound.startedAt!);
136+
socket.firstRoundWillStartSoon(currentRound.startedAt!);
137137
}, 200);
138138
}
139139

@@ -143,7 +143,7 @@ const startRound = (socket: GameServices) => {
143143
};
144144
setTimeout(async () => {
145145
_socket.broadcast.emit("roundStarts", roundWithoutPersoncode);
146-
events.roundStarts(roundWithoutPersoncode);
146+
socket.roundStarts(roundWithoutPersoncode);
147147

148148
const botPlayer = (
149149
await prisma.gamePlayer.findFirst({
@@ -177,7 +177,7 @@ const startRound = (socket: GameServices) => {
177177
};
178178

179179
const finishRound = async (gameServices: GameServices) => {
180-
const { _socket, ...events } = gameServices;
180+
const { _socket } = gameServices;
181181
let { currentRound } = _socket.data;
182182
const currentGame = _socket.data.currentGame;
183183
console.log(`Round ${currentRound.id} finished`);
@@ -198,9 +198,9 @@ const finishRound = async (gameServices: GameServices) => {
198198
};
199199
if (currentRound.roundNumber === numberOfRounds) {
200200
_socket.broadcast.emit("roundEnds", roundWithScores);
201-
events.roundEnds(roundWithScores);
201+
gameServices.roundEnds(roundWithScores);
202202
_socket.broadcast.emit("gameEnds");
203-
events.gameEnds();
203+
gameServices.gameEnds();
204204
} else {
205205
currentRound = await setRoundTimes(
206206
currentGame!.rounds.find(
@@ -216,7 +216,7 @@ const finishRound = async (gameServices: GameServices) => {
216216
roundWithScores,
217217
roundWithoutPersoncode,
218218
);
219-
events.roundEnds(roundWithScores, roundWithoutPersoncode);
219+
gameServices.roundEnds(roundWithScores, roundWithoutPersoncode);
220220
startRound(gameServices);
221221
}
222222
};
@@ -256,48 +256,49 @@ const removePlayer = async (
256256
}
257257
};
258258

259-
const listenEvents = ({ _socket, ...events }: GameServices) => ({
260-
removeBot: async () => {
261-
validateGameForBotAddOrRemove(
262-
_socket.data.user.id,
263-
_socket.data.currentGame,
264-
);
265-
await removePlayer(
266-
await getUser(`bot_${_socket.data.currentGame.dataset.name}`),
267-
_socket,
268-
events.playerLeft,
269-
);
270-
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
271-
_socket.data.gameId,
272-
))!;
273-
},
274-
addBot: async () => {
275-
validateGameForBotAddOrRemove(
276-
_socket.data.user.id,
277-
_socket.data.currentGame,
278-
);
259+
const listenEvents = (gameServices: GameServices) => {
260+
const { _socket } = gameServices;
261+
return {
262+
removeBot: async () => {
263+
validateGameForBotAddOrRemove(
264+
_socket.data.user.id,
265+
_socket.data.currentGame,
266+
);
267+
await removePlayer(
268+
await getUser(`bot_${_socket.data.currentGame.dataset.name}`),
269+
_socket,
270+
gameServices.playerLeft,
271+
);
272+
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
273+
_socket.data.currentGame.id,
274+
))!;
275+
},
276+
addBot: async () => {
277+
validateGameForBotAddOrRemove(
278+
_socket.data.user.id,
279+
_socket.data.currentGame,
280+
);
279281

280-
const botUsername = `bot_${_socket.data.currentGame.dataset.name}`;
281-
const botPlayer = await getUser(botUsername);
282-
await checkAndAssociatePlayer(_socket.data.currentGame, botPlayer);
283-
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
284-
_socket.data.gameId,
285-
))!;
286-
287-
_socket.broadcast.emit("playerJoined", botPlayer);
288-
_socket.emit("playerJoined", botPlayer);
289-
},
290-
joinMatch: async () => {
291-
{
282+
const botUsername = `bot_${_socket.data.currentGame.dataset.name}`;
283+
const botPlayer = await getUser(botUsername);
284+
await checkAndAssociatePlayer(_socket.data.currentGame, botPlayer);
285+
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
286+
_socket.data.currentGame.id,
287+
))!;
288+
289+
_socket.broadcast.emit("playerJoined", botPlayer);
290+
_socket.emit("playerJoined", botPlayer);
291+
},
292+
joinMatch: async () => {
292293
const player = await checkAndAssociatePlayer(
293294
_socket.data.currentGame,
294295
_socket.data.user,
295296
);
296297
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
297-
_socket.data.gameId,
298+
_socket.data.currentGame.id,
298299
))!;
299300

300-
events.playerJoined(player);
301+
gameServices.playerJoined(player);
301302

302303
const players = _socket.data.currentGame.gamePlayers.map(
303304
({ player }) => player,
@@ -312,57 +313,64 @@ const listenEvents = ({ _socket, ...events }: GameServices) => ({
312313
players,
313314
playerStats: await getPlayerStatistics(players.map(({ id }) => id)),
314315
};
315-
}
316-
},
317-
startMatch: async () => {
318-
if (
319-
_socket.data.currentGame?.gamePlayers[0] &&
320-
_socket.data.user.id !== _socket.data.currentGame.gamePlayers[0].playerId
321-
) {
322-
console.error(
323-
"The player starting the match must be the one who created it!",
324-
);
325-
return false;
326-
}
316+
},
317+
startMatch: async () => {
318+
if (
319+
_socket.data.currentGame?.gamePlayers[0] &&
320+
_socket.data.user.id !==
321+
_socket.data.currentGame.gamePlayers[0].playerId
322+
) {
323+
console.error(
324+
"The player starting the match must be the one who created it!",
325+
);
326+
return false;
327+
}
327328

328-
console.log(`Game ${_socket.data.gameId} is starting!`);
329+
console.log(`Game ${_socket.data.currentGame.id} is starting!`);
329330

330-
_socket.data.currentRound = await setRoundTimes(_socket.data.currentRound);
331-
startRound({ _socket, ...events });
331+
_socket.data.currentRound = await setRoundTimes(
332+
_socket.data.currentRound,
333+
);
334+
startRound(gameServices);
332335

333-
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
334-
_socket.data.gameId,
335-
))!;
336+
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
337+
_socket.data.currentGame.id,
338+
))!;
336339

337-
_socket.broadcast.emit("matchStarts");
338-
events.matchStarts();
339-
},
340-
guess: async (personcode: string | null) => {
341-
const haveAllPlayersGuessed = await onGuess(
342-
{ _socket, ...events },
343-
_socket.data.user,
344-
personcode,
345-
);
346-
if (haveAllPlayersGuessed) {
347-
return haveAllPlayersGuessed;
348-
}
349-
},
350-
disconnect: async ({ _socket }: GameServices, reason: string) => {
351-
if (reason !== "client namespace disconnect") {
352-
if (
353-
_socket &&
354-
_socket.data.currentGame.gamePlayers.findIndex(
355-
({ player }) => player.id === _socket.data.user.id,
356-
) > 0
357-
) {
358-
await removePlayer(_socket.data.user, _socket, events.playerLeft);
359-
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
360-
_socket.data.gameId,
361-
))!;
340+
_socket.broadcast.emit("matchStarts");
341+
gameServices.matchStarts();
342+
},
343+
guess: async (personcode: string | null) => {
344+
const haveAllPlayersGuessed = await onGuess(
345+
gameServices,
346+
_socket.data.user,
347+
personcode,
348+
);
349+
if (haveAllPlayersGuessed) {
350+
return haveAllPlayersGuessed;
362351
}
363-
}
364-
},
365-
});
352+
},
353+
disconnect: async (reason: string) => {
354+
if (reason !== "client namespace disconnect") {
355+
if (
356+
_socket &&
357+
_socket.data.currentGame.gamePlayers.findIndex(
358+
({ player }) => player.id === _socket.data.user.id,
359+
) > 0
360+
) {
361+
await removePlayer(
362+
_socket.data.user,
363+
_socket,
364+
gameServices.playerLeft,
365+
);
366+
_socket.data.currentGame = (await getGameWithRoundsDatasetPlayers(
367+
_socket.data.currentGame.id,
368+
))!;
369+
}
370+
}
371+
},
372+
};
373+
};
366374

367375
const getPublicGame = async (
368376
game: Awaited<ReturnType<typeof getGameWithRoundsDatasetPlayers>>,

apps/duckguessr/api/types/socketEvents.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ export type CurrentGame = NonNullable<
88
export type InterServerEvents = Record<string, never>;
99
export type SocketGameData = {
1010
user: player;
11-
gameId: number;
1211
currentRound: round;
1312
currentRoundEndTimeout: NodeJS.Timeout;
1413
currentGame: CurrentGame;

apps/duckguessr/app/components/GameStartingSoonModal.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const { firstRoundStartDate } = defineProps<{
4242
firstRoundStartDate: Date;
4343
}>();
4444
45-
const timeBeforeFirstRound = ref(null as number | null);
45+
const timeBeforeFirstRound = ref<number>();
4646
4747
const { t } = useI18n();
4848

apps/duckguessr/app/components/Matchmaking.vue

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
v-if="players.length"
44
:players="players"
55
:game-players-stats="gamePlayersStats!"
6-
:game-id="gameId"
6+
:game-id="game.id"
77
:is-bot-available="isBotAvailableForGame === true"
88
@start-match="startMatch"
99
@add-bot="addBot"
@@ -15,17 +15,18 @@
1515
import type { MatchDetails } from "~duckguessr-types/matchDetails";
1616
import { playerStore } from "~/stores/player";
1717
import type { player, userMedalPoints } from "~duckguessr-prisma-browser";
18+
import type { GameFullNoPersoncode } from "~duckguessr-types/game";
1819
19-
const players = ref([] as player[]);
20-
const gamePlayersStats = ref(null as userMedalPoints[] | null);
21-
const isBotAvailableForGame = ref(null as boolean | null);
20+
const players = ref<player[]>([]);
21+
const gamePlayersStats = ref<userMedalPoints[]>();
22+
const isBotAvailableForGame = ref<boolean>();
2223
23-
const { gameId } = defineProps<{
24-
gameId: number;
24+
const { game } = defineProps<{
25+
game: GameFullNoPersoncode;
2526
}>();
2627
2728
const { getGameSocketFromId } = inject(duckguessrSocketInjectionKey)!;
28-
const gameSocket = getGameSocketFromId(gameId);
29+
const gameSocket = getGameSocketFromId(game.id);
2930
3031
const emit = defineEmits<{
3132
(e: "start-match"): void;
@@ -59,17 +60,16 @@ watch(
5960
() => playerStore().playerUser,
6061
(value) => {
6162
if (value) {
62-
gameSocket.sendGame = () => {
63-
gameSocket
64-
.joinMatch()
65-
.then(({ players, isBotAvailable, playerStats }: MatchDetails) => {
66-
isBotAvailableForGame.value = isBotAvailable;
67-
gamePlayersStats.value = playerStats;
68-
for (const currentPlayer of players) {
69-
addPlayer(currentPlayer);
70-
}
71-
});
72-
};
63+
gameSocket
64+
.joinMatch()
65+
.then(({ players, isBotAvailable, playerStats }: MatchDetails) => {
66+
debugger;
67+
isBotAvailableForGame.value = isBotAvailable;
68+
gamePlayersStats.value = playerStats;
69+
for (const currentPlayer of players) {
70+
addPlayer(currentPlayer);
71+
}
72+
});
7373
gameSocket.playerJoined = (player: player) => {
7474
console.debug(`${player.username} is also ready`);
7575
addPlayer(player);
@@ -79,7 +79,7 @@ watch(
7979
removePlayer(player);
8080
};
8181
gameSocket.matchStarts = () => {
82-
console.debug(`Match starts on game ${gameId}`);
82+
console.debug(`Match starts on game ${game.id}`);
8383
emit("start-match");
8484
};
8585
}

apps/duckguessr/app/components/RoundResultModal.stories.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ export const LastRound: Story = {
8080
fullname: "Carl Barks",
8181
nationalitycountrycode: "us",
8282
},
83-
nextRoundStartDate: null,
83+
nextRoundStartDate: undefined,
8484
hasEverybodyGuessed: false,
8585
},
8686
};

apps/duckguessr/app/components/RoundResultModal.vue

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ const time = new Date().getTime();
8080
const initialTimeBeforeNextRound = computed(() =>
8181
nextRoundStartTime.value ? nextRoundStartTime.value - time : null,
8282
);
83-
const timeBeforeNextRound = ref(null as number | null);
83+
const timeBeforeNextRound = ref<number>();
8484
8585
const emit = defineEmits<{
8686
(e: "next-round"): void;
@@ -91,15 +91,12 @@ const { t } = useI18n();
9191
const url = computed(() => getUrl(roundUrl));
9292
9393
const updateTimeBeforeNextRound = () => {
94-
timeBeforeNextRound.value =
95-
nextRoundStartDate === null
96-
? null
97-
: Math.max(
98-
0,
99-
Math.ceil(
100-
(nextRoundStartDate.getTime() - new Date().getTime()) / 1000,
101-
),
102-
);
94+
timeBeforeNextRound.value = !nextRoundStartDate
95+
? undefined
96+
: Math.max(
97+
0,
98+
Math.ceil((nextRoundStartDate.getTime() - new Date().getTime()) / 1000),
99+
);
103100
};
104101
105102
onMounted(() => {

0 commit comments

Comments
 (0)