Compare commits

...

15 Commits

27 changed files with 597 additions and 324 deletions

2
.gitignore vendored
View File

@@ -2,6 +2,8 @@
.vinxi
*.db
.DS_STORE
# ---> Node
# Logs
logs

View File

@@ -8,3 +8,8 @@ build:
start:
PORT=$(PORT) pnpm start
note:
./notes/newfile
# touch ./notes/$$file.md
# code -r ./notes/$$file.md

7
deploy Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
branch=$(git branch --show-current)
git switch prod
git merge $branch
git push
git switch $branch

7
notes/newfile Executable file
View File

@@ -0,0 +1,7 @@
#!/bin/bash
ts=$(date +"%Y-%m-%d-%H%M%S")
file=./notes/$ts.md
touch $file
echo -e "# $ts\n" > $file
echo "$file:end"
code --goto "$file:2"

View File

@@ -1,7 +1,7 @@
{
"name": "games",
"type": "module",
"version": "0.0.8",
"version": "0.0.10",
"scripts": {
"dev": "pnpm --parallel dev",
"build": "pnpm run -F client build",

View File

@@ -8,9 +8,11 @@
},
"dependencies": {
"@elysiajs/eden": "^1.3.2",
"@solid-primitives/memo": "^1.4.3",
"@solid-primitives/scheduled": "^1.5.2",
"@solid-primitives/storage": "^4.3.3",
"@solidjs/router": "^0.15.3",
"color2k": "^2.0.3",
"js-cookie": "^3.0.5",
"kefir": "^3.8.8",
"kefir-bus": "^2.3.1",

View File

@@ -11,6 +11,4 @@ const { api } = treaty<Api>(
export default api;
export const fromWebsocket = <T>(ws: any) =>
fromEvents(ws, "message").map(
(evt) => (evt as unknown as { data: T }).data
);
fromEvents(ws, "message").map((evt) => (evt as unknown as { data: T }).data);

View File

@@ -1,7 +1,7 @@
import { Component, Suspense } from "solid-js";
import type { Card } from "@games/shared/cards";
import { Clickable, Sizable, Stylable } from "./toolbox";
import { Clickable, Scalable, Stylable } from "./toolbox";
const cardToSvgFilename = (card: Card) => {
if (card.kind == "joker") {
@@ -17,7 +17,12 @@ const cardToSvgFilename = (card: Card) => {
}`;
};
export const CARD_RATIO = 1.456730769;
export const BASE_CARD_WIDTH = 100;
export default ((props) => {
const width = () => BASE_CARD_WIDTH * (props.scale ?? 1);
const height = () => width() * CARD_RATIO;
return (
<Suspense>
<img
@@ -25,8 +30,8 @@ export default ((props) => {
draggable={false}
class={props.class}
style={props.style}
width={props.width ?? "100px"}
height={props.height}
width={`${width()}px`}
height={`${height()}px`}
src={
props.face == "down"
? "/views/back.svg"
@@ -45,5 +50,5 @@ export default ((props) => {
) &
Stylable &
Clickable &
Sizable
Scalable
>;

View File

@@ -1,8 +1,9 @@
import type { Hand } from "@games/shared/cards";
import { For } from "solid-js";
import Card from "./Card";
import { Stylable } from "./toolbox";
export default (props: { handCount: number }) => {
export default (props: { handCount: number } & Stylable) => {
return (
<For each={Array(props.handCount)}>
{(_, i) => {
@@ -10,16 +11,16 @@ export default (props: { handCount: number }) => {
return (
<Card
face="down"
width="40px"
scale={0.4}
style={{
"margin-left": "-10px",
"margin-right": "-10px",
transform: `rotate(${
midOffset * 0.2
}rad) translate(0px, ${
2 ** Math.abs(midOffset) * 2
}px)`,
"box-shadow": "-4px 4px 4px rgba(0, 0, 0, 0.7)",
"margin-left": "-12px",
"margin-right": "-12px",
transform: `translate(0px, ${Math.pow(
Math.abs(midOffset),
2
)}px) rotate(${midOffset * 0.12}rad)`,
"min-width": "40px",
"box-shadow": "-4px 4px 6px rgba(0, 0, 0, 0.6)",
}}
/>
);

View File

@@ -1,73 +0,0 @@
import { Accessor, createContext, For, useContext } from "solid-js";
import type {
SimpleAction,
SimplePlayerView,
SimpleResult,
} from "@games/shared/games/simple";
import { me } from "~/profile";
import Hand from "./Hand";
import Pile from "./Pile";
import { TableContext } from "./Table";
import { Portal } from "solid-js/web";
import FannedHand from "./FannedHand";
export const GameContext = createContext<{
view: Accessor<SimplePlayerView>;
submitAction: (action: SimpleAction) => any;
}>();
export default () => {
const table = useContext(TableContext)!;
const view = table.view as Accessor<SimplePlayerView>;
const submitAction = (action: SimpleAction) => table.sendWs({ action });
return (
<GameContext.Provider value={{ view, submitAction }}>
<Pile
count={view().deckCount}
class="cursor-pointer fixed center"
onClick={() => submitAction({ type: "draw" })}
/>
<Hand
class="fixed bc"
hand={view().myHand}
onClickCard={(card) => submitAction({ type: "discard", card })}
/>
<div class="absolute tc text-align-center">
It's{" "}
<span class="font-bold">
{view().playerTurn == me()
? "your"
: table.playerNames[view().playerTurn] + "'s"}
</span>{" "}
turn
</div>
<button
class="button fixed tl m-4 p-1"
onClick={() => {
table.sendWs({ quit: true });
}}
>
Quit
</button>
<For each={Object.entries(view().playerHandCounts)}>
{([playerKey, handCount], i) => (
<Portal
mount={document.getElementById(`player-${playerKey}`)!}
ref={(ref) => {
const midOffset =
i() + 0.5 - Object.values(view().playerHandCounts).length / 2;
ref.style = `position: absolute; display: flex; justify-content: center; top: 65%; transform: translate(${Math.abs(
midOffset * 0
)}px, 0px) rotate(${midOffset * 1}rad)`;
}}
>
<FannedHand handCount={handCount} />
</Portal>
)}
</For>
</GameContext.Provider>
);
};

View File

@@ -1,22 +1,63 @@
import { Component, For, JSX, Show } from "solid-js";
import Card from "./Card";
import { Component, createMemo, For, JSX, Show } from "solid-js";
import Card, { BASE_CARD_WIDTH, CARD_RATIO } from "./Card";
import { desaturate } from "color2k";
import { Clickable, Stylable } from "./toolbox";
import { Clickable, hashColor, Scalable, Stylable } from "./toolbox";
const cardOffset = 0.35; // Small offset for the stack effect
export default ((props) => {
const cards = createMemo(() => {
const numCards = Math.max(0, props.count - 1); // Subtract 1 for the top card
return Array.from({ length: numCards }, (_, i) => i).toReversed();
});
const width = () => BASE_CARD_WIDTH * (props.scale ?? 1);
const height = () => width() * CARD_RATIO;
const offset = () => cardOffset * (props.scale ?? 1);
return (
<Show when={props.count > 0}>
<Card
onClick={props.onClick}
style={props.style}
class={props.class + " shadow-lg shadow-black"}
face="down"
<div
style={{
...props.style,
}}
class={props.class}
>
<svg
class="absolute z-[-1]"
width={width() + cards().length * offset()}
height={height() + cards().length * offset()}
viewBox={`0 0 ${width() + cards().length * offset()} ${
height() + cards().length * offset()
}`}
xmlns="http://www.w3.org/2000/svg"
>
<For each={cards()}>
{(i) => {
const xOffset = (i * offset()) / 2;
const yOffset = i * offset();
const color = desaturate(hashColor(i), 0.9);
return (
<rect
x={xOffset}
y={yOffset}
width={width()}
height={height()}
rx="5" // Rounded corners
ry="5"
fill={color}
/>
);
}}
</For>
</svg>
<Card onClick={props.onClick} face="down" scale={props.scale} />
</div>
</Show>
);
}) satisfies Component<
{
count: number;
} & Stylable &
Clickable
Clickable &
Scalable
>;

View File

@@ -1,28 +1,18 @@
import { createSignal, useContext } from "solid-js";
import { onMount, useContext } from "solid-js";
import { playerColor } from "~/profile";
import { TableContext } from "./Table";
import { Stylable } from "./toolbox";
import { createObservable, createObservableWithInit } from "~/fn";
import { GameContext } from "./Game";
export default (props: { playerKey: string } & Stylable) => {
const table = useContext(TableContext);
const playerReady =
table?.wsEvents
.filter((evt) => evt.playersReady != null)
.map((evt) => evt.playersReady![props.playerKey])
.thru((Evt) => createObservableWithInit(Evt, false)) ??
createSignal(false)[0];
const game = useContext(GameContext);
return (
<div
id={`player-${props.playerKey}`}
ref={(e) => table?.setPlayers(props.playerKey, { ref: e })}
style={{
...props.style,
"background-color": playerColor(props.playerKey),
...(playerReady() && table?.view() == null
...(table?.view() == null && table?.players[props.playerKey].ready
? {
border: "10px solid green",
}
@@ -30,8 +20,8 @@ export default (props: { playerKey: string } & Stylable) => {
}}
class={`${props.class} w-20 h-20 rounded-full flex justify-center items-center`}
>
<p style={{ "font-size": "1em" }}>
{table?.playerNames[props.playerKey]}
<p class="font-[1em] text-align-center">
{table?.players[props.playerKey].name}
</p>
</div>
);

View File

@@ -1,5 +1,6 @@
import type { TWsIn, TWsOut } from "@games/server/src/table";
import { fromPromise, merge, Stream } from "kefir";
import games from "@games/shared/games/index";
import { pool, Property, Stream } from "kefir";
import {
Accessor,
createContext,
@@ -7,98 +8,140 @@ import {
createSignal,
For,
onCleanup,
onMount,
Setter,
Show,
} from "solid-js";
import { createStore, SetStoreFunction, Store } from "solid-js/store";
import { Dynamic } from "solid-js/web";
import api, { fromWebsocket } from "~/api";
import {
createObservable,
createObservableStore,
createObservableWithInit,
cx,
} from "~/fn";
import { me, mePromise } from "~/profile";
import Game from "./Game";
import { createObservable, createSynced, cx, extractProperty } from "~/fn";
import { me, name } from "~/profile";
import GAMES from "./games";
import Player from "./Player";
import games from "@games/shared/games/index";
import { createStore, Store } from "solid-js/store";
import { name } from "~/profile";
type PlayerStore = Store<{
[key: string]: {
name: string;
ready: boolean;
ref?: HTMLDivElement;
};
}>;
export const TableContext = createContext<{
view: Accessor<any>;
sendWs: (msg: TWsIn) => void;
wsEvents: Stream<TWsOut, any>;
playerNames: Store<{ [key: string]: string }>;
sendWs: (msg: TWsIn) => void;
tableRef: HTMLDivElement;
gameConfig: Accessor<any>;
setGameConfig: Setter<any>;
players: PlayerStore;
setPlayers: SetStoreFunction<PlayerStore>;
view: Accessor<any>;
}>();
export default (props: { tableKey: string }) => {
const wsPromise = new Promise<
ReturnType<ReturnType<typeof api.ws>["subscribe"]>
>((res) => {
const ws = api.ws(props).subscribe();
ws.on("open", () => res(ws));
ws.on("error", () => res(ws));
});
// #region Websocket declaration
let ws: ReturnType<ReturnType<typeof api.ws>["subscribe"]> | undefined =
undefined;
const wsEvents = pool<TWsOut, any>();
const sendWs = (msg: TWsIn) => ws?.send(msg);
const sendWs = (msg: TWsIn) => wsPromise.then((ws) => ws.send(msg));
const wsEvents = fromPromise(wsPromise).flatMap((ws) =>
fromWebsocket<TWsOut>(ws)
);
onCleanup(() => wsPromise.then((ws) => ws.close()));
// #endregion
const presenceEvents = wsEvents.filter(
(evt) => evt.playersPresent !== undefined
);
const gameEvents = wsEvents.filter((evt) => evt.view !== undefined);
const resultEvents = wsEvents.filter((evt) => evt.results !== undefined);
// #region inbound table properties
const [players, setPlayers] = createStore<PlayerStore>({});
const players = createObservableWithInit<string[]>(
presenceEvents.map((evt) => evt.playersPresent!),
[]
);
const playerNames = createObservableStore(
wsEvents
.filter((evt) => evt.playerNames != null)
.map(({ playerNames }) => playerNames!)
.toProperty(),
{}
.thru(extractProperty("playersPresent"))
.onValue((P) =>
setPlayers(
Object.fromEntries(
P.map((p) => [
p,
p in players ? players[p] : { name: "", ready: false },
])
)
)
);
wsEvents.thru(extractProperty("playerNames")).onValue((P) =>
Object.entries(P)
.filter(([player]) => player in players)
.map(([player, name]) => setPlayers(player, "name", name))
);
wsEvents.thru(extractProperty("playersReady")).onValue((P) =>
Object.entries(P)
.filter(([player]) => player in players)
.map(([player, ready]) => setPlayers(player, "ready", ready))
);
// #endregion
// #region inbound game properties
const [gameConfig, setGameConfig] = createSynced({
ws: wsEvents.thru(extractProperty("gameConfig")) as Property<
{ game: string; players: string[] },
any
>,
sendWs: (gameConfig) => sendWs({ gameConfig }),
});
const view = wsEvents.thru(extractProperty("view")).thru(createObservable);
// #endregion
const [ready, setReady] = createSignal(false);
mePromise.then(
(me) =>
me &&
wsEvents
.filter((evt) => evt.playersReady !== undefined)
.map((evt) => evt.playersReady?.[me] ?? false)
.onValue(setReady)
);
onMount(() => {
ws = api.ws(props).subscribe();
ws.on("open", () => {
wsEvents.plug(fromWebsocket<TWsOut>(ws));
// TODO: these need to be in a tracking scope to be disposed
createEffect(() => sendWs({ ready: ready() }));
createEffect(() => sendWs({ name: name() }));
const view = createObservable(gameEvents.map((evt) => evt.view));
const results = createObservable<string>(
merge([
gameEvents
.filter((evt) => "view" in evt && evt.view == null)
.map(() => undefined),
resultEvents.map((evt) => evt.results),
])
);
});
onCleanup(() => ws?.close());
});
const GamePicker = () => {
return (
<div class="absolute tc mt-8 flex gap-4">
<select value={gameConfig()?.game}>
<For each={Object.entries(games)}>
{([gameId]) => <option value={gameId}>{gameId}</option>}
</For>
</select>
<button onClick={() => setReady((prev) => !prev)} class="button p-1 ">
{ready() ? "Not Ready" : "Ready"}
</button>
</div>
);
};
let tableRef!: HTMLDivElement;
return (
<TableContext.Provider
value={{
sendWs,
wsEvents,
sendWs,
tableRef,
players,
setPlayers,
gameConfig,
setGameConfig,
view,
playerNames,
}}
>
{/* Player avatars around the table */}
<div class="flex justify-around p-t-14">
<For each={players().filter((p) => p != me())}>
<For each={gameConfig()?.players.filter((p) => p != me())}>
{(player, i) => {
const verticalOffset = () => {
const N = players().length - 1;
const N = gameConfig()!.players.length - 1;
const x = Math.abs((2 * i() + 1) / (N * 2) - 0.5);
const y = Math.sqrt(1 - x * x);
return 1 - y;
@@ -114,8 +157,10 @@ export default (props: { tableKey: string }) => {
}}
</For>
</div>
{/* The table body itself */}
<div
id="table"
ref={tableRef}
class={cx(
"fixed",
@@ -129,37 +174,26 @@ export default (props: { tableKey: string }) => {
"top-40",
"bottom-20",
"left-10",
"right-10"
"left-[2%]",
"right-[2%]"
)}
style={{
"border-radius": "50%",
}}
>
<Show when={view() == null}>
<div class="absolute tc mt-8 flex gap-4">
<select>
<For each={Object.entries(games)}>
{([gameId, game]) => <option value={gameId}>{gameId}</option>}
</For>
</select>
<button
onClick={() => setReady((prev) => !prev)}
class="button p-1 "
>
{ready() ? "Not Ready" : "Ready"}
</button>
</div>
<GamePicker />
</Show>
</div>
<Show when={view() != null}>
<Game />
</Show>
<Show when={results() != null}>
<span class="bg-[var(--light)] text-[var(--dark)] rounded-[24px] border-2 border-[var(--dark)] absolute center p-4 shadow-lg text-[4em] text-center">
{playerNames[results()!]} won!
</span>
</Show>
{/* The game being played */}
<Dynamic
component={
gameConfig()?.game ?? "" in GAMES
? GAMES[gameConfig()!.game as keyof typeof GAMES]
: undefined
}
/>
</TableContext.Provider>
);
};

View File

@@ -0,0 +1,5 @@
import simple from "./simple";
export default {
simple,
};

View File

@@ -0,0 +1,149 @@
import type {
SimpleAction,
SimplePlayerView,
} from "@games/shared/games/simple";
import { Accessor, createEffect, For, Show, useContext } from "solid-js";
import { Portal } from "solid-js/web";
import { me } from "~/profile";
import { createObservable, extractProperty } from "../../fn";
import FannedHand from "../FannedHand";
import Hand from "../Hand";
import Pile from "../Pile";
import { TableContext } from "../Table";
export default () => {
const table = useContext(TableContext)!;
const view = table.view as Accessor<SimplePlayerView>;
const Configuration = () => (
<Show when={view() == null}>
<Portal mount={table.tableRef}>
<div class="absolute center grid grid-cols-2 gap-col-2 text-xl">
<label for="allow discards" style={{ "text-align": "right" }}>
Allow discards
</label>
<input
type="checkbox"
id="allow discards"
style={{ width: "50px" }}
checked={table.gameConfig()?.["can discard"] ?? false}
onChange={(evt) =>
table.setGameConfig({
...table.gameConfig(),
"can discard": evt.target.checked,
})
}
/>
<label for="to win" style={{ "text-align": "right" }}>
Cards to win
</label>
<input
type="number"
id="to win"
style={{
"text-align": "center",
width: "50px",
color: "var(--yellow)",
}}
value={table.gameConfig()["cards to win"]}
onChange={(evt) =>
table.setGameConfig({
...table.gameConfig(),
"cards to win": Number.parseInt(evt.target.value),
})
}
/>
</div>
</Portal>
</Show>
);
const submitAction = (action: SimpleAction) => table.sendWs({ action });
const ActiveGame = () => (
<Show when={view() != null}>
{/* Main pile in the middle of the table */}
<Pile
count={view().deckCount}
scale={0.8}
class="cursor-pointer fixed center"
onClick={() => submitAction({ type: "draw" })}
/>
{/* Your own hand */}
<Hand
class="fixed bc"
hand={view().myHand}
onClickCard={(card) => submitAction({ type: "discard", card })}
/>
{/* Other players' hands */}
<For
each={Object.entries(view().playerHandCounts).filter(
([key, _]) => key in table.players
)}
>
{([playerKey, handCount], i) => (
<Portal
mount={table.players[playerKey].ref}
ref={(ref) => {
const midOffset =
i() + 0.5 - Object.values(view().playerHandCounts).length / 2;
ref.style = `position: absolute; display: flex; justify-content: center; top: 65%;`;
}}
>
<FannedHand handCount={handCount} />
</Portal>
)}
</For>
{/* Turn indicator */}
<div
class="absolute tc text-align-center"
style={{
"background-color":
view().playerTurn == me() ? "var(--yellow)" : "transparent",
color: view().playerTurn == me() ? "var(--dark)" : "var(--light)",
}}
>
It's{" "}
<span class="font-bold">
{view().playerTurn == me()
? "your"
: table.players[view().playerTurn].name + "'s"}
</span>{" "}
turn
</div>
{/* Quit button */}
<button
class="button fixed tl m-4 p-1"
onClick={() => {
table.sendWs({ quit: true });
}}
>
Quit
</button>
</Show>
);
const results = table.wsEvents
.thru(extractProperty("results"))
.thru(createObservable);
const Results = () => (
<Show when={results() != null}>
<span class="bg-[var(--light)] text-[var(--dark)] rounded-[24px] border-2 border-[var(--dark)] absolute center p-4 shadow-lg text-[4em] text-center">
{table.players[results()!].name} won!
</span>
</Show>
);
return (
<>
<Configuration />
<ActiveGame />
<Results />
</>
);
};

View File

@@ -1,3 +1,4 @@
import hash, { NotUndefined } from "object-hash";
import { JSX } from "solid-js";
export type Stylable = {
@@ -15,7 +16,8 @@ export type Clickable = {
| undefined;
};
export type Sizable = {
width?: string;
height?: string;
export type Scalable = {
scale?: number;
};
export const hashColor = (obj: NotUndefined) => `#${hash(obj).substring(0, 6)}`;

View File

@@ -1,6 +1,8 @@
import { Observable } from "kefir";
import { Accessor, createSignal } from "solid-js";
import { createLatest } from "@solid-primitives/memo";
import { Observable, Property, Stream } from "kefir";
import { Accessor, createEffect, createSignal } from "solid-js";
import { createStore } from "solid-js/store";
import type { ExtractPropertyType, UnionKeys } from "@games/shared/types";
declare global {
interface Array<T> {
@@ -39,11 +41,30 @@ export const createObservableWithInit = <T>(
export const cx = (...classes: string[]) => classes.join(" ");
export const createObservableStore = <T extends object = {}>(
obs: Observable<T, any>,
init: T
) => {
export const createObservableStore =
<T extends object = {}>(init: T) =>
(obs: Observable<T, any>) => {
const [store, setStore] = createStore<T>(init);
obs.onValue((val) => setStore(val));
return store;
};
export const extractProperty =
<T extends object, P extends UnionKeys<T>>(property: P) =>
(obs: Observable<T, any>): Property<ExtractPropertyType<T, P>, any> =>
obs
.filter((o) => property in o)
.map(
(o) => (o as { [K in P]: any })[property] as ExtractPropertyType<T, P>
)
.toProperty();
export const createSynced = <T>(p: {
ws: Stream<T, any>;
sendWs: (o: T) => void;
}) => {
const [local, setLocal] = createSignal<T>();
const remote = createObservable(p.ws.toProperty());
createEffect(() => local() !== undefined && p.sendWs(local()!));
return [createLatest([local, remote]), setLocal] as const;
};

View File

@@ -1,12 +1,10 @@
import { createEffect, createResource, createSignal, Resource } from "solid-js";
import { ApiType } from "./fn";
import api from "./api";
import hash from "object-hash";
import { makePersisted } from "@solid-primitives/storage";
import hash from "object-hash";
import { createResource, createSignal } from "solid-js";
import api from "./api";
export const mePromise = api.whoami.post().then((r) => r.data);
export const [me] = createResource(() => mePromise);
createEffect(() => console.log(me()));
export const playerColor = (humanKey: string) =>
"#" + hash(humanKey).substring(0, 6);

View File

@@ -3,30 +3,28 @@ import { A } from "@solidjs/router";
export default () => {
const randomTablePath = `/t/abcd`;
return (
<>
<div class="flex flex-col absolute center">
<h1>Welcome to games.drm.dev!</h1>
<p>
This website is a real-time multiplayer platform for playing
card games online.
This website is a real-time multiplayer platform for playing card
games online.
</p>
<br />
<p>
Games happen at <strong>tables</strong>. A table is any url of
the form{" "}
Games happen at <strong>tables</strong>. A table is any url of the
form{" "}
<span class="font-mono text-[var(--light-purple)]">
games.drm.dev/t/
<span class="text-[var(--yellow)]">*</span>
</span>
</p>
<br />
<p>
Go to the same one as your friend and you will find them there!
</p>
<p>Go to the same one as your friend and you will find them there!</p>
<br />
<p>
If you have a table key in mind (the part after /t/), then plug
it in to your URL bar! Or, here's a couple links to random
tables:
If you have a table key in mind (the part after /t/), then plug it in
to your URL bar! Or, here's a couple links to random tables:
</p>
<br />
<p>
@@ -36,5 +34,13 @@ export default () => {
</A>
</p>
</div>
<a href="https://brainmade.org" target="_blank">
<img
src="https://brainmade.org/white-logo.svg"
class="fixed bl m-2"
width="80"
/>
</a>
</>
);
};

View File

@@ -1,25 +1,12 @@
import { Game } from "@games/shared/games";
import { Human } from "@prisma/client";
import dayjs from "dayjs";
import { Elysia, t } from "elysia";
import { combine } from "kefir";
import Bus from "kefir-bus";
import { liveTable, WsIn, WsOut } from "./table";
import { Elysia } from "elysia";
import { generateTokenAndKey, resolveToken } from "./human";
import { err } from "./logging";
import { generateTokenAndKey, resolveToken, tokenExists } from "./human";
export const WS = Bus<
{
type: "open" | "message" | "error" | "close";
humanKey: string;
tableKey: string;
},
unknown
>();
import { liveTable, WsIn, WsOut } from "./table";
import type { ExtractPropertyType, UnionKeys } from "@games/shared/types";
const api = new Elysia({ prefix: "/api" })
.post("/whoami", async ({ cookie: { token } }) => {
console.log("WHOAMI");
let key: string | undefined;
if (token.value == null || (key = resolveToken(token.value)) == null) {
const [newToken, newKey] = generateTokenAndKey();
@@ -58,6 +45,7 @@ const api = new Elysia({ prefix: "/api" })
...table.outputs.global,
...(table.outputs.player[humanKey] ?? {}),
}).forEach(([type, stream]) =>
// @ts-ignore
stream.onValue((v) => send({ [type]: v }))
);
},

View File

@@ -16,7 +16,7 @@ new Elysia()
})
)
.onError(({ error }) => console.error(error))
// .onError(({ error }) => console.error(error))
.get("/ping", () => "pong")
.use(api)

View File

@@ -10,7 +10,7 @@ export const log = (value: unknown) => LogBus.emit(value);
export const err = (value: unknown) =>
LogBus.emitEvent({ type: "error", value });
LogStream.log();
LogStream.onError((err) => {
console.error(err);
});
// LogStream.log();
// LogStream.onError((err) => {
// console.error(err);
// });

View File

@@ -12,18 +12,26 @@ import { t } from "elysia";
import { combine, constant, merge, Observable, pool, Property } from "kefir";
import Bus, { type Bus as TBus } from "kefir-bus";
import { log } from "./logging";
import simple from "@games/shared/games/simple";
export const WsOut = t.Object({
playersPresent: t.Optional(t.Array(t.String())),
playerNames: t.Optional(t.Record(t.String(), t.String())),
playersReady: t.Optional(t.Nullable(t.Record(t.String(), t.Boolean()))),
gameConfig: t.Optional(t.Any()),
view: t.Optional(t.Any()),
results: t.Optional(t.Any()),
});
const DEFAULT_GAME_CONFIG = simple.defaultConfig;
export const WsOut = t.Union([
t.Object({ playersPresent: t.Array(t.String()) }),
t.Object({ playerNames: t.Record(t.String(), t.String()) }),
t.Object({ playersReady: t.Record(t.String(), t.Boolean()) }),
t.Object({
gameConfig: t.Object({ game: t.String(), players: t.Array(t.String()) }),
}),
t.Object({ view: t.Any() }),
t.Object({ results: t.Any() }),
]);
export type TWsOut = typeof WsOut.static;
export const WsIn = t.Union([
t.Object({ name: t.String() }),
t.Object({
gameConfig: t.Object({ game: t.String(), players: t.Array(t.String()) }),
}),
t.Object({ ready: t.Boolean() }),
t.Object({ action: t.Any() }),
t.Object({ quit: t.Literal(true) }),
@@ -136,8 +144,14 @@ export const liveTable = <
});
});
const { name, ready, action, quit } = partition(
["name", "ready", "action", "quit"],
const {
name,
ready,
action,
quit,
gameConfig: clientGameConfigs,
} = partition(
["name", "ready", "action", "quit", "gameConfig"],
messages
) as unknown as {
// yuck
@@ -145,6 +159,7 @@ export const liveTable = <
ready: Observable<Attributed & { ready: boolean }, any>;
action: Observable<Attributed & { action: GameAction }, any>;
quit: Observable<Attributed, any>;
gameConfig: Observable<Attributed & { gameConfig: GameConfig }, any>;
};
const gameEnds = quit.map((_) => null);
@@ -202,7 +217,7 @@ export const liveTable = <
const gameImpl = gameConfig
.filter((cfg) => cfg.game in GAMES)
.map((config) => GAMES[config.game as GameKey](config))
.map((config) => GAMES[config.game as GameKey].impl(config))
.toProperty();
const withGame = <T>(obs: Observable<T, any>) =>
@@ -226,7 +241,7 @@ export const liveTable = <
prev,
[{ action, humanKey }, game]: [
Attributed & { action: GameAction },
Game
ReturnType<Game["impl"]>
]
) =>
prev &&
@@ -258,18 +273,19 @@ export const liveTable = <
gameConfigPool.plug(
multiScan(
{
game: "simple",
players: [] as string[],
},
DEFAULT_GAME_CONFIG,
[
playersPresent.filterBy(gameIsActive.map((active) => !active)),
playersPresent.filterBy(gameIsActive.thru(invert)),
(prev, players) => ({
...prev,
players,
}),
],
[
clientGameConfigs.filterBy(gameIsActive.thru(invert)),
// @ts-ignore
(prev, { gameConfig }) => ({ ...gameConfig, players: prev.players }),
]
// TODO: Add player defined config changes
) as unknown as Observable<GameConfig, any>
);

View File

@@ -3,10 +3,15 @@ import simple from "./simple";
export type Game<
S = unknown, // state
A = unknown, // action
E extends { error: any } = { error: any }, // error
E = unknown, // error
V = unknown, // view
R = unknown // results
R = unknown, // results
C extends { game: string; players: string[] } = {
game: string;
players: string[];
}
> = {
impl: (config: C) => {
title: string;
rules: string;
init: () => S;
@@ -14,10 +19,12 @@ export type Game<
getView: (p: { state: S; humanKey: string }) => V;
resolveQuit: (p: { state: S; humanKey: string }) => S;
getResult: (state: S) => R | undefined;
};
defaultConfig: C;
};
export const GAMES: {
[key: string]: (config: { game: string; players: string[] }) => Game;
[key: string]: Game;
} = {
// renaissance,
simple,

View File

@@ -1,10 +1,13 @@
import { Card, Hand, newDeck, Pile, shuffle, vCard } from "@games/shared/cards";
import { heq } from "@games/shared/utils";
import type { Game } from ".";
import { XOR } from "ts-xor";
export type SimpleConfiguration = {
game: "simple";
players: string[];
"can discard": boolean;
"cards to win": number;
};
// omniscient game state
@@ -50,6 +53,16 @@ export const getSimplePlayerView = (
),
});
// type SimpleError = XOR<
// { "go away": string },
// { chill: string },
// { "ah ah": string }
// >;
type SimpleError = {
class: "go away" | "chill" | "ah ah";
message: string;
};
export const resolveSimpleAction = ({
config,
state,
@@ -62,13 +75,18 @@ export const resolveSimpleAction = ({
humanKey: string;
}): SimpleGameState => {
const playerHand = state.playerHands[humanKey];
if (playerHand == null) {
throw new Error(
`${humanKey} is not a player in this game; they cannot perform actions`
);
throw {
message: "You are not a part of this game!",
class: "go away",
} satisfies SimpleError;
}
if (humanKey != config.players[state.turnIdx]) {
throw new Error(`It's not ${humanKey}'s turn!`);
throw {
message: "It's not your turn!",
class: "chill",
} satisfies SimpleError;
}
const numPlayers = Object.keys(state.playerHands).length;
@@ -87,6 +105,13 @@ export const resolveSimpleAction = ({
};
} else {
// action.type == discard
if (config["can discard"] == false) {
throw {
message: "You're not allowed to discard!",
class: "ah ah",
} satisfies SimpleError;
}
const cardIndex = playerHand.findIndex(heq(action.card));
return {
deck: [action.card, ...state.deck],
@@ -103,10 +128,14 @@ export const resolveSimpleAction = ({
export type SimpleResult = string;
type SimpleError = { error: "whoops!" };
export default (config: SimpleConfiguration) =>
({
export default {
defaultConfig: {
game: "simple",
players: [],
"can discard": true,
"cards to win": 5,
},
impl: (config: SimpleConfiguration) => ({
title: "Simple",
rules: "You can draw, or you can discard. Then your turn is up.",
init: () => newSimpleGameState(config),
@@ -116,12 +145,14 @@ export default (config: SimpleConfiguration) =>
resolveQuit: () => null,
getResult: (state) =>
Object.entries(state.playerHands).find(
([_, hand]) => hand.length === 2
([_, hand]) => hand.length === config["cards to win"]
)?.[0],
} satisfies Game<
}),
} satisfies Game<
SimpleGameState,
SimpleAction,
SimpleError,
SimplePlayerView,
SimpleResult
>);
SimpleResult,
SimpleConfiguration
>;

9
pkg/shared/types.ts Normal file
View File

@@ -0,0 +1,9 @@
export type UnionKeys<T> = T extends any ? keyof T : never;
export type ExtractPropertyType<
T,
P extends string | number | symbol
> = T extends {
[K in P]: any;
}
? T[P]
: never;

22
pnpm-lock.yaml generated
View File

@@ -20,6 +20,9 @@ importers:
'@elysiajs/eden':
specifier: ^1.3.2
version: 1.3.3(elysia@1.3.20(exact-mirror@0.2.0(@sinclair/typebox@0.34.41))(file-type@21.0.0)(typescript@5.9.2))
'@solid-primitives/memo':
specifier: ^1.4.3
version: 1.4.3(solid-js@1.9.9)
'@solid-primitives/scheduled':
specifier: ^1.5.2
version: 1.5.2(solid-js@1.9.9)
@@ -29,6 +32,9 @@ importers:
'@solidjs/router':
specifier: ^0.15.3
version: 0.15.3(solid-js@1.9.9)
color2k:
specifier: ^2.0.3
version: 2.0.3
js-cookie:
specifier: ^3.0.5
version: 3.0.5
@@ -590,6 +596,11 @@ packages:
resolution: {integrity: sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ==}
engines: {node: '>=18'}
'@solid-primitives/memo@1.4.3':
resolution: {integrity: sha512-CA+n9yaoqbYm+My5tY2RWb6EE16tVyehM4GzwQF4vCwvjYPAYk1JSRIVuMC0Xuj5ExD2XQJE5E2yAaKY2HTUsg==}
peerDependencies:
solid-js: ^1.6.12
'@solid-primitives/scheduled@1.5.2':
resolution: {integrity: sha512-/j2igE0xyNaHhj6kMfcUQn5rAVSTLbAX+CDEBm25hSNBmNiHLu2lM7Usj2kJJ5j36D67bE8wR1hBNA8hjtvsQA==}
peerDependencies:
@@ -927,6 +938,9 @@ packages:
color-name@1.1.4:
resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}
color2k@2.0.3:
resolution: {integrity: sha512-zW190nQTIoXcGCaU08DvVNFTmQhUpnJfVuAKfWqUQkflXKpaDdpaYoM0iluLS9lgJNHyBF58KKA2FBEwkD7wog==}
colorette@2.0.20:
resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}
@@ -2827,6 +2841,12 @@ snapshots:
'@sindresorhus/merge-streams@4.0.0': {}
'@solid-primitives/memo@1.4.3(solid-js@1.9.9)':
dependencies:
'@solid-primitives/scheduled': 1.5.2(solid-js@1.9.9)
'@solid-primitives/utils': 6.3.2(solid-js@1.9.9)
solid-js: 1.9.9
'@solid-primitives/scheduled@1.5.2(solid-js@1.9.9)':
dependencies:
solid-js: 1.9.9
@@ -3238,6 +3258,8 @@ snapshots:
color-name@1.1.4: {}
color2k@2.0.3: {}
colorette@2.0.20: {}
compare-func@2.0.0: