Skip to content

Commit

Permalink
disconnect players when game is full to not spam server
Browse files Browse the repository at this point in the history
  • Loading branch information
troypoulter committed Apr 8, 2024
1 parent a885d2e commit b209249
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
3 changes: 3 additions & 0 deletions party/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import type * as Party from "partykit/server";
export default class PigGameServer implements Party.Server {
constructor(readonly room: Party.Room) {}

async onError(connection: Party.Connection, error: Error) {}

async onConnect(connection: Party.Connection) {
let gameState = await this.room.storage.get<GameState>("gameState");
if (!gameState || Object.keys(gameState.players).length >= 2) {
await connection.send(JSON.stringify({ message: "Game is full" }));
connection.close();
return;
}
Expand Down
14 changes: 14 additions & 0 deletions src/components/PigGameUI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,23 @@ export default function PigGameUI({ gameId }: { gameId: string }) {
const [myId, setMyId] = useState<string>("");
const [showWinningConfetti, setShowWinningConfetti] = useState(false);
const [showLosingConfetti, setShowLosingConfetti] = useState(false);
const [gameFullMessage, setGameFullMessage] = useState("");

const socket = usePartySocket({
host: PARTYKIT_HOST,
room: gameId,
onMessage(event) {
const data = JSON.parse(event.data);

if (data.message === "Game is full") {
setGameFullMessage(data.message);
socket.close();
// socket.updateProperties({
// maxRetries: 0,
// });
return;
}

if (data.gameState) {
setGameState(data.gameState as GameState);
}
Expand Down Expand Up @@ -62,6 +72,10 @@ export default function PigGameUI({ gameId }: { gameId: string }) {
const currentPlayer = getPlayerState(gameState, myId);
const winner = getPlayerState(gameState, gameState?.winnerId);

if (gameFullMessage) {
return <div>{gameFullMessage && <div>{gameFullMessage}</div>}</div>;
}

return (
<div>
<div className="bg-blue-400 shadow-md rounded-lg mt-8 mb-6 flex flex-col items-center justify-center">
Expand Down

0 comments on commit b209249

Please sign in to comment.