@kuncat/avoidant 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,814 @@
1
+ <script lang="ts">
2
+ import { onMount } from "svelte";
3
+ import { slide } from "svelte/transition";
4
+ import init, { GameState, type GameOptions, type MapData } from "../wasm/avoidant_wasm";
5
+ import { Canvas, T } from "@threlte/core";
6
+ import { OrbitControls } from "@threlte/extras";
7
+ import { MOUSE } from "three";
8
+ import Board from "./board.svelte";
9
+ import { MAP_HEIGHT, MAP_WIDTH } from "../generated/shared-constants";
10
+ import { m } from "../paraglide/messages";
11
+ import { getLocale, locales, setLocale } from "../paraglide/runtime";
12
+ import { generateMap } from "../workers/mapgen-client";
13
+
14
+ const PLAYER_NAME_STORAGE_KEY = "avoidant:playerName";
15
+ const SIZE_PRESETS = { small: 80, medium: 160, large: 320 } as const;
16
+ const MAP_MIN_X = 0;
17
+ const MAP_MIN_Z = 0;
18
+ const MAP_MAX_X = MAP_MIN_X + MAP_WIDTH;
19
+ const MAP_MAX_Z = MAP_MIN_Z + MAP_HEIGHT;
20
+ const MAP_CENTER_X = MAP_MIN_X + MAP_WIDTH / 2;
21
+ const MAP_CENTER_Z = MAP_MIN_Z + MAP_HEIGHT / 2;
22
+
23
+ const CAMERA_AZIMUTH_RAD = Math.PI / 4;
24
+ const CAMERA_ELEVATION_RAD = Math.atan(0.5);
25
+ const CAMERA_ORBIT_RADIUS = 240;
26
+
27
+ const horizontalDistance = Math.cos(CAMERA_ELEVATION_RAD) * CAMERA_ORBIT_RADIUS;
28
+ const cameraPosition: [number, number, number] = [
29
+ MAP_CENTER_X + horizontalDistance * Math.sin(CAMERA_AZIMUTH_RAD),
30
+ Math.sin(CAMERA_ELEVATION_RAD) * CAMERA_ORBIT_RADIUS,
31
+ MAP_CENTER_Z + horizontalDistance * Math.cos(CAMERA_AZIMUTH_RAD),
32
+ ];
33
+
34
+ type SizePreset = keyof typeof SIZE_PRESETS | "custom";
35
+ type Locale = (typeof locales)[number];
36
+ type AvoidantGameProps = {
37
+ relayServers?: string[];
38
+ };
39
+
40
+ let { relayServers = [] }: AvoidantGameProps = $props();
41
+
42
+ const localeLabels: Record<Locale, string> = {
43
+ en: "English",
44
+ bn: "বাংলা",
45
+ };
46
+
47
+ function normalizeRelayServerList(input: string[]): string[] {
48
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
49
+ const seen = new Set<string>();
50
+ const urls: string[] = [];
51
+ for (const item of input) {
52
+ const trimmed = item.trim();
53
+ if (!trimmed || seen.has(trimmed)) {
54
+ continue;
55
+ }
56
+ seen.add(trimmed);
57
+ urls.push(trimmed);
58
+ }
59
+ return urls;
60
+ }
61
+
62
+ function parseRelayServersInput(input: string): string[] {
63
+ return normalizeRelayServerList(input.split(/\r?\n/));
64
+ }
65
+
66
+ let status: string | undefined = $state(undefined);
67
+ let gameState = $state<GameState | undefined>(undefined);
68
+ let terrain = $state<MapData["terrain"] | undefined>(undefined);
69
+ let numCellsInput = $state(SIZE_PRESETS.medium);
70
+ let rngSeedInput = $state(0);
71
+ let playerNameInput = $state(
72
+ typeof window !== "undefined"
73
+ ? (localStorage.getItem(PLAYER_NAME_STORAGE_KEY) ?? m.default_player_name())
74
+ : m.default_player_name(),
75
+ );
76
+ let isTutorialMode = $state(false);
77
+ let tutorialText = $state("");
78
+ let setupMode: "host" | "join" | undefined = $state(undefined);
79
+ let sizePreset = $state<SizePreset>("medium");
80
+ let relayServersInput = $state("");
81
+ let relayServersInitialized = false;
82
+ let hasRelayServersConfigured = $derived(parseRelayServersInput(relayServersInput).length > 0);
83
+ let ticketInput = $state("");
84
+ let joinError: string | undefined = $state(undefined);
85
+ let inviteTicket = $state("");
86
+ let inviteUrl = $derived(
87
+ inviteTicket && typeof window !== "undefined"
88
+ ? `${window.location.origin}${window.location.pathname}?ticket=${encodeURIComponent(inviteTicket)}`
89
+ : "",
90
+ );
91
+ let isGeneratingInvite = $state(false);
92
+ let networkSnapshot = $derived(gameState?.networkSnapshot);
93
+ let score = $derived(gameState?.score);
94
+ let numSafeUnexploredCells = $derived(
95
+ $score ? Math.max(0, $score.totalCells - $score.voidTotal - $score.safeExplored) : 0,
96
+ );
97
+ let isScoreBreakdownHovered = $state(false);
98
+ let isScoreBreakdownPinned = $state(false);
99
+ let showScoreBreakdown = $derived(isScoreBreakdownHovered || isScoreBreakdownPinned);
100
+ let connectedPeerCount = $derived(
101
+ ($networkSnapshot?.peers ?? []).filter((peer) => peer.isConnected).length,
102
+ );
103
+ let cameraZoom = $state(7);
104
+
105
+ function toggleScoreBreakdown() {
106
+ isScoreBreakdownPinned = !isScoreBreakdownPinned;
107
+ }
108
+
109
+ function handleScoreSummaryKeydown(event: KeyboardEvent) {
110
+ if (event.key === "Enter" || event.key === " ") {
111
+ event.preventDefault();
112
+ toggleScoreBreakdown();
113
+ }
114
+ }
115
+
116
+ function calculateCoverZoom(
117
+ viewportWidth: number,
118
+ viewportHeight: number,
119
+ elevationMin: number,
120
+ elevationMax: number,
121
+ ): number {
122
+ const forwardX = -Math.cos(CAMERA_ELEVATION_RAD) * Math.sin(CAMERA_AZIMUTH_RAD);
123
+ const forwardY = -Math.sin(CAMERA_ELEVATION_RAD);
124
+ const forwardZ = -Math.cos(CAMERA_ELEVATION_RAD) * Math.cos(CAMERA_AZIMUTH_RAD);
125
+
126
+ const rightX = -forwardZ;
127
+ const rightZ = forwardX;
128
+ const rightLength = Math.hypot(rightX, rightZ);
129
+ const normalizedRightX = rightX / rightLength;
130
+ const normalizedRightZ = rightZ / rightLength;
131
+
132
+ const upX = normalizedRightZ * forwardY;
133
+ const upY = -(normalizedRightX * forwardZ - normalizedRightZ * forwardX);
134
+ const upZ = -normalizedRightX * forwardY;
135
+
136
+ const yMin = Math.min(elevationMin, elevationMax);
137
+ const yMax = Math.max(elevationMin, elevationMax);
138
+ const corners = [
139
+ [MAP_MIN_X, yMin, MAP_MIN_Z],
140
+ [MAP_MIN_X, yMin, MAP_MAX_Z],
141
+ [MAP_MAX_X, yMin, MAP_MIN_Z],
142
+ [MAP_MAX_X, yMin, MAP_MAX_Z],
143
+ [MAP_MIN_X, yMax, MAP_MIN_Z],
144
+ [MAP_MIN_X, yMax, MAP_MAX_Z],
145
+ [MAP_MAX_X, yMax, MAP_MIN_Z],
146
+ [MAP_MAX_X, yMax, MAP_MAX_Z],
147
+ ];
148
+
149
+ let minRight = Infinity;
150
+ let maxRight = -Infinity;
151
+ let minUp = Infinity;
152
+ let maxUp = -Infinity;
153
+
154
+ for (const [x, y, z] of corners) {
155
+ const projectedRight = x * normalizedRightX + z * normalizedRightZ;
156
+ const projectedUp = x * upX + y * upY + z * upZ;
157
+ minRight = Math.min(minRight, projectedRight);
158
+ maxRight = Math.max(maxRight, projectedRight);
159
+ minUp = Math.min(minUp, projectedUp);
160
+ maxUp = Math.max(maxUp, projectedUp);
161
+ }
162
+
163
+ const projectedWidth = Math.max(1e-6, maxRight - minRight);
164
+ const projectedHeight = Math.max(1e-6, maxUp - minUp);
165
+
166
+ // Threlte's orthographic frustum maps roughly 1 world unit to 1 pixel at zoom=1, so a cover fit is viewport-size divided by projected world size.
167
+ return Math.max(viewportWidth / projectedWidth, viewportHeight / projectedHeight) * 1.01;
168
+ }
169
+
170
+ function setInitialCameraZoom() {
171
+ if (typeof window !== "undefined") {
172
+ const viewportWidth = Math.max(1, window.innerWidth);
173
+ const viewportHeight = Math.max(1, window.innerHeight);
174
+ const elevationMin = gameState?.elevationMin ?? 0;
175
+ const elevationMax = gameState?.elevationMax ?? 0;
176
+ cameraZoom = calculateCoverZoom(viewportWidth, viewportHeight, elevationMin, elevationMax);
177
+ }
178
+ }
179
+
180
+ onMount(() => {
181
+ rngSeedInput = Math.floor(Date.now() / 1000);
182
+
183
+ const initializeWasm = async () => {
184
+ try {
185
+ status = m.status_loading();
186
+ await init();
187
+ status = undefined;
188
+
189
+ const sharedTicket = new URLSearchParams(window.location.search).get("ticket");
190
+ if (sharedTicket) {
191
+ // Clear the ticket from the visible URL so a refresh doesn't re-trigger join.
192
+ window.history.replaceState({}, "", `${window.location.pathname}${window.location.hash}`);
193
+ ticketInput = sharedTicket;
194
+ setupMode = "join";
195
+ }
196
+ } catch (error) {
197
+ status = m.status_initialization_failed();
198
+ console.error("Failed to initialize wasm", error);
199
+ }
200
+ };
201
+
202
+ void initializeWasm();
203
+ });
204
+
205
+ $effect(() => {
206
+ if (relayServersInitialized) {
207
+ return;
208
+ }
209
+
210
+ relayServersInput = normalizeRelayServerList(relayServers).join("\n");
211
+ relayServersInitialized = true;
212
+ });
213
+
214
+ $effect(() => {
215
+ if (!gameState) return;
216
+ setInitialCameraZoom();
217
+ });
218
+
219
+ $effect(() => {
220
+ if (gameState) return;
221
+ isScoreBreakdownHovered = false;
222
+ isScoreBreakdownPinned = false;
223
+ });
224
+
225
+ $effect(() => {
226
+ if (typeof window !== "undefined") {
227
+ try {
228
+ localStorage.setItem(PLAYER_NAME_STORAGE_KEY, playerNameInput);
229
+ } catch (error) {
230
+ console.warn("Failed to persist player name", error);
231
+ }
232
+ }
233
+ });
234
+
235
+ function hexCells(radius: number): string[] {
236
+ const cells: string[] = [];
237
+ const dx = radius * Math.sqrt(3);
238
+ const dy = radius * 1.5;
239
+ const size = 40;
240
+ for (let row = 0; ; row++) {
241
+ const cy = row * dy + radius;
242
+ if (cy - radius > size) break;
243
+ const xOffset = (row % 2) * (dx / 2);
244
+ for (let col = 0; ; col++) {
245
+ const cx = col * dx + xOffset + dx / 2;
246
+ if (cx - dx / 2 > size) break;
247
+ cells.push(
248
+ [
249
+ [cx, cy - radius],
250
+ [cx + dx / 2, cy - radius / 2],
251
+ [cx + dx / 2, cy + radius / 2],
252
+ [cx, cy + radius],
253
+ [cx - dx / 2, cy + radius / 2],
254
+ [cx - dx / 2, cy - radius / 2],
255
+ ]
256
+ .map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`)
257
+ .join(" "),
258
+ );
259
+ }
260
+ }
261
+ return cells;
262
+ }
263
+
264
+ type PresetIcon = {
265
+ value: SizePreset;
266
+ cells: string[] | null;
267
+ readonly label: string;
268
+ };
269
+
270
+ const presetIcons: PresetIcon[] = [
271
+ {
272
+ value: "small",
273
+ cells: hexCells(11),
274
+ get label() {
275
+ return m.preset_small();
276
+ },
277
+ },
278
+ {
279
+ value: "medium",
280
+ cells: hexCells(7),
281
+ get label() {
282
+ return m.preset_medium();
283
+ },
284
+ },
285
+ {
286
+ value: "large",
287
+ cells: hexCells(4.5),
288
+ get label() {
289
+ return m.preset_large();
290
+ },
291
+ },
292
+ {
293
+ value: "custom",
294
+ cells: null,
295
+ get label() {
296
+ return m.preset_custom();
297
+ },
298
+ },
299
+ ];
300
+
301
+ async function startGame() {
302
+ try {
303
+ const resolvedNumCells =
304
+ sizePreset === "custom" ? $state.snapshot(numCellsInput) : SIZE_PRESETS[sizePreset];
305
+ const relayUrls = parseRelayServersInput($state.snapshot(relayServersInput));
306
+ const options: GameOptions = {
307
+ elevationMax: 6.0,
308
+ elevationMin: 0.0,
309
+ numCells: resolvedNumCells,
310
+ relayUrls: relayUrls.length > 0 ? relayUrls : undefined,
311
+ rngSeed: $state.snapshot(rngSeedInput),
312
+ spikiness: 0.8,
313
+ };
314
+ status = m.status_generating_map();
315
+ gameState = new GameState(options);
316
+ const generated = await generateMap(options);
317
+ gameState.applyMapCells(generated.cells);
318
+ terrain = generated.terrain;
319
+ inviteTicket = "";
320
+ } catch (error) {
321
+ console.error("Failed to start game", error);
322
+ } finally {
323
+ setupMode = undefined;
324
+ status = undefined;
325
+ }
326
+ }
327
+
328
+ function extractTicket(input: string): string {
329
+ const trimmed = input.trim();
330
+ if (!trimmed) {
331
+ return "";
332
+ }
333
+ if (/^https?:\/\//i.test(trimmed)) {
334
+ try {
335
+ return new URL(trimmed).searchParams.get("ticket")?.trim() ?? "";
336
+ } catch {
337
+ return "";
338
+ }
339
+ }
340
+ return trimmed;
341
+ }
342
+
343
+ async function joinGame() {
344
+ joinError = undefined;
345
+ let succeeded = false;
346
+ try {
347
+ status = m.status_joining_game();
348
+ const ticket = extractTicket(ticketInput);
349
+ if (!ticket) {
350
+ throw new Error(m.error_join_ticket_required());
351
+ }
352
+ let options: GameOptions;
353
+ try {
354
+ options = GameState.optionsFromTicket(ticket);
355
+ } catch (error) {
356
+ console.error("Failed to parse ticket", error);
357
+ throw new Error(m.error_join_ticket_invalid(), { cause: error });
358
+ }
359
+ const nextGameState = new GameState(options);
360
+ status = m.status_generating_map();
361
+ const generated = await generateMap(options);
362
+ nextGameState.applyMapCells(generated.cells);
363
+ status = m.status_joining_game();
364
+ try {
365
+ await nextGameState.joinAsPeer(ticket, playerNameInput);
366
+ } catch (error) {
367
+ console.error("Failed to join peer", error);
368
+ try {
369
+ nextGameState.free();
370
+ } catch (freeError) {
371
+ console.error("Failed to release game state", freeError);
372
+ }
373
+ throw new Error(m.error_join_connect_failed(), { cause: error });
374
+ }
375
+ gameState = nextGameState;
376
+ terrain = generated.terrain;
377
+ inviteTicket = "";
378
+ succeeded = true;
379
+ } catch (error) {
380
+ console.error("Failed to join game", error);
381
+ joinError = error instanceof Error ? error.message : m.error_join_failed();
382
+ } finally {
383
+ status = undefined;
384
+ if (succeeded) {
385
+ setupMode = undefined;
386
+ ticketInput = "";
387
+ } else {
388
+ setupMode = "join";
389
+ }
390
+ }
391
+ }
392
+
393
+ function exitGame() {
394
+ try {
395
+ gameState?.free();
396
+ } catch (error) {
397
+ console.error("Failed to release game state", error);
398
+ }
399
+ gameState = undefined;
400
+ setupMode = undefined;
401
+ inviteTicket = "";
402
+ ticketInput = "";
403
+ joinError = undefined;
404
+ status = undefined;
405
+ rngSeedInput = Math.floor(Date.now() / 1000);
406
+ }
407
+
408
+ async function copyInviteTicket() {
409
+ if (!inviteUrl) {
410
+ return;
411
+ }
412
+ try {
413
+ await navigator.clipboard.writeText(inviteUrl);
414
+ } catch (error) {
415
+ console.error("Failed to copy invitation URL", error);
416
+ }
417
+ }
418
+
419
+ async function generateInvite() {
420
+ if (isGeneratingInvite) {
421
+ return;
422
+ }
423
+ isGeneratingInvite = true;
424
+ try {
425
+ inviteTicket = (await gameState?.invite(playerNameInput)) ?? "";
426
+ if (inviteTicket) {
427
+ await copyInviteTicket();
428
+ }
429
+ } catch (error) {
430
+ console.error("Failed to create invitation", error);
431
+ } finally {
432
+ isGeneratingInvite = false;
433
+ }
434
+ }
435
+ </script>
436
+
437
+ <div
438
+ class="panel-wrapper fixed inset-x-0 z-20 flex justify-center select-none"
439
+ class:[&_*]:text-white={gameState}
440
+ class:panel-wrapper-card={!gameState}
441
+ class:panel-wrapper-header={gameState}
442
+ oncontextmenu={(event) => event.preventDefault()}
443
+ role="application"
444
+ >
445
+ <div
446
+ class="panel-shell w-full"
447
+ class:max-w-full={gameState}
448
+ class:max-w-md={!gameState && setupMode}
449
+ class:max-w-xs={!gameState && !setupMode}
450
+ class:panel-card={!gameState}
451
+ class:panel-header={gameState}
452
+ class:py-6={!gameState && setupMode}
453
+ class:py-12={!gameState && !setupMode}
454
+ >
455
+ <div class="flex flex-wrap items-center gap-3" class:justify-center={!gameState}>
456
+ <h1
457
+ class="panel-title font-semibold tracking-wide"
458
+ class:pb-4={!gameState}
459
+ class:text-5xl={!gameState}
460
+ class:text-lg={gameState}
461
+ >
462
+ Avoidant
463
+ </h1>
464
+ {#if gameState}
465
+ {#if $score}
466
+ <div
467
+ class="relative text-sm text-slate-600"
468
+ role="group"
469
+ aria-label={m.aria_score_summary()}
470
+ onmouseenter={() => (isScoreBreakdownHovered = true)}
471
+ onmouseleave={() => (isScoreBreakdownHovered = false)}
472
+ >
473
+ <div
474
+ class="score-summary"
475
+ role="button"
476
+ tabindex="0"
477
+ aria-expanded={showScoreBreakdown}
478
+ aria-controls="score-breakdown"
479
+ onclick={toggleScoreBreakdown}
480
+ onfocus={() => (isScoreBreakdownHovered = true)}
481
+ onblur={() => (isScoreBreakdownHovered = false)}
482
+ onkeydown={handleScoreSummaryKeydown}
483
+ >
484
+ {m.label_score()}: <strong class="text-slate-200!">{Math.round($score.score)}</strong>
485
+ <span class="opacity-70">({Math.round($score.efficiency * 100)}%)</span>
486
+ {#if $score.completed}
487
+ <span class="font-semibold text-emerald-600!">{m.text_avoided()}</span>
488
+ {:else}
489
+ <span class="opacity-80">
490
+ {m.label_safe_cells_remaining({ count: numSafeUnexploredCells })}:
491
+ <strong class="text-slate-200!">{numSafeUnexploredCells}</strong>
492
+ </span>
493
+ {/if}
494
+ </div>
495
+
496
+ {#if showScoreBreakdown}
497
+ <div id="score-breakdown" class="score-breakdown" role="status">
498
+ {#if $score.streak > 1}<p>
499
+ <span class="opacity-70"
500
+ >×{(1 + Math.min($score.streak, 10) * 0.1).toFixed(1)}
501
+ {m.label_streak()}</span
502
+ >
503
+ </p>
504
+ {/if}
505
+ <p class="text-emerald-600!">
506
+ {m.label_safe_cells_explored({ count: $score.safeExplored })}:
507
+ <strong>{$score.safeExplored}</strong>
508
+ </p>
509
+ <p class="text-rose-500!">
510
+ {m.label_voids_discovered()}: <strong>{$score.voidExplored}</strong>
511
+ </p>
512
+ </div>
513
+ {/if}
514
+ </div>
515
+ {/if}
516
+ <div class="ml-auto text-sm text-slate-200!">
517
+ {#if connectedPeerCount > 0}
518
+ {m.label_players({ count: connectedPeerCount + 1 })}:
519
+ <strong>{connectedPeerCount + 1}</strong>
520
+ {/if}
521
+ </div>
522
+ <div class="flex gap-2">
523
+ {#if !isTutorialMode && hasRelayServersConfigured && ($score?.safeExplored ?? 0) + ($score?.voidExplored ?? 0) === 0}
524
+ <button
525
+ class="btn btn-primary"
526
+ type="button"
527
+ onclick={generateInvite}
528
+ disabled={isGeneratingInvite}
529
+ >
530
+ {#if isGeneratingInvite}
531
+ <span class="spinner" aria-hidden="true"></span>
532
+ <span>{m.status_preparing()}</span>
533
+ {:else}
534
+ {m.action_invite()}
535
+ {/if}
536
+ </button>
537
+ {/if}
538
+ <button class="btn btn-danger" type="button" onclick={exitGame}>{m.action_exit()}</button>
539
+ </div>
540
+ {/if}
541
+ </div>
542
+
543
+ {#if status}
544
+ <p class="mt-2 text-sm text-slate-600!">{status}</p>
545
+ {/if}
546
+
547
+ {#if !gameState}
548
+ {#if setupMode === "host"}
549
+ <form
550
+ class="mt-4 w-full"
551
+ transition:slide={{ duration: 150 }}
552
+ onsubmit={async (event) => {
553
+ event.preventDefault();
554
+ await startGame();
555
+ }}
556
+ >
557
+ <div class="-mx-3 mb-2 flex flex-wrap">
558
+ <div class="mb-4 w-full px-3">
559
+ <label class="field-label" for="player-name">{m.field_player_name()}</label>
560
+ <input class="field" id="player-name" type="text" bind:value={playerNameInput} />
561
+ </div>
562
+ <div class="mb-4 w-full px-3">
563
+ <span class="field-label">{m.field_map_size()}</span>
564
+ <div class="grid grid-cols-4 gap-2">
565
+ {#each presetIcons as preset (preset.value)}
566
+ <button
567
+ type="button"
568
+ class="preset-btn"
569
+ class:preset-btn-active={sizePreset === preset.value}
570
+ aria-pressed={sizePreset === preset.value}
571
+ onclick={() => (sizePreset = preset.value)}
572
+ >
573
+ <span class="preset-icon">
574
+ {#if preset.cells}
575
+ <svg
576
+ viewBox="0 0 40 40"
577
+ fill="none"
578
+ stroke="currentColor"
579
+ stroke-width="1"
580
+ stroke-linejoin="round"
581
+ aria-hidden="true"
582
+ >
583
+ {#each preset.cells as points, i (i)}
584
+ <polygon {points} />
585
+ {/each}
586
+ </svg>
587
+ {:else}
588
+ <svg
589
+ viewBox="0 0 40 40"
590
+ fill="none"
591
+ stroke="currentColor"
592
+ stroke-width="2.5"
593
+ stroke-linecap="round"
594
+ aria-hidden="true"
595
+ >
596
+ <line x1="8" y1="12" x2="32" y2="12" />
597
+ <circle cx="15" cy="12" r="3.5" fill="currentColor" />
598
+ <line x1="8" y1="20" x2="32" y2="20" />
599
+ <circle cx="25" cy="20" r="3.5" fill="currentColor" />
600
+ <line x1="8" y1="28" x2="32" y2="28" />
601
+ <circle cx="19" cy="28" r="3.5" fill="currentColor" />
602
+ </svg>
603
+ {/if}
604
+ </span>
605
+ <span class="preset-label">{preset.label}</span>
606
+ <span class="preset-count">
607
+ {preset.value === "custom"
608
+ ? sizePreset === "custom"
609
+ ? m.cells_count({ count: numCellsInput })
610
+ : ""
611
+ : m.cells_count({ count: SIZE_PRESETS[preset.value] })}
612
+ </span>
613
+ </button>
614
+ {/each}
615
+ </div>
616
+ </div>
617
+ <div class="mb-4 w-full px-3">
618
+ <details class="advanced-settings">
619
+ <summary class="advanced-settings-summary">{m.label_advanced_settings()}</summary>
620
+ <div class="advanced-settings-content">
621
+ <label class="field-label" for="relay-servers"
622
+ ><a
623
+ href="https://docs.iroh.computer/deployment/dedicated-infrastructure"
624
+ target="_blank"
625
+ rel="noopener noreferrer">{m.field_relay_servers()}</a
626
+ ></label
627
+ >
628
+ <textarea
629
+ class="field field-textarea mb-1"
630
+ id="relay-servers"
631
+ bind:value={relayServersInput}
632
+ rows="4"
633
+ spellcheck="false"
634
+ ></textarea>
635
+ <p class="field-help">{m.text_relay_servers_hint()}</p>
636
+ </div>
637
+ </details>
638
+ </div>
639
+ {#if sizePreset === "custom"}
640
+ <div class="w-full px-3" transition:slide={{ duration: 180 }}>
641
+ <div class="-mx-3 flex flex-wrap">
642
+ <div class="mb-6 w-full px-3 md:mb-0 md:w-1/2">
643
+ <label class="field-label" for="grid-first-name">{m.field_size()}</label>
644
+ <input
645
+ class="field"
646
+ id="grid-first-name"
647
+ type="number"
648
+ inputmode="numeric"
649
+ bind:value={numCellsInput}
650
+ min="32"
651
+ max="5000"
652
+ step="1"
653
+ />
654
+ </div>
655
+ <div class="w-full px-3 md:w-1/2">
656
+ <label class="field-label" for="grid-last-name">{m.field_seed()}</label>
657
+ <input
658
+ class="field"
659
+ id="grid-last-name"
660
+ type="number"
661
+ inputmode="numeric"
662
+ bind:value={rngSeedInput}
663
+ min="0"
664
+ />
665
+ </div>
666
+ </div>
667
+ </div>
668
+ {/if}
669
+ <!-- <div class="checkbox-field mb-4 flex w-full items-center gap-2 px-3">
670
+ <label class="field-label mb-0!" for="tutorial-mode">Tutorial Mode</label>
671
+ <input id="tutorial-mode" type="checkbox" bind:checked={isTutorialMode} />
672
+ </div> -->
673
+ </div>
674
+ <div class="flex flex-wrap justify-center gap-2">
675
+ <button class="btn btn-secondary" type="button" onclick={() => (setupMode = undefined)}>
676
+ {m.action_back()}
677
+ </button>
678
+ <button class="btn btn-primary" type="submit">{m.action_start()}</button>
679
+ </div>
680
+ </form>
681
+ {:else if setupMode === "join"}
682
+ <form
683
+ class="mt-4 w-full"
684
+ transition:slide={{ duration: 220 }}
685
+ onsubmit={async (event) => {
686
+ event.preventDefault();
687
+ await joinGame();
688
+ }}
689
+ >
690
+ <div class="-mx-3 mb-2 flex flex-wrap">
691
+ <div class="mb-6 w-full px-3 md:mb-0">
692
+ <label class="field-label" for="join-player-name">{m.field_player_name()}</label>
693
+ <input class="field" id="join-player-name" type="text" bind:value={playerNameInput} />
694
+ </div>
695
+ <div class="mb-6 w-full px-3 md:mb-0">
696
+ <label class="field-label" for="grid-first-name"
697
+ >{m.field_ticket_or_invitation_url()}</label
698
+ >
699
+ <input
700
+ class="field"
701
+ id="grid-first-name"
702
+ type="text"
703
+ bind:value={ticketInput}
704
+ oninput={() => (joinError = undefined)}
705
+ />
706
+ </div>
707
+ {#if joinError}
708
+ <div class="w-full px-3" transition:slide={{ duration: 150 }}>
709
+ <p class="join-error" role="alert">{joinError}</p>
710
+ </div>
711
+ {/if}
712
+ </div>
713
+ <div class="flex flex-wrap justify-center gap-2">
714
+ <button
715
+ class="btn btn-secondary"
716
+ type="button"
717
+ onclick={() => {
718
+ setupMode = undefined;
719
+ joinError = undefined;
720
+ }}
721
+ >
722
+ {m.action_back()}
723
+ </button>
724
+ <button class="btn btn-primary" type="submit">{m.action_join()}</button>
725
+ </div>
726
+ </form>
727
+ {:else}
728
+ <div class="mt-4 flex flex-wrap justify-center gap-2" transition:slide={{ duration: 220 }}>
729
+ <button class="btn btn-primary" type="button" onclick={() => (setupMode = "host")}>
730
+ {m.action_new_game()}
731
+ </button>
732
+ <button class="btn btn-primary" type="button" onclick={() => (setupMode = "join")}>
733
+ {m.action_join_game()}
734
+ </button>
735
+ </div>
736
+ <div class="mt-4 flex justify-center" transition:slide={{ duration: 180 }}>
737
+ <label class="sr-only" for="language-select">Language</label>
738
+ <select
739
+ id="language-select"
740
+ class="locale-select min-w-1/2"
741
+ value={getLocale()}
742
+ aria-label="Language"
743
+ onchange={(event) => {
744
+ setLocale((event.currentTarget as HTMLSelectElement).value as Locale);
745
+ }}
746
+ >
747
+ {#each locales as locale (locale)}
748
+ <option value={locale}
749
+ >{localeLabels[locale] ? `${localeLabels[locale]} (${locale})` : locale}</option
750
+ >
751
+ {/each}
752
+ </select>
753
+ </div>
754
+ {/if}
755
+ {:else if inviteTicket}
756
+ <div class="mt-3" transition:slide={{ duration: 200 }}>
757
+ <div class="mb-2 flex items-center justify-between gap-2">
758
+ <label class="field-label mb-0" for="invite-ticket">{m.field_invitation_url()}</label>
759
+ <button
760
+ class="icon-btn"
761
+ type="button"
762
+ aria-label={m.aria_close_invitation()}
763
+ onclick={() => (inviteTicket = "")}
764
+ >
765
+ ×
766
+ </button>
767
+ </div>
768
+ <div class="flex items-stretch gap-2">
769
+ <input
770
+ id="invite-ticket"
771
+ class="field mb-0 flex-1"
772
+ type="text"
773
+ readonly
774
+ value={inviteUrl}
775
+ />
776
+ <button class="btn btn-secondary" type="button" onclick={copyInviteTicket}>
777
+ {m.action_copy()}
778
+ </button>
779
+ </div>
780
+ </div>
781
+ {/if}
782
+ </div>
783
+ </div>
784
+
785
+ {#if gameState}
786
+ <div style="height: 100vh; width: 100%;">
787
+ <Canvas colorSpace="srgb-linear">
788
+ <T.OrthographicCamera
789
+ makeDefault
790
+ zoom={cameraZoom}
791
+ near={0.1}
792
+ far={1000}
793
+ position={cameraPosition}
794
+ />
795
+ <Board bind:gameState {terrain} />
796
+ <OrbitControls
797
+ enableDamping
798
+ enablePan={true}
799
+ enableZoom={true}
800
+ enableRotate={true}
801
+ minPolarAngle={0}
802
+ maxPolarAngle={Math.PI / 2}
803
+ target={[MAP_CENTER_X, 0, MAP_CENTER_Z]}
804
+ mouseButtons={{ LEFT: MOUSE.PAN, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.ROTATE }}
805
+ />
806
+ </Canvas>
807
+ </div>
808
+ {/if}
809
+
810
+ {#if isTutorialMode}
811
+ <div class="absolute bottom-0 h-10 w-full px-4 text-slate-200">
812
+ {tutorialText}
813
+ </div>
814
+ {/if}