Initial commit.

This commit is contained in:
Greyson Parrelli
2026-07-22 23:07:29 -04:00
commit 612a4e6227
38 changed files with 6106 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
import { useState } from 'react'
import { clearSession, loadSession, saveSession } from './api'
import type { Session } from './types'
import { Home } from './components/Home'
import { Table } from './components/Table'
export function App() {
const [session, setSession] = useState<Session | null>(loadSession)
if (!session) {
return (
<Home
onSession={(s) => {
saveSession(s)
setSession(s)
}}
/>
)
}
return (
<Table
session={session}
onLeave={() => {
clearSession()
setSession(null)
}}
/>
)
}
+39
View File
@@ -0,0 +1,39 @@
import type { Session } from './types'
const SESSION_KEY = 'sapbg-session'
async function post(path: string, body: unknown): Promise<Session> {
const res = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const data = await res.json()
if (!res.ok) throw new Error(data.error ?? 'request failed')
return data as Session
}
export function createGame(name: string): Promise<Session> {
return post('/api/games', { name })
}
export function joinGame(code: string, name: string): Promise<Session> {
return post('/api/join', { code, name })
}
export function loadSession(): Session | null {
try {
const raw = localStorage.getItem(SESSION_KEY)
return raw ? (JSON.parse(raw) as Session) : null
} catch {
return null
}
}
export function saveSession(s: Session) {
localStorage.setItem(SESSION_KEY, JSON.stringify(s))
}
export function clearSession() {
localStorage.removeItem(SESSION_KEY)
}
+135
View File
@@ -0,0 +1,135 @@
import { useEffect, useRef, useState } from 'react'
import type { Card, ClientMessage, GameView, PlayerView } from '../types'
import { CardView } from './CardView'
interface Props {
view: GameView
you: PlayerView
send: (msg: ClientMessage) => void
}
// ArrangePhase lets the player order their deck for battle. Leftmost card
// fights first; food cards buff the next pet to their right... i.e. foods
// apply "down" to the next pet later in the order. Drag cards or use the
// arrow buttons to reorder, then lock in.
export function ArrangePhase({ view, you, send }: Props) {
const [order, setOrder] = useState<Card[]>(you.deck ?? [])
const dragIndex = useRef<number | null>(null)
const locked = you.ready
// If the server-side deck changes (shouldn't during arrange, but be safe),
// resync.
useEffect(() => {
setOrder(you.deck ?? [])
}, [you.deck])
function move(from: number, to: number) {
if (to < 0 || to >= order.length) return
setOrder((o) => {
const next = [...o]
const [c] = next.splice(from, 1)
next.splice(to, 0, c)
return next
})
}
// Which pets do the foods land on? Compute buff per card for preview.
const bonuses = new Map<string, number>()
{
let pendingApples = 0
for (const c of order) {
if (c.kind === 'food') {
if (c.food === 'apple') pendingApples++
} else {
bonuses.set(c.id, pendingApples)
pendingApples = 0
}
}
}
const trailingFoods = (() => {
let n = 0
for (let i = order.length - 1; i >= 0 && order[i].kind === 'food'; i--) n++
return n
})()
const opponent = view.players.find((p) => p.seat !== view.youSeat)
if (locked) {
return (
<div className="centered">
<h2>Order locked in </h2>
<p className="muted">
Waiting for {opponent?.name ?? 'your opponent'} to arrange their deck
</p>
</div>
)
}
return (
<div className="arrange">
<div className="shop-status">
<span className="status-hot">Arrange your battle line</span>
</div>
<p className="hint">
The <strong>leftmost</strong> card fights first. Food cards power up the
next pet to their <strong>right</strong>.
{trailingFoods > 0 && (
<span className="warn-text">
{' '}
{trailingFoods} food card{trailingFoods > 1 ? 's' : ''} at the end
will be wasted!
</span>
)}
</p>
<div className="arrange-row">
<div className="arrange-marker"> first</div>
{order.map((c, i) => (
<div
key={c.id}
className="arrange-card"
draggable
onDragStart={() => (dragIndex.current = i)}
onDragOver={(e) => {
e.preventDefault()
if (dragIndex.current !== null && dragIndex.current !== i) {
move(dragIndex.current, i)
dragIndex.current = i
}
}}
onDragEnd={() => (dragIndex.current = null)}
>
<CardView card={c} bonus={bonuses.get(c.id) ?? 0} />
<div className="arrange-arrows">
<button
className="btn btn-ghost btn-sm"
disabled={i === 0}
onClick={() => move(i, i - 1)}
aria-label="move earlier"
>
</button>
<button
className="btn btn-ghost btn-sm"
disabled={i === order.length - 1}
onClick={() => move(i, i + 1)}
aria-label="move later"
>
</button>
</div>
</div>
))}
</div>
<div className="actions">
<button
className="btn btn-primary btn-big"
onClick={() => send({ type: 'arrange', order: order.map((c) => c.id) })}
>
Lock in & battle
</button>
</div>
</div>
)
}
+191
View File
@@ -0,0 +1,191 @@
import { useEffect, useMemo, useState } from 'react'
import type { BattleEvent, BattleUnit, ClientMessage, GameView } from '../types'
import { CardView } from './CardView'
interface Props {
view: GameView
send: (msg: ClientMessage) => void
}
const STEP_MS = 1400
interface UnitState {
unit: BattleUnit
index: number
damage: number
dead: boolean // died in an earlier step (gone)
dying: boolean // died in the step just played (animate out)
}
// applyEvents replays the first `step` events onto a seat's lineup.
function applyEvents(view: GameView, seat: number, step: number): UnitState[] {
const battle = view.battle!
const events = battle.events ?? []
const states: UnitState[] = (battle.lineups[seat] ?? []).map((u, i) => ({
unit: u,
index: i,
damage: 0,
dead: false,
dying: false,
}))
const seatPos = seat === 0 ? 0 : 1
for (let k = 0; k < step && k < events.length; k++) {
const ev = events[k]
const s = states[ev.units[seatPos]]
if (!s) continue
s.damage = ev.damage[seatPos]
if (ev.died[seatPos]) {
s.dying = k === step - 1
s.dead = k < step - 1
}
}
return states
}
// BattlePhase plays back the battle log: front pets clash, damage numbers
// fly, the fallen fade out, then the round result lands.
export function BattlePhase({ view, send }: Props) {
const battle = view.battle!
const events = battle.events ?? []
const [step, setStep] = useState(0)
const [acked, setAcked] = useState(false)
const done = step >= events.length
useEffect(() => {
if (done) return
const t = window.setTimeout(() => setStep((s) => s + 1), STEP_MS)
return () => window.clearTimeout(t)
}, [step, done])
const youSeat = view.youSeat
const oppSeat = view.players.find((p) => p.seat !== youSeat)?.seat ?? 1
const yourLine = useMemo(
() => applyEvents(view, youSeat, step),
[view, youSeat, step],
)
const oppLine = useMemo(
() => applyEvents(view, oppSeat, step),
[view, oppSeat, step],
)
const lastEvent = step > 0 ? events[step - 1] : null
function renderSide(line: UnitState[], side: 'left' | 'right', seat: number) {
const seatPos = seat === 0 ? 0 : 1
const frontIdx = line.find((s) => !s.dead && !s.dying)?.index
return (
<div className={`battle-side battle-side-${side}`}>
{line
.filter((s) => !s.dead)
.map((s) => {
const isFront = s.index === frontIdx
const clashing =
!done && lastEvent !== null && lastEvent.units[seatPos] === s.index
return (
<div
key={`${s.unit.card.id}-${clashing ? step : 'idle'}`}
className={[
'battle-unit',
clashing ? `clash-${side}` : '',
s.dying ? 'unit-dying' : '',
isFront && !s.dying ? 'is-front' : '',
]
.filter(Boolean)
.join(' ')}
>
<CardView
card={s.unit.card}
bonus={s.unit.bonus}
damage={s.damage}
dead={s.dying}
/>
{clashing && (
<div className="damage-pop">
{lastEvent!.damage[seatPos] -
prevDamage(events, step - 1, seatPos, s.index)}
</div>
)}
</div>
)
})}
</div>
)
}
const you = view.players[youSeat]
const opp = view.players[oppSeat]
const won = battle.winnerSeat === youSeat
const draw = battle.winnerSeat < 0
return (
<div className="battle">
<div className="battle-header">
<h2>Battle! Round {battle.round}</h2>
{!done && (
<button className="btn btn-ghost btn-sm" onClick={() => setStep(events.length)}>
Skip
</button>
)}
</div>
<div className="battle-names">
<span>{you?.name} (you)</span>
<span className="battle-vs">VS</span>
<span>{opp?.name}</span>
</div>
<div className="battlefield">
{renderSide(yourLine, 'left', youSeat)}
<div className="battle-center" aria-hidden>
</div>
{renderSide(oppLine, 'right', oppSeat)}
</div>
{done && (
<div className={`battle-result ${draw ? 'is-draw' : won ? 'is-win' : 'is-loss'}`}>
<div className="battle-result-title">
{draw ? 'Draw!' : won ? 'Victory!' : 'Defeat…'}
</div>
{!draw && (
<div className="battle-result-sub">
{view.players[battle.winnerSeat]?.name} wins{' '}
{'🏆'.repeat(battle.trophies)}
</div>
)}
{draw && <div className="battle-result-sub">No trophies awarded</div>}
{acked ? (
<p className="muted">Waiting for opponent</p>
) : (
<button
className="btn btn-primary btn-big"
onClick={() => {
setAcked(true)
send({ type: 'ready' })
}}
>
{battle.round >= view.maxRounds ? 'See final results' : 'Next round →'}
</button>
)}
</div>
)}
</div>
)
}
// prevDamage finds the damage a unit had before the given event, so the
// floating number shows just this clash's hit.
function prevDamage(
events: BattleEvent[],
upto: number,
seatPos: number,
unitIndex: number,
): number {
let dmg = 0
for (let k = 0; k < upto; k++) {
const ev = events[k]
if (ev.units[seatPos] === unitIndex) dmg = ev.damage[seatPos]
}
return dmg
}
+70
View File
@@ -0,0 +1,70 @@
import type { Card } from '../types'
import { artFor, SUIT_EMOJI } from '../petArt'
interface Props {
card: Card
size?: 'sm' | 'md' | 'lg'
selected?: boolean
disabled?: boolean
onClick?: () => void
// Battle decorations
bonus?: number
damage?: number
dead?: boolean
}
// CardView renders one physical card: pets get a power badge and suit stamp,
// foods a description line. Battle mode layers on buffs and damage markers.
export function CardView({
card,
size = 'md',
selected,
disabled,
onClick,
bonus = 0,
damage = 0,
dead,
}: Props) {
const power = (card.power ?? 0) + bonus
const classes = [
'card',
`card-${size}`,
card.kind === 'food' ? 'card-food' : 'card-pet',
selected ? 'is-selected' : '',
disabled ? 'is-disabled' : '',
dead ? 'is-dead' : '',
onClick && !disabled ? 'is-clickable' : '',
]
.filter(Boolean)
.join(' ')
return (
<div
className={classes}
onClick={disabled ? undefined : onClick}
role={onClick ? 'button' : undefined}
>
<div className="card-top">
<span className="card-tier">T{card.tier || ''}</span>
{card.suit && (
<span className="card-suit" title={`Suit: ${card.suit}`}>
{SUIT_EMOJI[card.suit]}
</span>
)}
</div>
<div className="card-art" aria-hidden>
{artFor(card.name)}
</div>
<div className="card-name">{card.name}</div>
{card.kind === 'pet' ? (
<div className="card-bottom">
<span className={`card-power ${bonus > 0 ? 'is-buffed' : ''}`}>{power}</span>
{damage > 0 && !dead && <span className="card-damage">{damage}</span>}
</div>
) : (
<div className="card-food-text">+1 power</div>
)}
{selected && <div className="card-check"></div>}
</div>
)
}
+35
View File
@@ -0,0 +1,35 @@
import type { GameView } from '../types'
export function GameOver({ view, onLeave }: { view: GameView; onLeave: () => void }) {
const winner = view.winnerSeat >= 0 ? view.players[view.winnerSeat] : null
const youWon = view.winnerSeat === view.youSeat
return (
<div className="gameover">
<div className="gameover-emoji" aria-hidden>
{winner ? (youWon ? '🎉' : '💀') : '🤝'}
</div>
<h1 className="gameover-title">
{winner ? (youWon ? 'You win!' : `${winner.name} wins!`) : "It's a tie!"}
</h1>
<div className="gameover-scores">
{[...view.players]
.sort((a, b) => b.trophies - a.trophies)
.map((p) => (
<div key={p.id} className={`score-line ${p.seat === view.youSeat ? 'is-you' : ''}`}>
<span className="score-name">
{p.name}
{p.seat === view.youSeat ? ' (you)' : ''}
</span>
<span className="score-trophies">
{'🏆'.repeat(p.trophies) || '—'} <strong>{p.trophies}</strong>
</span>
</div>
))}
</div>
<button className="btn btn-primary btn-big" onClick={onLeave}>
Back to the den
</button>
</div>
)
}
+78
View File
@@ -0,0 +1,78 @@
import { useState } from 'react'
import { createGame, joinGame } from '../api'
import type { Session } from '../types'
// Home is the create/join screen shown when there's no active session.
export function Home({ onSession }: { onSession: (s: Session) => void }) {
const [name, setName] = useState('')
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function run(fn: () => Promise<Session>) {
setBusy(true)
setError(null)
try {
onSession(await fn())
} catch (e) {
setError(e instanceof Error ? e.message : 'something went wrong')
} finally {
setBusy(false)
}
}
return (
<div className="home">
<div className="home-pets" aria-hidden>
🐷🦔🐶🦩🐉
</div>
<h1 className="home-title">
Super Auto Pets
<span className="home-subtitle">The Board Game</span>
</h1>
<div className="home-card">
<label className="field">
<span>Your name</span>
<input
value={name}
maxLength={20}
placeholder="e.g. Greyson"
onChange={(e) => setName(e.target.value)}
/>
</label>
<button
className="btn btn-primary btn-big"
disabled={busy}
onClick={() => run(() => createGame(name))}
>
Host a new game
</button>
<div className="home-divider">
<span>or join a friend</span>
</div>
<div className="home-join">
<input
className="code-input"
value={code}
maxLength={5}
placeholder="CODE"
onChange={(e) => setCode(e.target.value.toUpperCase())}
/>
<button
className="btn btn-secondary"
disabled={busy || code.length < 5}
onClick={() => run(() => joinGame(code, name))}
>
Join
</button>
</div>
{error && <div className="home-error">{error}</div>}
</div>
</div>
)
}
+20
View File
@@ -0,0 +1,20 @@
import type { GameView } from '../types'
export function Lobby({ view }: { view: GameView }) {
return (
<div className="lobby">
<div className="lobby-bounce" aria-hidden>
🐟
</div>
<h2>Waiting for an opponent</h2>
<p className="muted">Share this code so a friend can join:</p>
<div className="lobby-code">{view.code}</div>
<button
className="btn btn-secondary"
onClick={() => navigator.clipboard?.writeText(view.code)}
>
Copy code
</button>
</div>
)
}
+194
View File
@@ -0,0 +1,194 @@
import { useEffect, useState } from 'react'
import type { Card, ClientMessage, GameView, PlayerView } from '../types'
import { CardView } from './CardView'
import { SUIT_EMOJI } from '../petArt'
interface Props {
view: GameView
you: PlayerView
send: (msg: ClientMessage) => void
}
export function ShopPhase({ view, you, send }: Props) {
const [selected, setSelected] = useState<string[]>([])
const cleanup = view.phase === 'cleanup'
const myTurn = !cleanup && view.turn === view.youSeat && you.coins > 0
const deck = you.deck ?? []
const opponent = view.players.find((p) => p.seat !== view.youSeat)
const pending = view.pending
const myPending = pending?.playerId === you.id
// Drop selections that no longer exist (bought/traded/discarded cards).
useEffect(() => {
setSelected((sel) => sel.filter((id) => deck.some((c) => c.id === id)))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [you.deck])
function toggle(id: string) {
setSelected((sel) =>
sel.includes(id) ? sel.filter((s) => s !== id) : [...sel, id],
)
}
const selectedCards = selected
.map((id) => deck.find((c) => c.id === id))
.filter((c): c is Card => !!c)
const sameSuit =
selectedCards.length === 3 &&
selectedCards.every((c) => c.suit && c.suit === selectedCards[0].suit)
const excessPets = you.petCount - view.maxPets
const cleanupReady =
cleanup &&
excessPets > 0 &&
selectedCards.length === excessPets &&
selectedCards.every((c) => c.kind === 'pet')
function act(msg: ClientMessage) {
send(msg)
setSelected([])
}
return (
<div className="shop">
{/* Status line */}
<div className="shop-status">
{cleanup ? (
excessPets > 0 ? (
<span className="status-hot">
Too many pets! Discard <strong>{excessPets}</strong> they become
apples 🍎
</span>
) : (
<span className="muted">
Waiting for {opponent?.name ?? 'opponent'} to discard down to{' '}
{view.maxPets} pets
</span>
)
) : pending && !myPending ? (
<span className="muted">
{opponent?.name ?? 'Opponent'} is trading up a tier
</span>
) : myTurn ? (
<span className="status-hot">Your turn spend a coin 🪙</span>
) : (
<span className="muted">
{view.players[view.turn]?.name ?? 'Opponent'}s turn
</span>
)}
</div>
{/* Shop row */}
{!cleanup && (
<section className="shop-row-wrap">
<div className="section-label">
Shop · Tier {view.round}
<span className="muted"> · {view.deckCounts[view.round - 1]} left in deck</span>
</div>
<div className="shop-row">
{view.shopRow.map((c, i) =>
c.id ? (
<CardView
key={c.id}
card={c}
size="lg"
disabled={!myTurn}
onClick={myTurn ? () => act({ type: 'buy', row: i }) : undefined}
/>
) : (
<div key={`empty-${i}`} className="card-slot-empty" />
),
)}
</div>
{myTurn && <div className="hint">Tap a card to buy it for 1 🪙</div>}
</section>
)}
{/* Your deck */}
<section className="deck-wrap">
<div className="section-label">
Your deck
<span className="muted">
{' '}
· {you.petCount}/{view.maxPets} pets
</span>
</div>
{deck.length === 0 ? (
<div className="muted deck-empty">No cards yet buy something!</div>
) : (
<div className="deck-row">
{deck.map((c) => (
<CardView
key={c.id}
card={c}
selected={selected.includes(c.id)}
onClick={() => toggle(c.id)}
/>
))}
</div>
)}
</section>
{/* Actions */}
<div className="actions">
{cleanup ? (
excessPets > 0 && (
<button
className="btn btn-primary"
disabled={!cleanupReady}
onClick={() => act({ type: 'discard', cards: selected })}
>
Discard {excessPets} pet{excessPets > 1 ? 's' : ''} 🍎
</button>
)
) : (
<>
<button
className="btn btn-secondary"
disabled={!myTurn || selected.length === 0}
onClick={() => act({ type: 'discard', cards: selected })}
title="Convert selected cards into apples (+1 power each)"
>
Discard {selected.length > 0 ? selected.length : ''} 🍎 (1 🪙)
</button>
<button
className="btn btn-secondary"
disabled={!myTurn || !sameSuit || view.round >= view.maxRounds}
onClick={() => act({ type: 'trade', cards: selected })}
title="Trade 3 same-suit pets for a pick from the next tier"
>
Trade 3 {sameSuit && selectedCards[0].suit ? SUIT_EMOJI[selectedCards[0].suit] : 'matching'} Tier{' '}
{Math.min(view.round + 1, view.maxRounds)} (1 🪙)
</button>
<button
className="btn btn-ghost"
disabled={!myTurn}
onClick={() => act({ type: 'pass' })}
title="Give up your remaining coins"
>
Pass
</button>
</>
)}
</div>
{/* Trade picker */}
{myPending && pending && (
<div className="modal-backdrop">
<div className="modal">
<h3>Pick one the other goes under the tier {pending.tier} deck</h3>
<div className="modal-cards">
{pending.options.map((c, i) => (
<CardView
key={c.id}
card={c}
size="lg"
onClick={() => send({ type: 'tradeChoose', pick: i })}
/>
))}
</div>
</div>
</div>
)}
</div>
)
}
+74
View File
@@ -0,0 +1,74 @@
import { useGame } from '../useGame'
import type { Session } from '../types'
import { Lobby } from './Lobby'
import { ShopPhase } from './ShopPhase'
import { ArrangePhase } from './ArrangePhase'
import { BattlePhase } from './BattlePhase'
import { GameOver } from './GameOver'
// Table connects to the game and routes to the right phase screen.
export function Table({ session, onLeave }: { session: Session; onLeave: () => void }) {
const { view, error, connected, send } = useGame(session)
if (!view) {
return (
<div className="centered muted">
{connected ? 'Loading game…' : 'Connecting…'}
</div>
)
}
const you = view.players[view.youSeat]
const opponents = view.players.filter((p) => p.seat !== view.youSeat)
return (
<div className="table">
<header className="topbar">
<div className="topbar-brand" title="Super Auto Pets: The Board Game">
🐾 <span>SAP</span>
</div>
{view.phase !== 'gameover' && (
<div className="topbar-round">
Round <strong>{view.round}</strong> / {view.maxRounds}
</div>
)}
<div className="topbar-players">
{view.players.map((p) => (
<div
key={p.id}
className={`topbar-player ${p.seat === view.youSeat ? 'is-you' : ''}`}
>
<span className={`conn-dot ${p.connected ? 'on' : 'off'}`} />
<span className="topbar-name">{p.name}</span>
<span className="chip">🏆 {p.trophies}</span>
{(view.phase === 'shop' || view.phase === 'cleanup') && (
<span className="chip">🪙 {p.coins}</span>
)}
</div>
))}
</div>
<div className="topbar-code" title="Share this code with your opponent">
{view.code}
</div>
<button className="btn btn-ghost btn-sm" onClick={onLeave}>
Leave
</button>
</header>
<main className="table-main">
{view.phase === 'lobby' && <Lobby view={view} />}
{(view.phase === 'shop' || view.phase === 'cleanup') && (
<ShopPhase view={view} you={you} send={send} />
)}
{view.phase === 'arrange' && <ArrangePhase view={view} you={you} send={send} />}
{view.phase === 'battle' && <BattlePhase view={view} send={send} />}
{view.phase === 'gameover' && <GameOver view={view} onLeave={onLeave} />}
</main>
{opponents.some((p) => !p.connected) && view.phase !== 'lobby' && (
<div className="banner banner-warn">An opponent is disconnected</div>
)}
{error && <div className="toast">{error}</div>}
</div>
)
}
+14
View File
@@ -0,0 +1,14 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import '@fontsource/lilita-one'
import '@fontsource/nunito/400.css'
import '@fontsource/nunito/700.css'
import '@fontsource/nunito/900.css'
import './styles.css'
import { App } from './App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+35
View File
@@ -0,0 +1,35 @@
import type { Suit } from './types'
const PET_EMOJI: Record<string, string> = {
// Tier 1
Ant: '🐜', Cricket: '🦗', Fish: '🐟', Horse: '🐴',
Beaver: '🦫', Otter: '🦦', Pig: '🐷', Mosquito: '🦟',
// Tier 2
Crab: '🦀', Swan: '🦢', Hedgehog: '🦔', Peacock: '🦚',
Flamingo: '🦩', Rat: '🐀', Shrimp: '🦐', Spider: '🕷️',
// Tier 3
Dog: '🐶', Badger: '🦡', Camel: '🐫', Giraffe: '🦒',
Kangaroo: '🦘', Ox: '🐂', Rabbit: '🐰', Sheep: '🐑',
// Tier 4
Skunk: '🦨', Hippo: '🦛', Bison: '🦬', Deer: '🦌',
Squirrel: '🐿️', Whale: '🐳', Worm: '🪱', Penguin: '🐧',
// Tier 5
Scorpion: '🦂', Rhino: '🦏', Monkey: '🐒', Cow: '🐄',
Seal: '🦭', Shark: '🦈', Turkey: '🦃', Crocodile: '🐊',
// Tier 6
Leopard: '🐆', Boar: '🐗', Fly: '🪰', Gorilla: '🦍',
Mammoth: '🦣', Snake: '🐍', Tiger: '🐯', Dragon: '🐉',
// Foods
Apple: '🍎',
}
export function artFor(name: string): string {
return PET_EMOJI[name] ?? '🐾'
}
export const SUIT_EMOJI: Record<Suit, string> = {
sun: '☀️',
moon: '🌙',
star: '⭐',
leaf: '🍃',
}
+957
View File
@@ -0,0 +1,957 @@
/* ============================================================
Super Auto Pets: The Board Game — cozy tabletop theme.
Deep felt table, cream cards with cocoa borders, chunky type.
============================================================ */
:root {
--felt-900: #12351f;
--felt-800: #1a4a2b;
--felt-700: #226038;
--wood: #5b3a1e;
--wood-light: #7a5230;
--cream: #fdf3dc;
--cream-dark: #f3e3bd;
--cocoa: #4a2c14;
--ink: #33230f;
--coral: #ff8a3d;
--coral-dark: #e06a1b;
--gold: #ffcf5c;
--red: #d94a38;
--teal: #2f9c8a;
--font-display: 'Lilita One', system-ui, sans-serif;
--font-body: 'Nunito', system-ui, sans-serif;
--card-radius: 12px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body,
#root {
min-height: 100vh;
}
body {
font-family: var(--font-body);
color: var(--cream);
background-color: var(--felt-900);
background-image:
radial-gradient(ellipse at 50% -20%, rgba(255, 255, 255, 0.09), transparent 60%),
radial-gradient(ellipse at 50% 120%, rgba(0, 0, 0, 0.45), transparent 60%),
url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='160' height='160' filter='url(%23n)' opacity='0.05'/%3E%3C/svg%3E"),
linear-gradient(160deg, var(--felt-800), var(--felt-900) 70%);
}
h1,
h2,
h3 {
font-family: var(--font-display);
font-weight: 400;
letter-spacing: 0.02em;
}
.muted {
color: rgba(253, 243, 220, 0.55);
}
.centered {
min-height: 60vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
text-align: center;
}
.hint {
font-size: 0.9rem;
color: rgba(253, 243, 220, 0.65);
text-align: center;
}
.warn-text {
color: var(--gold);
font-weight: 700;
}
/* ---------- buttons ---------- */
.btn {
font-family: var(--font-display);
font-size: 1rem;
letter-spacing: 0.03em;
color: var(--cream);
background: var(--wood);
border: 3px solid rgba(0, 0, 0, 0.25);
border-radius: 12px;
padding: 10px 18px;
cursor: pointer;
box-shadow: 0 4px 0 rgba(0, 0, 0, 0.35);
transition: transform 80ms ease, box-shadow 80ms ease, filter 120ms ease;
}
.btn:hover:not(:disabled) {
filter: brightness(1.1);
}
.btn:active:not(:disabled) {
transform: translateY(3px);
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.35);
}
.btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.btn-primary {
background: linear-gradient(180deg, var(--coral), var(--coral-dark));
color: #fff;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.btn-secondary {
background: linear-gradient(180deg, var(--teal), #227465);
}
.btn-ghost {
background: transparent;
border-color: rgba(253, 243, 220, 0.3);
box-shadow: none;
}
.btn-big {
font-size: 1.25rem;
padding: 14px 28px;
}
.btn-sm {
font-size: 0.8rem;
padding: 4px 10px;
border-width: 2px;
}
/* ---------- home ---------- */
.home {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 20px;
padding: 24px;
}
.home-pets {
font-size: 2.6rem;
letter-spacing: 0.3em;
animation: float 3s ease-in-out infinite;
}
@keyframes float {
0%,
100% {
transform: translateY(0);
}
50% {
transform: translateY(-8px);
}
}
.home-title {
font-size: clamp(2.2rem, 6vw, 3.6rem);
text-align: center;
color: var(--gold);
text-shadow: 0 4px 0 rgba(0, 0, 0, 0.35);
display: flex;
flex-direction: column;
line-height: 1.05;
}
.home-subtitle {
font-size: 0.42em;
color: var(--cream);
letter-spacing: 0.25em;
text-transform: uppercase;
}
.home-card {
background: rgba(0, 0, 0, 0.25);
border: 2px solid rgba(253, 243, 220, 0.15);
border-radius: 20px;
padding: 28px;
display: flex;
flex-direction: column;
gap: 16px;
width: min(380px, 92vw);
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
font-weight: 700;
font-size: 0.9rem;
}
.field input,
.code-input {
font-family: var(--font-body);
font-size: 1.1rem;
font-weight: 700;
color: var(--ink);
background: var(--cream);
border: 3px solid var(--cocoa);
border-radius: 10px;
padding: 10px 12px;
outline: none;
width: 100%;
}
.code-input {
font-family: var(--font-display);
letter-spacing: 0.35em;
text-transform: uppercase;
text-align: center;
}
.home-divider {
text-align: center;
font-size: 0.85rem;
color: rgba(253, 243, 220, 0.5);
display: flex;
align-items: center;
gap: 10px;
}
.home-divider::before,
.home-divider::after {
content: '';
flex: 1;
height: 1px;
background: rgba(253, 243, 220, 0.2);
}
.home-join {
display: flex;
gap: 10px;
}
.home-error {
color: #ffb3a7;
font-weight: 700;
text-align: center;
}
/* ---------- topbar ---------- */
.table {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.topbar {
display: flex;
align-items: center;
gap: 16px;
padding: 10px 16px;
background: linear-gradient(180deg, var(--wood-light), var(--wood));
border-bottom: 4px solid rgba(0, 0, 0, 0.35);
flex-wrap: wrap;
}
.topbar-brand {
font-family: var(--font-display);
font-size: 1.2rem;
color: var(--gold);
}
.topbar-round {
font-size: 0.95rem;
}
.topbar-players {
display: flex;
gap: 14px;
flex: 1;
flex-wrap: wrap;
}
.topbar-player {
display: flex;
align-items: center;
gap: 6px;
background: rgba(0, 0, 0, 0.2);
border-radius: 999px;
padding: 4px 12px;
font-size: 0.9rem;
}
.topbar-player.is-you {
outline: 2px solid var(--gold);
}
.topbar-name {
font-weight: 900;
}
.chip {
font-size: 0.85rem;
}
.conn-dot {
width: 8px;
height: 8px;
border-radius: 50%;
display: inline-block;
}
.conn-dot.on {
background: #6fe08b;
}
.conn-dot.off {
background: var(--red);
}
.topbar-code {
font-family: var(--font-display);
letter-spacing: 0.25em;
background: rgba(0, 0, 0, 0.25);
border: 2px dashed rgba(253, 243, 220, 0.4);
border-radius: 8px;
padding: 4px 10px;
}
.table-main {
flex: 1;
padding: 20px 16px 40px;
max-width: 1100px;
width: 100%;
margin: 0 auto;
}
/* ---------- lobby ---------- */
.lobby {
min-height: 60vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14px;
text-align: center;
}
.lobby-bounce {
font-size: 3rem;
animation: float 2s ease-in-out infinite;
}
.lobby-code {
font-family: var(--font-display);
font-size: 3rem;
letter-spacing: 0.35em;
color: var(--gold);
background: rgba(0, 0, 0, 0.25);
border: 3px dashed rgba(255, 207, 92, 0.5);
border-radius: 16px;
padding: 12px 28px 12px 40px;
}
/* ---------- cards ---------- */
.card {
position: relative;
width: 108px;
height: 148px;
background: linear-gradient(180deg, var(--cream), var(--cream-dark));
border: 3px solid var(--cocoa);
border-radius: var(--card-radius);
color: var(--ink);
display: flex;
flex-direction: column;
align-items: center;
padding: 6px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.35);
flex-shrink: 0;
transition: transform 120ms ease, box-shadow 120ms ease;
user-select: none;
}
.card-lg {
width: 128px;
height: 176px;
}
.card-sm {
width: 84px;
height: 116px;
}
.card.is-clickable {
cursor: pointer;
}
.card.is-clickable:hover {
transform: translateY(-6px) rotate(-1deg);
box-shadow: 0 10px 16px rgba(0, 0, 0, 0.4);
}
.card.is-selected {
outline: 4px solid var(--gold);
transform: translateY(-6px);
}
.card.is-disabled {
filter: saturate(0.6) brightness(0.85);
}
.card.is-dead {
filter: grayscale(1);
}
.card-top {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.72rem;
}
.card-tier {
font-weight: 900;
color: rgba(51, 35, 15, 0.55);
}
.card-suit {
font-size: 0.95rem;
}
.card-art {
font-size: 3rem;
line-height: 1.25;
filter: drop-shadow(0 3px 2px rgba(0, 0, 0, 0.25));
}
.card-lg .card-art {
font-size: 3.6rem;
}
.card-sm .card-art {
font-size: 2.2rem;
}
.card-name {
font-family: var(--font-display);
font-size: 0.85rem;
margin-top: auto;
}
.card-bottom {
display: flex;
gap: 6px;
align-items: center;
margin-top: 2px;
}
.card-power {
font-family: var(--font-display);
background: radial-gradient(circle at 35% 30%, #ffb347, var(--coral-dark));
color: #fff;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
border: 2px solid rgba(0, 0, 0, 0.25);
border-radius: 50%;
width: 30px;
height: 30px;
display: grid;
place-items: center;
font-size: 0.95rem;
}
.card-power.is-buffed {
background: radial-gradient(circle at 35% 30%, #7be495, #1f9e55);
}
.card-damage {
font-family: var(--font-display);
color: #fff;
background: var(--red);
border: 2px solid rgba(0, 0, 0, 0.25);
border-radius: 8px;
padding: 1px 6px;
font-size: 0.8rem;
}
.card-food-text {
font-size: 0.72rem;
font-weight: 700;
color: #7a2e1e;
margin-top: 2px;
}
.card-food {
background: linear-gradient(180deg, #ffe9e0, #ffd4c2);
}
.card-check {
position: absolute;
top: -10px;
right: -10px;
background: var(--gold);
color: var(--ink);
font-weight: 900;
border: 2px solid var(--cocoa);
border-radius: 50%;
width: 26px;
height: 26px;
display: grid;
place-items: center;
}
.card-slot-empty {
width: 128px;
height: 176px;
border: 3px dashed rgba(253, 243, 220, 0.25);
border-radius: var(--card-radius);
flex-shrink: 0;
}
/* ---------- shop ---------- */
.shop {
display: flex;
flex-direction: column;
gap: 22px;
}
.shop-status {
text-align: center;
font-size: 1.15rem;
font-weight: 900;
min-height: 1.6em;
}
.status-hot {
color: var(--gold);
animation: pulse 1.6s ease-in-out infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.65;
}
}
.section-label {
font-family: var(--font-display);
font-size: 1rem;
margin-bottom: 10px;
color: rgba(253, 243, 220, 0.9);
}
.shop-row-wrap,
.deck-wrap {
background: rgba(0, 0, 0, 0.18);
border: 2px solid rgba(253, 243, 220, 0.1);
border-radius: 18px;
padding: 14px 16px;
}
.shop-row,
.deck-row {
display: flex;
gap: 14px;
flex-wrap: wrap;
justify-content: center;
}
.deck-empty {
text-align: center;
padding: 20px 0;
}
.actions {
display: flex;
gap: 12px;
justify-content: center;
flex-wrap: wrap;
}
/* ---------- modal ---------- */
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.6);
display: grid;
place-items: center;
z-index: 50;
}
.modal {
background: linear-gradient(180deg, var(--felt-700), var(--felt-800));
border: 3px solid rgba(253, 243, 220, 0.25);
border-radius: 20px;
padding: 24px;
text-align: center;
display: flex;
flex-direction: column;
gap: 18px;
max-width: 92vw;
}
.modal-cards {
display: flex;
gap: 18px;
justify-content: center;
}
/* ---------- arrange ---------- */
.arrange {
display: flex;
flex-direction: column;
gap: 18px;
}
.arrange-row {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
justify-content: center;
background: rgba(0, 0, 0, 0.18);
border: 2px solid rgba(253, 243, 220, 0.1);
border-radius: 18px;
padding: 18px 16px;
min-height: 220px;
}
.arrange-marker {
font-family: var(--font-display);
color: var(--gold);
writing-mode: vertical-rl;
transform: rotate(180deg);
font-size: 0.9rem;
opacity: 0.8;
}
.arrange-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
cursor: grab;
}
.arrange-card:active {
cursor: grabbing;
}
.arrange-arrows {
display: flex;
gap: 4px;
}
/* ---------- battle ---------- */
.battle {
display: flex;
flex-direction: column;
gap: 16px;
}
.battle-header {
display: flex;
justify-content: center;
align-items: center;
gap: 14px;
}
.battle-names {
display: flex;
justify-content: center;
gap: 18px;
font-weight: 900;
}
.battle-vs {
font-family: var(--font-display);
color: var(--gold);
}
.battlefield {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
background:
radial-gradient(ellipse at center, rgba(255, 207, 92, 0.07), transparent 65%),
rgba(0, 0, 0, 0.2);
border: 2px solid rgba(253, 243, 220, 0.1);
border-radius: 18px;
padding: 26px 12px;
min-height: 240px;
overflow-x: auto;
}
.battle-center {
font-size: 1.6rem;
opacity: 0.5;
flex-shrink: 0;
}
.battle-side {
display: flex;
gap: 10px;
flex: 1;
min-width: 0;
}
/* Front units meet in the middle: left side is reversed so index 0 sits
next to the center. */
.battle-side-left {
flex-direction: row-reverse;
}
.battle-side-right {
flex-direction: row;
}
.battle-unit {
position: relative;
flex-shrink: 0;
}
.battle-unit .card {
width: 96px;
height: 132px;
}
.battle-unit.is-front .card {
outline: 3px solid rgba(255, 207, 92, 0.6);
}
@keyframes clash-left {
0% {
transform: translateX(0);
}
35% {
transform: translateX(26px) rotate(4deg);
}
60% {
transform: translateX(-6px);
}
100% {
transform: translateX(0);
}
}
@keyframes clash-right {
0% {
transform: translateX(0);
}
35% {
transform: translateX(-26px) rotate(-4deg);
}
60% {
transform: translateX(6px);
}
100% {
transform: translateX(0);
}
}
.battle-unit.clash-left {
animation: clash-left 500ms ease;
}
.battle-unit.clash-right {
animation: clash-right 500ms ease;
}
@keyframes dying {
to {
opacity: 0;
transform: translateY(30px) rotate(12deg) scale(0.85);
}
}
.battle-unit.unit-dying {
animation: dying 700ms ease 500ms forwards;
}
@keyframes damage-pop {
0% {
opacity: 0;
transform: translate(-50%, 0) scale(0.6);
}
25% {
opacity: 1;
transform: translate(-50%, -16px) scale(1.15);
}
100% {
opacity: 0;
transform: translate(-50%, -44px) scale(1);
}
}
.damage-pop {
position: absolute;
top: 0;
left: 50%;
font-family: var(--font-display);
font-size: 1.4rem;
color: #ff6b52;
text-shadow: 0 2px 0 rgba(0, 0, 0, 0.5);
animation: damage-pop 1100ms ease 250ms forwards;
opacity: 0;
pointer-events: none;
z-index: 5;
}
.battle-result {
text-align: center;
display: flex;
flex-direction: column;
gap: 10px;
align-items: center;
animation: result-in 400ms ease;
}
@keyframes result-in {
from {
opacity: 0;
transform: translateY(16px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.battle-result-title {
font-family: var(--font-display);
font-size: 2.4rem;
}
.battle-result.is-win .battle-result-title {
color: var(--gold);
}
.battle-result.is-loss .battle-result-title {
color: #ff8f7a;
}
.battle-result.is-draw .battle-result-title {
color: var(--teal);
}
.battle-result-sub {
font-size: 1.1rem;
font-weight: 700;
}
/* ---------- game over ---------- */
.gameover {
min-height: 60vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 18px;
text-align: center;
}
.gameover-emoji {
font-size: 4rem;
}
.gameover-title {
font-size: 3rem;
color: var(--gold);
text-shadow: 0 4px 0 rgba(0, 0, 0, 0.35);
}
.gameover-scores {
display: flex;
flex-direction: column;
gap: 8px;
background: rgba(0, 0, 0, 0.22);
border-radius: 16px;
padding: 18px 26px;
min-width: min(360px, 90vw);
}
.score-line {
display: flex;
justify-content: space-between;
gap: 24px;
font-size: 1.1rem;
}
.score-line.is-you .score-name {
color: var(--gold);
font-weight: 900;
}
/* ---------- toasts & banners ---------- */
.toast {
position: fixed;
bottom: 24px;
left: 50%;
transform: translateX(-50%);
background: var(--red);
color: #fff;
font-weight: 700;
border-radius: 12px;
padding: 10px 20px;
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.4);
animation: result-in 200ms ease;
z-index: 100;
}
.banner {
position: fixed;
top: 64px;
left: 50%;
transform: translateX(-50%);
border-radius: 10px;
padding: 6px 16px;
font-size: 0.9rem;
font-weight: 700;
z-index: 90;
}
.banner-warn {
background: rgba(217, 74, 56, 0.9);
}
@media (max-width: 600px) {
.card {
width: 92px;
height: 128px;
}
.card-lg {
width: 104px;
height: 146px;
}
.battle-unit .card {
width: 78px;
height: 110px;
}
}
+91
View File
@@ -0,0 +1,91 @@
// Mirrors of the Go view types (internal/game/view.go).
export type Suit = 'sun' | 'moon' | 'star' | 'leaf'
export type CardKind = 'pet' | 'food'
export type Phase = 'lobby' | 'shop' | 'cleanup' | 'arrange' | 'battle' | 'gameover'
export interface Card {
id: string
kind: CardKind
name: string
tier: number
power?: number
suit?: Suit
effect?: string
food?: string
}
export interface PlayerView {
id: string
name: string
seat: number
coins: number
trophies: number
ready: boolean
connected: boolean
deckSize: number
petCount: number
deck?: Card[]
}
export interface PendingTrade {
playerId: string
tier: number
options: [Card, Card]
}
export interface BattleUnit {
card: Card
foods: Card[] | null
bonus: number
damage: number
}
export interface BattleEvent {
type: 'clash'
units: number[]
damage: number[]
died: boolean[]
}
export interface BattleResult {
round: number
lineups: BattleUnit[][]
wastedFoods: (Card[] | null)[]
events: BattleEvent[] | null
winnerSeat: number
trophies: number
}
export interface GameView {
gameId: string
code: string
phase: Phase
round: number
maxRounds: number
maxPets: number
youSeat: number
turn: number
shopRow: Card[]
deckCounts: number[]
players: PlayerView[]
pending?: PendingTrade
battle?: BattleResult
winnerSeat: number
}
export type ClientMessage =
| { type: 'buy'; row: number }
| { type: 'discard'; cards: string[] }
| { type: 'trade'; cards: string[] }
| { type: 'tradeChoose'; pick: number }
| { type: 'pass' }
| { type: 'arrange'; order: string[] }
| { type: 'ready' }
export interface Session {
gameId: string
code: string
playerId: string
token: string
}
+72
View File
@@ -0,0 +1,72 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { ClientMessage, GameView, Session } from './types'
interface ServerMessage {
type: 'state' | 'error'
state?: GameView
error?: string
}
// useGame owns the WebSocket for a session: it keeps the latest server view,
// reconnects with backoff, and exposes send() for actions. Server-rejected
// actions surface as a transient `error`.
export function useGame(session: Session) {
const [view, setView] = useState<GameView | null>(null)
const [error, setError] = useState<string | null>(null)
const [connected, setConnected] = useState(false)
const wsRef = useRef<WebSocket | null>(null)
const errorTimer = useRef<number>(undefined)
useEffect(() => {
let ws: WebSocket
let closed = false
let retryDelay = 500
let retryTimer: number | undefined
function connect() {
const proto = location.protocol === 'https:' ? 'wss' : 'ws'
const params = new URLSearchParams({
game: session.gameId,
player: session.playerId,
token: session.token,
})
ws = new WebSocket(`${proto}://${location.host}/api/ws?${params}`)
wsRef.current = ws
ws.onopen = () => {
retryDelay = 500
setConnected(true)
}
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data) as ServerMessage
if (msg.type === 'state' && msg.state) setView(msg.state)
if (msg.type === 'error' && msg.error) showError(msg.error)
}
ws.onclose = () => {
setConnected(false)
if (closed) return
retryTimer = window.setTimeout(connect, retryDelay)
retryDelay = Math.min(retryDelay * 2, 8000)
}
}
function showError(msg: string) {
setError(msg)
window.clearTimeout(errorTimer.current)
errorTimer.current = window.setTimeout(() => setError(null), 3500)
}
connect()
return () => {
closed = true
window.clearTimeout(retryTimer)
window.clearTimeout(errorTimer.current)
ws.close()
}
}, [session.gameId, session.playerId, session.token])
const send = useCallback((msg: ClientMessage) => {
wsRef.current?.send(JSON.stringify(msg))
}, [])
return { view, error, connected, send }
}