Added Websockets

This commit is contained in:
2025-08-30 00:55:31 +02:00
parent 04a47f4a00
commit 362cd7019b
12 changed files with 223 additions and 22 deletions

View File

@@ -0,0 +1,113 @@
<script lang="ts">
import Wall from "./Wall.svelte";
import type { Player } from "./Player";
import { GameState } from "./GameState";
import type { Game } from "$lib/games/games";
import ws from "$lib/websocket.svelte";
import { page } from "$app/state";
let startDisabled = $state(true);
let _startDisabled = true;
$effect(() => {
if (!ws.message) return;
console.log(ws.message);
if (ws.nextMessage() == "DISPLAY-CONNECTED") {
if (!_startDisabled) {
gameManager?.sendStart();
gameManager?.sendCurrentState();
}
_startDisabled = false;
startDisabled = false;
}
});
class GameManager {
public state: GameState = $state(GameState.INIT);
public game: Game;
public players: Player[];
public currentWall = $state(0);
constructor(game: Game, players: Player[]) {
this.game = game;
this.players = players;
}
startGame(): void {
this.state = GameState.CHOOSING_QUESTION;
this.sendStart();
this.sendCurrentState();
}
sendStart(): void {
ws.sendMessage({
type: "start"
});
}
sendCurrentState(): void {
ws.sendMessage({
type: "players",
players
});
ws.sendMessage({
type: "goto",
route: `/${page.params.game}/${this.currentWall}`
});
}
}
let { data } = $props();
let players: Player[] = $state([
{
name: "Player 1",
points: 0
},
{
name: "Player 2",
points: 0
},
{
name: "Player 3",
points: 0
}
]);
let gameManager = new GameManager(data, players);
function addPlayer() {
players.push({
name: "Player " + (players.length + 1),
points: 0
});
}
function removePlayer(index: number) {
players.splice(index, 1);
}
</script>
<div class="flex h-full flex-col">
<h1 class="ms-4 text-7xl font-bold">{gameManager.game.name}</h1>
{#if gameManager.state === GameState.INIT}
<div class="p-4">
<div class="flex items-center">
<h2 class="grow pb-4 text-5xl">Spieler</h2>
<button class="btn" disabled={startDisabled} onclick={() => gameManager.startGame()}
>Start</button
>
</div>
<div class="flex flex-col space-y-2 pb-4">
{#each gameManager.players as player, i}
<div class="flex items-center">
<input class="inputField grow" type="text" bind:value={player.name} />
<button class="btn" onclick={() => removePlayer(i)}>Löschen</button>
</div>
{/each}
</div>
<button class="btn" onclick={addPlayer}>Spieler hinzufügen</button>
</div>
{:else}
<Wall wall={gameManager.game.walls[gameManager.currentWall]} />
{/if}
</div>