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
+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>
)
}