Skip to content

Commit

Permalink
Live leaderboard page
Browse files Browse the repository at this point in the history
  • Loading branch information
hopperelec committed Mar 12, 2024
1 parent b5c03cd commit 4a24577
Show file tree
Hide file tree
Showing 7 changed files with 128 additions and 31 deletions.
16 changes: 15 additions & 1 deletion src/lib/server/ably-server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import ably from "ably";
import { ABLY_API_KEY } from "$env/static/private";

export default new ably.Realtime.Promise({ key: ABLY_API_KEY });
const ablyServer = new ably.Realtime.Promise({ key: ABLY_API_KEY });
export default ablyServer;

export async function updatePoints(
gameId: number,
userId: number,
points: number,
) {
await ablyServer.channels
.get("player:" + gameId + ":" + userId)
.publish("points", { points: points });
await ablyServer.channels
.get("game:" + gameId + ":points")
.publish("points", { userId, points });
}
15 changes: 6 additions & 9 deletions src/routes/game/[gameId=id]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,6 @@
setTimeout(() => elm.remove(), 1000);
}
function claimRoom(svgRef: number) {
data.currPoints += 1;
movePlayer(data.userId, svgRef);
addPtsChangeGlyph(1);
}
async function askQuestion(question: string): Promise<boolean> {
const res = await fetch("answer", {
method: "POST",
Expand All @@ -100,7 +94,6 @@
while (askAgain) {
if (await askQuestion(question)) askAgain = false;
}
claimRoom(clickedSvgRef);
} else {
alert(
"An unexpected error occurred while trying to choose a question for you.",
Expand Down Expand Up @@ -132,7 +125,10 @@
Points: <span>{data.currPoints}</span>
</p>
<div bind:this={ptsChangeContainer} id="pts-change-container"></div>
{#if data.isHost}<a id="end" class="button" href="end">End game</a>{/if}
<div id="top-right">
<a class="button" href="leaderboard">Leaderboard</a>
{#if data.isHost}<a class="button" href="end">End game</a>{/if}
</div>
<div id="map-container">
<SVGMap
bind:this={map}
Expand Down Expand Up @@ -191,9 +187,10 @@
z-index: -1;
}
#end {
#top-right {
position: fixed;
top: 0;
right: 0;
display: flex;
}
</style>
6 changes: 4 additions & 2 deletions src/routes/game/[gameId=id]/answer/+server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { error, json } from "@sveltejs/kit";
import prisma from "$lib/server/prisma";
import ablyServer from "$lib/server/ably-server";
import ablyServer, { updatePoints } from "$lib/server/ably-server";

export const POST = async ({ request, params, locals }) => {
const player = await prisma.player.findUnique({
Expand All @@ -27,21 +27,23 @@ export const POST = async ({ request, params, locals }) => {
"i",
).test(await request.text());
if (correct) {
await prisma.player.update({
const newPlayerData = await prisma.player.update({
where: { id: player.id },
data: {
currQuestionId: null,
points: { increment: 1 },
currRoomId: player.currMove.id,
currMoveId: null,
},
select: { points: true },
});
await ablyServer.channels
.get("game:" + params.gameId + ":positions")
.publish("move", {
userId: locals.user.id,
svgRef: player.currMove.svgRef,
});
await updatePoints(+params.gameId, locals.user.id, newPlayerData.points);
}
return json({ correct });
};
40 changes: 40 additions & 0 deletions src/routes/game/[gameId=id]/leaderboard/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import getPlayer from "$lib/server/get-player";
import prisma from "$lib/server/prisma";
import { error } from "@sveltejs/kit";

export const load = async ({ params, locals }) => {
const player = await getPlayer(locals.user, +params.gameId);
const ret = await prisma.player.findUnique({
where: { id: player.id },
select: {
isHost: true,
user: { select: { id: true } },
game: {
select: {
players: {
select: {
user: { select: { id: true, name: true } },
points: true,
},
},
},
},
},
});
if (!ret)
error(
500,
"An unexpected error occurred while trying to retrieve your player data",
);
return {
userId: ret.user.id,
isHost: ret.isHost,
players: ret.game.players.map((player) => {
return {
id: player.user.id,
name: player.user.name,
points: player.points,
};
}),
};
};
55 changes: 55 additions & 0 deletions src/routes/game/[gameId=id]/leaderboard/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<script lang="ts">
import Leaderboard from "$lib/Leaderboard.svelte";
import ablyClientStore from "$lib/ably-client";
import { page } from "$app/stores";
import "$lib/button.css";
export let data;
const players = data.players.reduce(
(acc, player) => {
acc[player.id] = {
name: player.name || "User " + player.id,
points: player.points,
};
return acc;
},
{} as { [key: number]: { name: string; points: number } },
);
$: orderedPlayers = Object.values(players).sort(
(a, b) => b.points - a.points,
);
ablyClientStore.subscribe(async (ablyClient) => {
if (!ablyClient) return;
await ablyClient.channels
.get("game:" + $page.params.gameId + ":points")
.subscribe((message) => {
switch (message.name) {
case "points":
players[message.data.userId].points = message.data.points;
break;
}
});
});
</script>

<div id="page-container">
<div id="leaderboard-container">
<Leaderboard {orderedPlayers} />
</div>
<a class="button" href="../">Back to game</a>
</div>

<style>
#page-container {
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
}
#leaderboard-container {
height: 100%;
}
</style>
14 changes: 1 addition & 13 deletions src/routes/game/[gameId=id]/shop/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,6 @@
export let data;
const itemCosts = data.shopItems.reduce(
(acc, item) => {
acc[item.id] = item.cost;
return acc;
},
{} as { [key: number]: number },
);
ablyClientStore.subscribe(async (ablyClient) => {
if (!ablyClient) return;
await ablyClient.channels
Expand All @@ -28,11 +20,7 @@
async function buyItem(itemId: number) {
const res = await fetch(`${itemId}/buy`);
if (res.ok) {
data.points -= itemCosts[itemId];
} else {
alert((await res.json()).message);
}
if (!res.ok) alert((await res.json()).message);
}
</script>

Expand Down
13 changes: 7 additions & 6 deletions src/routes/game/[gameId=id]/shop/[itemId=id]/buy/+server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { error } from "@sveltejs/kit";
import prisma from "$lib/server/prisma";
import ablyServer from "$lib/server/ably-server";
import ablyServer, { updatePoints } from "$lib/server/ably-server";
import type { User } from "@prisma/client";

type ActionDetails = {
Expand Down Expand Up @@ -130,11 +130,7 @@ const ACTIONS: { [key: string]: (details: ActionDetails) => Promise<void> } = {
where: { id: Number(randPlayer.id) },
data: { points: newPoints },
});
await ablyServer.channels
.get("player:" + gameId + ":" + randPlayer.userId)
.publish("points", {
points: newPoints,
});
await updatePoints(gameId, Number(randPlayer.userId), newPoints);
},
};

Expand Down Expand Up @@ -177,5 +173,10 @@ export const GET = async ({ params, locals }) => {
where: { id: player.id },
data: { points: { decrement: shopItem.cost } },
});
await updatePoints(
+params.gameId,
locals.user.id,
player.points - shopItem.cost,
);
return new Response();
};

0 comments on commit 4a24577

Please sign in to comment.