games: a blackjack table you can actually sit down at

The engine, the escrow and the wire were all in place; nothing had a browser on
the end of it. This is that end: a lobby, a table, and the five endpoints between
them.

The browser holds no game. It sends intents and gets back a view — the cards it
is entitled to see, and the script of how they arrived, one event per card off
the shoe. The dealer's hole card is not in the payload at all until the reveal,
because a field the client is told to ignore is a field somebody reads in
devtools. The shoe lives in game_live_hands, which also means a redeploy
mid-hand no longer costs a player their stake: the hand is still there when they
come back.

The money is ordered so nothing can be spent twice. The stake leaves the stack in
the same statement that checks it exists, before a card is dealt. Every new hand
is seated with a plain INSERT, so a double-clicked Deal is decided by the primary
key rather than by a read that raced — it loses, gets its chips back, and the
hand in progress is untouched. A double takes its raise up front and hands it
straight back if the engine refuses the move.

Cards are dealt rather than swapped in — they fly out of the shoe and turn over,
which was a requirement and not a flourish. The faces and the chips are still
plain; that's next.
This commit is contained in:
prosolis
2026-07-13 23:20:42 -07:00
parent cb84e1d549
commit c69fbb63db
17 changed files with 1949 additions and 18 deletions

View File

@@ -102,6 +102,16 @@ label = "Amy (US, female)"
id = "en_US-ryan-high"
label = "Ryan (US, male, HQ)"
# The casino (games.parodia.dev). Signed-in only — there is real money in it — so
# it needs [web.auth] above, and web.auth.cookie_domain if the games host is a
# different subdomain from the news one. Chips are 1:1 with gogobee euros and
# cross the border through the escrow endpoints, which gogobee polls; matrix_server
# is how a player is named to that ledger (@<authentik username>:<matrix_server>).
[web.games]
enabled = false
host = "games.parodia.dev"
matrix_server = "parodia.dev"
# Every enabled source MUST set direct_route to a key from [matrix.channels] above.
# There is no automatic classification — Pete posts each story to its configured channel.
# Optional: language = "en" drops feed items whose per-item <language> tag is

View File

@@ -60,6 +60,7 @@ type WebConfig struct {
Auth AuthConfig `toml:"auth"` // optional OIDC sign-in (Authentik)
Push PushConfig `toml:"push"` // optional Web Push digests (VAPID)
TTS TTSConfig `toml:"tts"` // optional server-side neural read-aloud (Piper)
Games GamesConfig `toml:"games"` // optional casino (games.parodia.dev)
// AdminSubs is the allowlist of OIDC subjects allowed to view the
// owner-facing source-health dashboard at /status. Empty means the page is
// inaccessible to everyone (returns 404). Requires auth to be enabled.
@@ -108,6 +109,23 @@ type VoiceConfig struct {
Label string `toml:"label"` // menu label, e.g. "Ryan — US, male"
}
// GamesConfig wires the casino. It is signed-in only — there is money in it —
// so it does nothing without web.auth, and it needs the Matrix server name
// because that is how a player's identity reaches gogobee's euro ledger: an
// Authentik username is the Matrix localpart, and the Matrix id is the account.
type GamesConfig struct {
Enabled bool `toml:"enabled"`
// Host is the public hostname the casino answers on, e.g.
// "games.parodia.dev". Requests arriving on it are served the casino at "/";
// everywhere else the same pages live under /games. Empty means no host
// branching, which is the normal state of affairs in local development.
Host string `toml:"host"`
// MatrixServer is the server name half of a player's Matrix id
// ("parodia.dev" -> @reala:parodia.dev). Without it, no player can be
// identified in the economy and the casino stays shut.
MatrixServer string `toml:"matrix_server"`
}
// AuthConfig wires Pete's web UI to an OIDC provider (our Authentik instance).
// When enabled, signed-in users get their preferences stored server-side keyed
// by the OIDC subject; anonymous visitors keep using browser localStorage.

View File

@@ -503,6 +503,91 @@ func Touch(user string) {
nowUnix(), nowUnix(), user)
}
// ---- the hand in progress -------------------------------------------------
var (
// ErrNoLiveHand means the player isn't in a hand right now.
ErrNoLiveHand = errors.New("games: no hand in progress")
// ErrHandInProgress means they already are, and may not be dealt another.
ErrHandInProgress = errors.New("games: already in a hand")
)
// LiveHand is a hand a player is in the middle of. State is the engine's own
// State, serialized whole — the shoe is in there, which is exactly why this row
// never leaves the server.
type LiveHand struct {
Game string
State []byte
Seed1 uint64
Seed2 uint64
}
// StartLiveHand seats a *new* hand, and refuses if the player is already in one.
// The plain INSERT is the point: it is the primary key, not a prior read, that
// decides. Two Deal clicks racing each other would otherwise both see an empty
// felt, both take a stake, and the second would overwrite the first — taking the
// player's chips for a hand that no longer exists anywhere.
func StartLiveHand(user string, h LiveHand) error {
res, err := Get().Exec(
`INSERT INTO game_live_hands (matrix_user, game, state, seed1, seed2, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(matrix_user) DO NOTHING`,
user, h.Game, string(h.State), int64(h.Seed1), int64(h.Seed2), nowUnix(),
)
if err != nil {
return fmt.Errorf("games: start live hand: %w", err)
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrHandInProgress
}
return nil
}
// SaveLiveHand stores the hand a player is in, replacing any earlier one. The
// player's stake has already left their stack by the time this is called, so
// the write is what makes the hand recoverable if Pete restarts mid-deal.
func SaveLiveHand(user string, h LiveHand) error {
now := nowUnix()
if _, err := Get().Exec(
`INSERT INTO game_live_hands (matrix_user, game, state, seed1, seed2, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(matrix_user) DO UPDATE SET
game = excluded.game, state = excluded.state,
seed1 = excluded.seed1, seed2 = excluded.seed2, updated_at = excluded.updated_at`,
user, h.Game, string(h.State), int64(h.Seed1), int64(h.Seed2), now,
); err != nil {
return fmt.Errorf("games: save live hand: %w", err)
}
return nil
}
// LoadLiveHand returns the hand a player is in, or ErrNoLiveHand.
func LoadLiveHand(user string) (LiveHand, error) {
var h LiveHand
var state string
var s1, s2 int64
err := Get().QueryRow(
`SELECT game, state, seed1, seed2 FROM game_live_hands WHERE matrix_user = ?`, user,
).Scan(&h.Game, &state, &s1, &s2)
if errors.Is(err, sql.ErrNoRows) {
return LiveHand{}, ErrNoLiveHand
}
if err != nil {
return LiveHand{}, fmt.Errorf("games: load live hand: %w", err)
}
h.State, h.Seed1, h.Seed2 = []byte(state), uint64(s1), uint64(s2)
return h, nil
}
// ClearLiveHand ends a hand. Called when it settles — the audit log in
// game_hands is what survives it.
func ClearLiveHand(user string) error {
if _, err := Get().Exec(`DELETE FROM game_live_hands WHERE matrix_user = ?`, user); err != nil {
return fmt.Errorf("games: clear live hand: %w", err)
}
return nil
}
// HouseTake is the total rake collected since a given time — the number that
// answers "is this economy inflating".
func HouseTake(since int64) (int64, error) {

View File

@@ -225,6 +225,23 @@ CREATE TABLE IF NOT EXISTS game_hands (
CREATE INDEX IF NOT EXISTS idx_game_hands_user ON game_hands(matrix_user, played_at DESC);
CREATE INDEX IF NOT EXISTS idx_game_hands_played ON game_hands(played_at);
-- The hand a player is in the middle of. One per player: you cannot be dealt a
-- second hand while chips are riding on the first.
--
-- The state column is the engine's State, serialized whole — shoe included. It
-- lives here rather than in memory because Pete redeploys often, and a player
-- whose stake has already been taken must find their cards where they left them
-- rather than a table that has forgotten them. It is also why the deck never
-- goes to the browser: the authoritative shoe is this row, on the server.
CREATE TABLE IF NOT EXISTS game_live_hands (
matrix_user TEXT PRIMARY KEY,
game TEXT NOT NULL, -- 'blackjack'
state TEXT NOT NULL, -- JSON: the engine's State
seed1 INTEGER NOT NULL, -- carried to the audit log when it settles
seed2 INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_post_log_guid_channel ON post_log(guid, channel);
CREATE INDEX IF NOT EXISTS idx_post_log_event_id ON post_log(event_id);
CREATE INDEX IF NOT EXISTS idx_post_log_channel_posted ON post_log(channel, posted_at);

View File

@@ -0,0 +1,84 @@
package web
import (
"net/http"
"pete/internal/games/blackjack"
"pete/internal/storage"
)
// The casino's two pages. Both require a signed-in visitor — there is money in
// here, and a player has to be somebody gogobee's ledger can name.
//
// Neither page renders any game state server-side. The felt is drawn by the
// browser from /api/games/table, because a hand is a thing that *happens*: cards
// are dealt one at a time and the table plays that back. A server-rendered hand
// would arrive fully formed, which is the one thing a card table must never do.
// gameTeaser is a table that isn't open yet. They're on the lobby because an
// empty casino with one game reads as broken, and this reads as early.
type gameTeaser struct {
Name string
Emoji string
Blurb string
}
var comingSoon = []gameTeaser{
{Name: "Hold'em", Emoji: "♠️", Blurb: "Six seats, and Pete's bots know how to play."},
{Name: "UNO", Emoji: "🎴", Blurb: "Normal rules, or no mercy."},
{Name: "Trivia", Emoji: "🧠", Blurb: "Faster answers score higher."},
{Name: "Hangman", Emoji: "🪢", Blurb: "Guess the phrase before Pete finishes drawing."},
}
// betDenominations are the chips you build a bet out of.
var betDenominations = []int64{5, 25, 100, 500}
type gamesPage struct {
pageData
Cap int64
RakePct int
Soon []gameTeaser
Denominations []int64
}
// requirePlayer sends an anonymous visitor to sign in and comes back here after.
// Anyone who is signed in but carries a session from before the casino existed
// has no username in it, so they get sent through sign-in too — which mints one.
func (s *Server) requirePlayer(w http.ResponseWriter, r *http.Request) bool {
if !s.gamesReady() {
http.NotFound(w, r)
return false
}
u := s.auth.userFromRequest(r)
if u != nil && u.MatrixUser(s.cfg.Games.MatrixServer) != "" {
return true
}
http.Redirect(w, r, "/auth/login?next="+r.URL.Path, http.StatusFound)
return false
}
func (s *Server) gamesPage(r *http.Request) gamesPage {
base := s.base(r)
base.NoIndex = true // the casino is for players, not for search engines
return gamesPage{
pageData: base,
Cap: storage.MaxChipsOnTable,
RakePct: int(blackjack.DefaultRules().RakePct * 100),
Soon: comingSoon,
Denominations: betDenominations,
}
}
func (s *Server) handleLobby(w http.ResponseWriter, r *http.Request) {
if !s.requirePlayer(w, r) {
return
}
s.render(w, "games", s.gamesPage(r))
}
func (s *Server) handleBlackjack(w http.ResponseWriter, r *http.Request) {
if !s.requirePlayer(w, r) {
return
}
s.render(w, "blackjack", s.gamesPage(r))
}

530
internal/web/games_play.go Normal file
View File

@@ -0,0 +1,530 @@
package web
import (
"encoding/json"
"errors"
"io"
"log/slog"
"math/rand/v2"
"net/http"
"time"
"pete/internal/games/blackjack"
"pete/internal/games/cards"
"pete/internal/storage"
)
// The table, as a browser sees it.
//
// Everything here is server-authoritative. The browser sends intents — deal me
// in, hit, stand — and gets back a *view*: the cards it is entitled to see and
// nothing else. The shoe stays in game_live_hands, on this side of the wire.
// That is not belt-and-braces, it is the whole reason the engines are Go: a game
// with money on it cannot trust a client-reported result, and a client that
// holds the deck can read the next card.
//
// The stake leaves the player's stack *before* the hand is dealt, and comes back
// only through the engine's own payout. So a hand that crashes halfway costs the
// player their bet and nothing more, and a hand that Pete restarts through is
// still sitting there when they come back.
// gamesReady reports whether the casino can actually run: it needs sign-in (a
// player has to be someone) and a Matrix server name (that someone has to exist
// in gogobee's ledger).
func (s *Server) gamesReady() bool {
return s.cfg.Games.Enabled && s.auth != nil && s.cfg.Games.MatrixServer != ""
}
// player resolves the signed-in visitor to their Matrix id, or writes the
// failure. An empty id means a session from before games existed, which carries
// no username: sending them back through sign-in mints one.
func (s *Server) player(w http.ResponseWriter, r *http.Request) (string, bool) {
if !s.gamesReady() {
http.NotFound(w, r)
return "", false
}
u := s.auth.userFromRequest(r)
if u == nil {
writeJSONStatus(w, http.StatusUnauthorized, map[string]string{"error": "sign in to play"})
return "", false
}
mx := u.MatrixUser(s.cfg.Games.MatrixServer)
if mx == "" {
writeJSONStatus(w, http.StatusForbidden, map[string]string{
"error": "your session predates the casino — sign out and back in",
})
return "", false
}
return mx, true
}
// ---- what the browser is allowed to see -----------------------------------
// cardView is one card, pre-rendered. The browser draws faces, not logic: it
// gets the glyph and the colour rather than a rank it has to map itself.
type cardView struct {
Label string `json:"label"` // "A♠"
Rank string `json:"rank"` // "A"
Suit string `json:"suit"` // "♠"
Red bool `json:"red"`
}
func viewCard(c cards.Card) cardView {
label := c.String()
// String() renders rank then a three-byte suit glyph, except for a card that
// isn't one ("??"), which has no glyph to split off.
if len(label) <= len("♠") {
return cardView{Label: label, Rank: label}
}
cut := len(label) - len("♠")
return cardView{Label: label, Rank: label[:cut], Suit: label[cut:], Red: c.Red()}
}
// handView is a blackjack hand as its player may see it. While they are still
// acting, the dealer's hole card is *absent* — not sent and flagged hidden, but
// genuinely not in the payload. A field the browser is told to ignore is a field
// somebody reads in devtools.
type handView struct {
Phase string `json:"phase"`
Bet int64 `json:"bet"`
Player []cardView `json:"player"`
Dealer []cardView `json:"dealer"`
Hole bool `json:"hole"` // true: the dealer has a face-down card
Total int `json:"total"`
Soft bool `json:"soft"`
DTotal int `json:"dealer_total"` // what the *shown* dealer cards add to
Outcome string `json:"outcome,omitempty"`
Payout int64 `json:"payout,omitempty"`
Rake int64 `json:"rake,omitempty"`
Net int64 `json:"net"`
Double bool `json:"can_double"`
}
func viewHand(st blackjack.State) handView {
v := handView{
Phase: string(st.Phase),
Bet: st.Bet,
Outcome: string(st.Outcome),
Payout: st.Payout,
Rake: st.Rake,
Net: st.Net(),
Double: st.CanDouble(),
}
for _, c := range st.Player {
v.Player = append(v.Player, viewCard(c))
}
v.Total, v.Soft = blackjack.HandValue(st.Player)
dealer := st.Dealer
if st.Phase == blackjack.PhasePlayer && len(dealer) > 1 {
dealer = dealer[:1] // the hole card is the dealer's business until it isn't
v.Hole = true
}
for _, c := range dealer {
v.Dealer = append(v.Dealer, viewCard(c))
}
v.DTotal, _ = blackjack.HandValue(dealer)
return v
}
// eventView is the dealing script. The engine emits one event per card off the
// shoe, in order, and the table animates them one at a time — which is why the
// events go over the wire at all rather than the browser diffing two states.
type eventView struct {
Kind string `json:"kind"`
Card *cardView `json:"card,omitempty"`
Text string `json:"text,omitempty"`
}
// viewEvents renders the engine's events for the browser, dropping the cards it
// is not yet allowed to see: the dealer's second card is dealt face-down, and
// only the "reveal" event turns it over.
func viewEvents(evs []blackjack.Event, phase blackjack.Phase) []eventView {
out := make([]eventView, 0, len(evs))
dealerCards := 0
for _, e := range evs {
v := eventView{Kind: e.Kind, Text: e.Text}
if e.Card != nil {
c := viewCard(*e.Card)
v.Card = &c
}
if e.Kind == "dealer_card" {
dealerCards++
// The hole card, while the hand is still the player's to play: send
// the event so the table deals a face-down card, but not the face.
if dealerCards == 2 && phase == blackjack.PhasePlayer {
v.Card = nil
v.Kind = "dealer_hole"
}
}
out = append(out, v)
}
return out
}
// tableView is the whole page state: the money, and the hand if there is one.
type tableView struct {
Chips int64 `json:"chips"`
Pending int64 `json:"pending"` // buy-ins gogobee hasn't answered yet
Euros float64 `json:"euros"` // advisory, and up to a couple of minutes stale
Cap int64 `json:"cap"`
Hand *handView `json:"hand,omitempty"`
Events []eventView `json:"events,omitempty"` // only on a move, for the animation
Rake float64 `json:"rake_pct"`
}
// table reads the player's money and any hand in progress.
func (s *Server) table(user string) (tableView, error) {
st, err := storage.Chips(user)
if err != nil {
return tableView{}, err
}
v := tableView{
Chips: st.Chips,
Pending: st.Pending,
Euros: st.EuroBalance,
Cap: storage.MaxChipsOnTable,
Rake: blackjack.DefaultRules().RakePct,
}
live, err := storage.LoadLiveHand(user)
if errors.Is(err, storage.ErrNoLiveHand) {
return v, nil
}
if err != nil {
return tableView{}, err
}
var hand blackjack.State
if err := json.Unmarshal(live.State, &hand); err != nil {
// A hand we can't read is a hand nobody can play. Rather than wedge the
// player out of the casino forever, drop it and tell them.
slog.Error("games: unreadable live hand, discarding", "user", user, "err", err)
_ = storage.ClearLiveHand(user)
return v, nil
}
hv := viewHand(hand)
v.Hand = &hv
return v, nil
}
// ---- handlers -------------------------------------------------------------
// handleTable is the page's poll: chips, euros, and whatever hand is on the felt.
func (s *Server) handleTable(w http.ResponseWriter, r *http.Request) {
user, ok := s.player(w, r)
if !ok {
return
}
v, err := s.table(user)
if err != nil {
slog.Error("games: table", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
writeJSON(w, v)
}
// amountBody is {amount: n} — chips, which are euros.
type amountBody struct {
Amount int64 `json:"amount"`
}
func decodeJSON(r *http.Request, v any) error {
return json.NewDecoder(io.LimitReader(r.Body, 1<<14)).Decode(v)
}
// handleBuyIn opens a buy-in. It creates no chips: it writes an escrow row, and
// gogobee decides — up to three seconds later — whether the player could afford
// it. The browser watches `pending` fall to zero to know how it went.
func (s *Server) handleBuyIn(w http.ResponseWriter, r *http.Request) {
user, ok := s.player(w, r)
if !ok {
return
}
var req amountBody
if err := decodeJSON(r, &req); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
e, err := storage.RequestBuyIn(user, req.Amount)
switch {
case errors.Is(err, storage.ErrBadAmount):
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "buy in for something more than nothing"})
return
case errors.Is(err, storage.ErrOverTableCap):
writeJSONStatus(w, http.StatusBadRequest, map[string]string{
"error": "that would put more than the table cap in front of you",
})
return
case err != nil:
slog.Error("games: buy-in", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
storage.Touch(user)
slog.Info("games: buy-in requested", "user", user, "amount", e.Amount, "guid", e.GUID)
v, err := s.table(user)
if err != nil {
slog.Error("games: table after buy-in", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
writeJSON(w, v)
}
// handleCashOut sends chips back across the border. The chips are destroyed
// here and now — see storage.RequestCashOut for why that has to happen before
// gogobee has said anything — so the response already shows an empty stack. An
// amount of zero or less means "all of it", which is what the button does.
func (s *Server) handleCashOut(w http.ResponseWriter, r *http.Request) {
user, ok := s.player(w, r)
if !ok {
return
}
var req amountBody
if err := decodeJSON(r, &req); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
// You cannot walk away from a hand you have chips riding on. The stake is
// already off the stack, so this isn't about the money — it's that a hand
// left half-played would settle into a session that no longer exists.
if _, err := storage.LoadLiveHand(user); err == nil {
writeJSONStatus(w, http.StatusConflict, map[string]string{"error": "finish the hand first"})
return
} else if !errors.Is(err, storage.ErrNoLiveHand) {
slog.Error("games: cash-out live-hand check", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
amount := req.Amount
if amount <= 0 {
st, err := storage.Chips(user)
if err != nil {
slog.Error("games: cash-out", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
amount = st.Chips
}
e, err := storage.RequestCashOut(user, amount)
switch {
case errors.Is(err, storage.ErrBadAmount), errors.Is(err, storage.ErrInsufficientChips):
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "you don't have those chips"})
return
case err != nil:
slog.Error("games: cash-out", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
slog.Info("games: cash-out requested", "user", user, "amount", e.Amount, "guid", e.GUID)
v, err := s.table(user)
if err != nil {
slog.Error("games: table after cash-out", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
writeJSON(w, v)
}
// ---- blackjack ------------------------------------------------------------
// handleDeal takes the bet and deals. The order matters: chips are staked first,
// in the same statement that checks they exist, so two deals fired at once
// cannot bet the same chip. Only then is a hand dealt.
func (s *Server) handleDeal(w http.ResponseWriter, r *http.Request) {
user, ok := s.player(w, r)
if !ok {
return
}
var req struct {
Bet int64 `json:"bet"`
}
if err := decodeJSON(r, &req); err != nil || req.Bet <= 0 {
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "bet something"})
return
}
if err := storage.Stake(user, req.Bet); err != nil {
if errors.Is(err, storage.ErrInsufficientChips) || errors.Is(err, storage.ErrBadAmount) {
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "not enough chips for that bet"})
return
}
slog.Error("games: stake", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
seed1, seed2 := newSeeds()
rng := rand.New(rand.NewPCG(seed1, seed2))
st, evs, err := blackjack.New(req.Bet, blackjack.DefaultRules(), rng)
if err != nil {
// The hand never happened, so the stake never should have left. Give it back.
_ = storage.Award(user, req.Bet)
slog.Error("games: deal", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
s.persist(w, user, st, evs, seed1, seed2, true)
}
// handleMove plays one move of the hand in progress.
func (s *Server) handleMove(w http.ResponseWriter, r *http.Request) {
user, ok := s.player(w, r)
if !ok {
return
}
var req struct {
Move string `json:"move"`
}
if err := decodeJSON(r, &req); err != nil {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
live, err := storage.LoadLiveHand(user)
if errors.Is(err, storage.ErrNoLiveHand) {
writeJSONStatus(w, http.StatusConflict, map[string]string{"error": "no hand in progress"})
return
}
if err != nil {
slog.Error("games: load hand", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
var st blackjack.State
if err := json.Unmarshal(live.State, &st); err != nil {
slog.Error("games: unreadable live hand", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
move := blackjack.Move(req.Move)
// A double doubles the stake, so the extra chips have to be taken before the
// move is applied — and if they aren't there, the move simply isn't legal.
// Take them first: if the engine then refuses the move, they go straight back.
doubled := false
if move == blackjack.Double {
if !st.CanDouble() {
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "you can only double on the first two cards"})
return
}
if err := storage.Stake(user, st.Bet); err != nil {
if errors.Is(err, storage.ErrInsufficientChips) {
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "not enough chips to double"})
return
}
slog.Error("games: stake double", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
doubled = true
}
next, evs, err := blackjack.ApplyMove(st, move)
if err != nil {
if doubled {
_ = storage.Award(user, st.Bet) // the move didn't happen; neither did the raise
}
writeJSONStatus(w, http.StatusBadRequest, map[string]string{"error": "that move isn't legal here"})
return
}
s.persist(w, user, next, evs, live.Seed1, live.Seed2, false)
}
// persist writes the hand back and answers the browser. A finished hand pays
// out, goes in the audit log, and leaves the felt; an unfinished one is saved
// as it stands, so a redeploy mid-hand is survivable.
//
// fresh marks a hand that has just been dealt, which is the one case where the
// write may be refused: the primary key, not an earlier read, is what enforces
// one hand at a time. A Deal that loses that race gets its stake back.
func (s *Server) persist(w http.ResponseWriter, user string, st blackjack.State, evs []blackjack.Event, seed1, seed2 uint64, fresh bool) {
blob, err := json.Marshal(st)
if err != nil {
slog.Error("games: marshal hand", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// Seat the hand before doing anything else with it — even one that is already
// over, because a natural settles the instant it's dealt. The insert is what
// enforces one hand at a time, and it has to happen for *every* new hand: a
// natural dealt on top of a hand already in progress would otherwise settle,
// clear the felt, and take the other hand's stake down with it.
hand := storage.LiveHand{Game: "blackjack", State: blob, Seed1: seed1, Seed2: seed2}
save := storage.SaveLiveHand
if fresh {
save = storage.StartLiveHand
}
if err := save(user, hand); err != nil {
if errors.Is(err, storage.ErrHandInProgress) {
// Somebody was already sitting here. This hand was never seated, so the
// chips it staked go back: the player is in one hand, not two.
_ = storage.Award(user, st.Bet)
writeJSONStatus(w, http.StatusConflict, map[string]string{"error": "you're already in a hand"})
return
}
slog.Error("games: save hand", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if st.Phase == blackjack.PhaseDone {
// Pay first, then clear. If Pete dies between the two, the player has been
// paid and the worst case is a settled hand still showing on the felt —
// which reads as done and can be cleared. The other order loses them a win.
if err := storage.Award(user, st.Payout); err != nil {
slog.Error("games: award", "user", user, "payout", st.Payout, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
if err := storage.RecordHand(storage.Hand{
MatrixUser: user, Game: "blackjack",
Bet: st.Bet, Payout: st.Payout, Rake: st.Rake,
Outcome: string(st.Outcome), Seed1: seed1, Seed2: seed2,
}); err != nil {
slog.Error("games: record hand", "user", user, "err", err) // audit only; don't fail the player's hand
}
if err := storage.ClearLiveHand(user); err != nil {
slog.Error("games: clear hand", "user", user, "err", err)
}
}
storage.Touch(user)
v, err := s.table(user)
if err != nil {
slog.Error("games: table", "user", user, "err", err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// A settled hand is gone from storage, so the table view has no hand to show —
// but the browser still needs the final cards to animate the reveal onto.
if st.Phase == blackjack.PhaseDone {
hv := viewHand(st)
v.Hand = &hv
}
v.Events = viewEvents(evs, st.Phase)
writeJSON(w, v)
}
// newSeeds mints the shoe's seed. It goes in the audit log, so a hand somebody
// disputes can be dealt again exactly as it fell.
func newSeeds() (uint64, uint64) {
return rand.Uint64(), uint64(time.Now().UnixNano())
}
func writeJSONStatus(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(v); err != nil {
slog.Error("games: write response", "err", err)
}
}

View File

@@ -0,0 +1,275 @@
package web
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"pete/internal/config"
"pete/internal/storage"
)
const testPlayer = "@reala:parodia.dev"
// newCasino is a server with the tables open and one signed-in player. The
// Authenticator is built by hand rather than through OIDC discovery: sign-in is
// a network call, and none of what's under test is about the handshake.
func newCasino(t *testing.T) *Server {
t.Helper()
s, _ := newAdvServer(t, "tok")
s.auth = &Authenticator{secret: []byte("test-secret-key-at-least-16")}
s.cfg.Games = config.GamesConfig{Enabled: true, MatrixServer: "parodia.dev"}
return s
}
// as returns a request carrying the signed session of the given username. An
// empty username is the pre-casino session: signed in, but nobody the economy
// can name.
func as(t *testing.T, s *Server, username, method, path string, body any) *http.Request {
t.Helper()
var buf bytes.Buffer
if body != nil {
if err := json.NewEncoder(&buf).Encode(body); err != nil {
t.Fatal(err)
}
}
r := httptest.NewRequest(method, path, &buf)
payload, _ := json.Marshal(SessionUser{
Sub: "sub-1", Username: username, Exp: time.Now().Add(time.Hour).Unix(),
})
r.AddCookie(&http.Cookie{Name: sessionCookie, Value: s.auth.sign(payload)})
return r
}
// call runs one request against a handler and decodes the table view.
func call(t *testing.T, s *Server, h http.HandlerFunc, r *http.Request) (tableView, int) {
t.Helper()
w := httptest.NewRecorder()
h(w, r)
var v tableView
if w.Code == 200 {
if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil {
t.Fatalf("decode table: %v (body %q)", err, w.Body.String())
}
}
return v, w.Code
}
// fund puts chips in front of the player the way the border really does it.
func fund(t *testing.T, chips int64) {
t.Helper()
e, err := storage.RequestBuyIn(testPlayer, chips)
if err != nil {
t.Fatal(err)
}
if _, err := storage.ClaimEscrow(e.GUID); err != nil {
t.Fatal(err)
}
if _, err := storage.SettleEscrow(e.GUID, true, "", 0); err != nil {
t.Fatal(err)
}
}
func chipsNow(t *testing.T) int64 {
t.Helper()
st, err := storage.Chips(testPlayer)
if err != nil {
t.Fatal(err)
}
return st.Chips
}
// TestDealTakesTheStakeAndHidesTheHoleCard is the one thing the table cannot get
// wrong: the bet leaves the stack, and the dealer's second card does not leave
// the server.
func TestDealTakesTheStakeAndHidesTheHoleCard(t *testing.T) {
s := newCasino(t)
fund(t, 1000)
v, code := call(t, s, s.handleDeal, as(t, s, "reala", "POST", "/api/games/blackjack/deal", map[string]int64{"bet": 100}))
if code != 200 {
t.Fatalf("deal = %d, want 200", code)
}
if v.Chips != 900 {
t.Fatalf("chips after a 100 bet = %d, want 900", v.Chips)
}
if v.Hand == nil {
t.Fatal("deal returned no hand")
}
if len(v.Hand.Player) != 2 {
t.Fatalf("player was dealt %d cards, want 2", len(v.Hand.Player))
}
// A natural settles on the spot and legitimately shows both dealer cards.
if v.Hand.Phase == "done" {
return
}
if !v.Hand.Hole || len(v.Hand.Dealer) != 1 {
t.Fatalf("dealer shows %d cards (hole=%v), want 1 with the hole card held back",
len(v.Hand.Dealer), v.Hand.Hole)
}
// And it isn't smuggled out in the dealing script either.
for _, e := range v.Events {
if e.Kind == "dealer_hole" && e.Card != nil {
t.Fatal("the hole card's face went to the browser in the events")
}
}
}
// TestHandSettlesIntoTheChipStack plays a hand to the end and checks the chips
// moved by exactly what the engine said they did — and that the hand left the
// felt and landed in the audit log.
func TestHandSettlesIntoTheChipStack(t *testing.T) {
s := newCasino(t)
fund(t, 1000)
v, _ := call(t, s, s.handleDeal, as(t, s, "reala", "POST", "/deal", map[string]int64{"bet": 100}))
for v.Hand != nil && v.Hand.Phase == "player" {
v, _ = call(t, s, s.handleMove, as(t, s, "reala", "POST", "/move", map[string]string{"move": "stand"}))
}
if v.Hand == nil || v.Hand.Phase != "done" {
t.Fatalf("hand didn't finish: %+v", v.Hand)
}
// 1000, minus the stake, plus whatever came back.
want := int64(1000) - 100 + v.Hand.Payout
if got := chipsNow(t); got != want {
t.Fatalf("chips = %d, want %d (payout %d, outcome %q)", got, want, v.Hand.Payout, v.Hand.Outcome)
}
if _, err := storage.LoadLiveHand(testPlayer); err == nil {
t.Fatal("a settled hand is still sitting on the felt")
}
if v.Hand.Outcome == "" {
t.Fatal("a finished hand with no outcome")
}
// The rake only ever comes out of winnings.
if v.Hand.Outcome == "push" && v.Hand.Payout != 100 {
t.Fatalf("a push paid %d, want the 100 back untouched", v.Hand.Payout)
}
if v.Hand.Net < 0 && v.Hand.Rake != 0 {
t.Fatalf("a losing hand was raked %d", v.Hand.Rake)
}
}
// TestOneHandAtATime is the double-click: a second Deal must not overwrite the
// hand the first one is paying for, and must not keep the chips it staked.
func TestOneHandAtATime(t *testing.T) {
s := newCasino(t)
fund(t, 1000)
first, _ := call(t, s, s.handleDeal, as(t, s, "reala", "POST", "/deal", map[string]int64{"bet": 100}))
if first.Hand != nil && first.Hand.Phase == "done" {
t.Skip("dealt a natural; there is no live hand to protect")
}
before := chipsNow(t)
w := httptest.NewRecorder()
s.handleDeal(w, as(t, s, "reala", "POST", "/deal", map[string]int64{"bet": 100}))
if w.Code != http.StatusConflict {
t.Fatalf("second deal = %d, want 409", w.Code)
}
if got := chipsNow(t); got != before {
t.Fatalf("the refused deal cost the player %d chips", before-got)
}
// The original hand is untouched.
live, err := storage.LoadLiveHand(testPlayer)
if err != nil {
t.Fatalf("the live hand went missing: %v", err)
}
var st struct {
Player []struct{} `json:"player"`
}
if err := json.Unmarshal(live.State, &st); err != nil {
t.Fatal(err)
}
if len(st.Player) != len(first.Hand.Player) {
t.Fatal("the refused deal replaced the hand in progress")
}
}
// TestCannotCashOutMidHand — the stake is on the table, so the session it would
// settle into cannot be closed underneath it.
func TestCannotCashOutMidHand(t *testing.T) {
s := newCasino(t)
fund(t, 1000)
v, _ := call(t, s, s.handleDeal, as(t, s, "reala", "POST", "/deal", map[string]int64{"bet": 100}))
if v.Hand != nil && v.Hand.Phase == "done" {
t.Skip("dealt a natural; nothing is in progress")
}
w := httptest.NewRecorder()
s.handleCashOut(w, as(t, s, "reala", "POST", "/cashout", map[string]int64{"amount": 0}))
if w.Code != http.StatusConflict {
t.Fatalf("cash-out mid-hand = %d, want 409", w.Code)
}
if got := chipsNow(t); got != 900 {
t.Fatalf("the refused cash-out moved chips: %d, want 900", got)
}
}
// TestDoubleWithoutTheChipsChangesNothing: a double the player can't cover is
// refused, and refusing it must not quietly pocket the raise.
func TestDoubleWithoutTheChipsChangesNothing(t *testing.T) {
s := newCasino(t)
fund(t, 100)
v, _ := call(t, s, s.handleDeal, as(t, s, "reala", "POST", "/deal", map[string]int64{"bet": 100}))
if v.Hand == nil || v.Hand.Phase != "player" {
t.Skip("no live hand to double on")
}
if chipsNow(t) != 0 {
t.Fatal("test wants a player with nothing left to raise with")
}
w := httptest.NewRecorder()
s.handleMove(w, as(t, s, "reala", "POST", "/move", map[string]string{"move": "double"}))
if w.Code != http.StatusBadRequest {
t.Fatalf("broke double = %d, want 400", w.Code)
}
if got := chipsNow(t); got != 0 {
t.Fatalf("chips = %d after a refused double, want 0", got)
}
// And the hand is still there, still doubleable once they can afford it.
after, code := call(t, s, s.handleTable, as(t, s, "reala", "GET", "/table", nil))
if code != 200 || after.Hand == nil || !after.Hand.Double {
t.Fatalf("the hand should be intact and still doubleable: %d %+v", code, after.Hand)
}
}
// TestTableNeedsAPlayerTheEconomyCanName. Anonymous is a 401. A session minted
// before the casino existed carries no username, so it can't be mapped to a
// Matrix id — that's a 403, and the fix is to sign in again.
func TestTableNeedsAPlayerTheEconomyCanName(t *testing.T) {
s := newCasino(t)
w := httptest.NewRecorder()
s.handleTable(w, httptest.NewRequest("GET", "/api/games/table", nil))
if w.Code != http.StatusUnauthorized {
t.Fatalf("anonymous = %d, want 401", w.Code)
}
w = httptest.NewRecorder()
s.handleTable(w, as(t, s, "", "GET", "/api/games/table", nil))
if w.Code != http.StatusForbidden {
t.Fatalf("session with no username = %d, want 403", w.Code)
}
}
// TestCasinoIsShutWithoutAServerName. No Matrix server name means no player can
// be named to gogobee, so the tables 404 rather than dealing hands whose money
// has nowhere to go.
func TestCasinoIsShutWithoutAServerName(t *testing.T) {
s := newCasino(t)
s.cfg.Games.MatrixServer = ""
w := httptest.NewRecorder()
s.handleTable(w, as(t, s, "reala", "GET", "/api/games/table", nil))
if w.Code != http.StatusNotFound {
t.Fatalf("table with no server name = %d, want 404", w.Code)
}
}

View File

@@ -9,6 +9,7 @@ import (
"io/fs"
"log/slog"
"net/http"
"strings"
"sync"
"time"
@@ -81,12 +82,13 @@ type Server struct {
// gets its own template set sharing layout.html + _card.html, which avoids
// `main` define collisions between pages.
func New(cfg config.WebConfig, sources []config.SourceConfig, postingEnabled bool, adv config.AdventureConfig, advPost PriorityPoster) (*Server, error) {
pages := []string{"index", "channel", "weather", "bookmarks", "for-you", "status", "story"}
pages := []string{"index", "channel", "weather", "bookmarks", "for-you", "status", "story", "games", "blackjack"}
tpls := make(map[string]*template.Template, len(pages))
for _, p := range pages {
t, err := template.New("").Funcs(funcs).ParseFS(templateFS,
"templates/layout.html",
"templates/_card.html",
"templates/_chipbar.html",
"templates/"+p+".html",
)
if err != nil {
@@ -210,6 +212,19 @@ func New(cfg config.WebConfig, sources []config.SourceConfig, postingEnabled boo
mux.HandleFunc("POST /api/games/escrow/claim", s.handleEscrowClaim)
mux.HandleFunc("POST /api/games/escrow/settled", s.handleEscrowSettled)
// The casino. Signed-in only — there is money in it — so these hang off the
// auth block, and gamesReady() also insists on a Matrix server name: without
// one, no player can be named to gogobee's ledger and the tables stay shut.
if s.gamesReady() {
mux.HandleFunc("GET /games", s.handleLobby)
mux.HandleFunc("GET /games/blackjack", s.handleBlackjack)
mux.HandleFunc("GET /api/games/table", s.handleTable)
mux.HandleFunc("POST /api/games/buyin", s.handleBuyIn)
mux.HandleFunc("POST /api/games/cashout", s.handleCashOut)
mux.HandleFunc("POST /api/games/blackjack/deal", s.handleDeal)
mux.HandleFunc("POST /api/games/blackjack/move", s.handleMove)
}
if s.auth != nil {
mux.HandleFunc("GET /auth/login", s.auth.handleLogin)
mux.HandleFunc("GET /auth/callback", s.auth.handleCallback)
@@ -232,12 +247,56 @@ func New(cfg config.WebConfig, sources []config.SourceConfig, postingEnabled boo
s.srv = &http.Server{
Addr: cfg.ListenAddr,
Handler: mux,
Handler: s.hostRouter(mux),
ReadHeaderTimeout: 5 * time.Second,
}
return s, nil
}
// hostRouter puts the casino at the root of its own hostname without giving it
// its own mux. games.parodia.dev and news.parodia.dev are the same process on
// the same port — Caddy sends both here — so a request that arrives on the games
// host has /games prefixed onto its path, and "/" lands on the lobby.
//
// Shared plumbing (the API, sign-in, static files, health) is left alone: it is
// the same plumbing whichever door you came in by, and the login round-trip in
// particular has to keep working on both hosts.
func (s *Server) hostRouter(mux http.Handler) http.Handler {
host := strings.ToLower(strings.TrimSpace(s.cfg.Games.Host))
if host == "" || !s.gamesReady() {
return mux
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.EqualFold(hostOnly(r.Host), host) || isSharedPath(r.URL.Path) {
mux.ServeHTTP(w, r)
return
}
// Rewrite a copy: the request's URL is shared with anything that logged it.
r2 := r.Clone(r.Context())
r2.URL.Path = "/games" + strings.TrimSuffix(r.URL.Path, "/")
mux.ServeHTTP(w, r2)
})
}
// isSharedPath marks the paths that mean the same thing on every host and must
// not be shuffled under /games.
func isSharedPath(p string) bool {
for _, prefix := range []string{"/api/", "/auth/", "/static/", "/img/", "/games"} {
if strings.HasPrefix(p, prefix) {
return true
}
}
return p == "/healthz" || p == "/sw.js" || p == "/manifest.webmanifest"
}
// hostOnly strips the port from a Host header.
func hostOnly(host string) string {
if i := strings.IndexByte(host, ':'); i >= 0 {
return host[:i]
}
return host
}
// Start runs the HTTP server and blocks until ctx is canceled.
func (s *Server) Start(ctx context.Context) {
go func() {

View File

@@ -527,4 +527,132 @@ html[data-phase="night"] {
font-size: 0.8rem;
font-weight: 700;
}
/* ---- the casino ---------------------------------------------------------
Cards are dealt, not swapped in: each one starts at the shoe in the corner,
flies to its place, and turns over. The whole point of the table is that you
watch it happen, so this is written as one animation per card with a delay,
and the JS just says which cards exist and in what order. */
.pete-felt {
background:
radial-gradient(120% 90% at 50% -10%, rgba(255,255,255,0.10), transparent 60%),
linear-gradient(160deg, #2f7d5b 0%, #24614a 55%, #1c4d3c 100%);
}
/* The shoe: where every card comes from. */
.pete-shoe {
position: absolute;
top: 1.25rem;
right: 1.25rem;
height: 4.2rem;
width: 3rem;
border-radius: 0.55rem;
background: linear-gradient(150deg, #b4553f, #8d3f2f);
border: 2px solid rgba(0,0,0,0.18);
box-shadow: 0 4px 0 rgba(0,0,0,0.18), inset 0 0 0 3px rgba(255,255,255,0.12);
}
.pete-shoe::after {
content: "";
position: absolute;
inset: 0.45rem 0.4rem auto 0.4rem;
height: 0.5rem;
border-radius: 0.2rem;
background: rgba(0,0,0,0.22);
}
.pete-hand {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
min-height: 6.6rem;
}
/* One card. The wrapper does the flight, the inner face does the flip, so the
two never fight over the same transform. */
.pete-card {
perspective: 700px;
height: 6.4rem;
width: 4.5rem;
animation: pete-deal 0.42s cubic-bezier(0.22, 1, 0.36, 1) backwards;
}
.pete-card-inner {
position: relative;
height: 100%;
width: 100%;
transform-style: preserve-3d;
transition: transform 0.45s cubic-bezier(0.4, 0, 0.2, 1);
}
/* Face-down is the resting state of a card that hasn't been turned over: the
hole card sits like this until the dealer plays. */
.pete-card[data-face="down"] .pete-card-inner { transform: rotateY(180deg); }
.pete-card-front,
.pete-card-back {
position: absolute;
inset: 0;
display: grid;
border-radius: 0.55rem;
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
box-shadow: 0 3px 0 rgba(0,0,0,0.18), 0 6px 14px rgba(0,0,0,0.22);
}
.pete-card-front {
place-items: center;
background: #fdfaf2;
border: 2px solid rgba(30,20,10,0.12);
color: #2b2118;
font-family: "Fredoka", "Nunito", system-ui, sans-serif;
line-height: 1;
}
.pete-card-front[data-red="1"] { color: #cc3d4a; }
.pete-card-back {
transform: rotateY(180deg);
background:
repeating-linear-gradient(45deg, rgba(255,255,255,0.10) 0 6px, transparent 6px 12px),
linear-gradient(150deg, #b4553f, #8d3f2f);
border: 2px solid rgba(0,0,0,0.15);
}
.pete-card-rank { font-size: 1.5rem; font-weight: 700; }
.pete-card-suit { font-size: 1.15rem; margin-top: 0.1rem; }
/* The flight itself: out of the shoe (up and to the right), scaled down and
spinning slightly, into place. */
@keyframes pete-deal {
from {
opacity: 0;
transform: translate(var(--deal-x, 14rem), var(--deal-y, -7rem)) scale(0.72) rotate(9deg);
}
to {
opacity: 1;
transform: translate(0, 0) scale(1) rotate(0);
}
}
/* A settled hand: the winning side gets a little lift, so a win reads at a
glance rather than only in the text. */
.pete-hand[data-won="1"] .pete-card { animation: pete-deal 0.42s cubic-bezier(0.22,1,0.36,1) backwards, pete-win 0.6s ease 0.1s; }
@keyframes pete-win {
0%, 100% { transform: translateY(0); }
40% { transform: translateY(-0.6rem); }
}
/* Chips: the denominations you bet with. */
.pete-chip {
background: radial-gradient(circle at 50% 35%, rgba(255,255,255,0.28), transparent 60%), var(--chip, #e07a5f);
border: 3px dashed rgba(255,255,255,0.55);
box-shadow: 0 3px 0 rgba(60,40,20,0.22), 0 6px 14px rgba(60,40,20,0.18);
}
.pete-chip[data-chip="5"] { --chip: #5aa9e6; }
.pete-chip[data-chip="25"] { --chip: #4caf7d; }
.pete-chip[data-chip="100"] { --chip: #2b2118; }
.pete-chip[data-chip="500"] { --chip: #b079d6; }
.pete-chip[aria-pressed="true"] { outline: 3px solid var(--accent); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
.pete-card { animation: none; }
.pete-card-inner { transition: none; }
.pete-hand[data-won="1"] .pete-card { animation: none; }
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,302 @@
// The blackjack table.
//
// The browser holds no game. It sends intents — deal, hit, stand, double — and
// the server answers with the cards you're allowed to see plus the *script* of
// how they got there: one event per card off the shoe, in the order the shoe
// gave them up. This file's job is to play that script back at a human speed
// rather than snapping the finished hand into place.
//
// Which is also why the hole card works the way it does: the server sends a
// "dealer_hole" event with no card attached, because while you are still acting
// it hasn't told anyone what that card is. It arrives with the reveal.
(function () {
"use strict";
var root = document.querySelector("[data-blackjack]");
if (!root) return;
var dealerEl = root.querySelector("[data-dealer]");
var playerEl = root.querySelector("[data-player]");
var dTotalEl = root.querySelector("[data-dealer-total]");
var pTotalEl = root.querySelector("[data-player-total]");
var betChip = root.querySelector("[data-bet]");
var verdictEl = root.querySelector("[data-verdict]");
var betting = root.querySelector("[data-betting]");
var actions = root.querySelector("[data-actions]");
var betAmount = root.querySelector("[data-bet-amount]");
var dealBtn = root.querySelector("[data-deal]");
var msgEl = root.querySelector("[data-table-msg]");
var bet = 25;
var busy = false; // a request is in flight, or cards are still landing
var hand = null; // the hand as the server last described it
var DEAL_MS = 380; // one card's flight, and the gap before the next
var FLIP_MS = 450;
var reduced = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function pace(ms) { return reduced ? 0 : ms; }
function wait(ms) { return new Promise(function (r) { setTimeout(r, pace(ms)); }); }
function say(text, tone) {
if (!text) { msgEl.classList.add("hidden"); return; }
msgEl.textContent = text;
msgEl.classList.remove("hidden");
msgEl.style.color = tone === "bad" ? "#cc3d4a" : "";
}
// ---- drawing --------------------------------------------------------------
// cardEl builds one card. face === null means face-down: the card is dealt,
// but this browser has not been told what it is.
function cardEl(face) {
var wrap = document.createElement("div");
wrap.className = "pete-card";
wrap.dataset.face = face ? "up" : "down";
// Every card flies out of the shoe, which sits in the top-right of the felt.
// The offset is per-card, so a card landing further left flies further.
wrap.style.setProperty("--deal-x", "14rem");
wrap.style.setProperty("--deal-y", "-6rem");
var inner = document.createElement("div");
inner.className = "pete-card-inner";
var front = document.createElement("div");
front.className = "pete-card-front";
var back = document.createElement("div");
back.className = "pete-card-back";
inner.appendChild(front);
inner.appendChild(back);
wrap.appendChild(inner);
if (face) paintFace(front, face);
return wrap;
}
function paintFace(front, face) {
front.dataset.red = face.red ? "1" : "0";
front.innerHTML = "";
var rank = document.createElement("span");
rank.className = "pete-card-rank";
rank.textContent = face.rank;
var suit = document.createElement("span");
suit.className = "pete-card-suit";
suit.textContent = face.suit;
front.appendChild(rank);
front.appendChild(suit);
front.setAttribute("aria-label", face.label);
}
// turnOver flips a face-down card up, now that we've been told what it is.
function turnOver(wrap, face) {
if (!wrap) return;
paintFace(wrap.querySelector(".pete-card-front"), face);
wrap.dataset.face = "up";
}
function totals(v) {
if (v.total) {
pTotalEl.textContent = v.total + (v.soft ? " (soft)" : "");
pTotalEl.classList.remove("hidden");
} else {
pTotalEl.classList.add("hidden");
}
// While the hole card is down, the dealer's total is only what's showing —
// so say so, rather than printing a number that quietly means something else.
if (v.dealer && v.dealer.length) {
dTotalEl.textContent = v.hole ? v.dealer_total + " showing" : String(v.dealer_total);
dTotalEl.classList.remove("hidden");
} else {
dTotalEl.classList.add("hidden");
}
}
// paint puts a hand on the felt with no animation. This is the resume path:
// you reloaded, or Pete restarted, and your cards are simply there.
function paint(v) {
dealerEl.innerHTML = "";
playerEl.innerHTML = "";
if (!v) { setPhase(null); return; }
v.player.forEach(function (c) { playerEl.appendChild(cardEl(c)); });
v.dealer.forEach(function (c) { dealerEl.appendChild(cardEl(c)); });
if (v.hole) dealerEl.appendChild(cardEl(null));
totals(v);
setPhase(v);
}
var VERDICTS = {
blackjack: "Blackjack! 🎉",
win: "You win!",
dealer_bust: "Dealer busts. You win!",
lose: "Dealer takes it.",
bust: "Bust.",
push: "Push — your bet comes back.",
};
function verdict(v) {
var text = VERDICTS[v.outcome] || "";
if (!text) { verdictEl.classList.add("hidden"); return; }
if (v.net > 0) text += " +" + v.net.toLocaleString();
else if (v.net < 0) text += " " + v.net.toLocaleString();
verdictEl.textContent = text;
verdictEl.classList.remove("hidden");
playerEl.dataset.won = v.net > 0 ? "1" : "0";
}
// setPhase swaps the controls: bet between hands, act during one.
function setPhase(v) {
hand = v;
var live = !!v && v.phase === "player";
betting.classList.toggle("hidden", live);
actions.classList.toggle("hidden", !live);
if (v && v.bet) {
betChip.textContent = "Bet " + v.bet.toLocaleString();
betChip.classList.remove("hidden");
} else {
betChip.classList.add("hidden");
}
if (live) {
var dbl = actions.querySelector('[data-move="double"]');
if (dbl) dbl.disabled = !v.can_double;
}
if (!v || v.phase !== "player") verdictEl.classList.toggle("hidden", !(v && v.outcome));
}
// ---- the script -----------------------------------------------------------
// play walks the server's events, one card at a time. It is deliberately the
// only thing that renders during a hand: the final state is applied at the end,
// so what you watch and what the server says can't disagree halfway through.
function play(view) {
var events = view.events || [];
var final = view.hand;
var hole = null; // the face-down card element, once one has been dealt
var chain = Promise.resolve();
events.forEach(function (e) {
chain = chain.then(function () {
switch (e.kind) {
case "deal":
dealerEl.innerHTML = "";
playerEl.innerHTML = "";
playerEl.dataset.won = "0";
verdictEl.classList.add("hidden");
return;
case "player_card":
playerEl.appendChild(cardEl(e.card));
return wait(DEAL_MS);
case "dealer_card":
dealerEl.appendChild(cardEl(e.card));
return wait(DEAL_MS);
case "dealer_hole":
hole = cardEl(null);
dealerEl.appendChild(hole);
return wait(DEAL_MS);
case "reveal":
// The hole card turns over. Its face is in the final hand — this is
// the first moment the server has been willing to say what it was.
if (!hole) hole = dealerEl.querySelector('.pete-card[data-face="down"]');
if (hole && final && final.dealer && final.dealer[1]) {
turnOver(hole, final.dealer[1]);
}
return wait(FLIP_MS);
case "settle":
return;
}
});
});
return chain.then(function () {
if (final) {
totals(final);
setPhase(final);
if (final.phase === "done") verdict(final);
} else {
paint(null);
}
});
}
// ---- talking to the table -------------------------------------------------
function send(path, body) {
if (busy) return;
busy = true;
say("");
return window.PeteGames.post(path, body)
.then(function (view) {
window.PeteGames.apply(view);
return play(view);
})
.catch(function (err) {
say(err.message, "bad");
// Whatever we thought was on the felt, the server is the authority on it.
return window.PeteGames.refresh();
})
.then(function () { busy = false; });
}
// ---- betting --------------------------------------------------------------
function showBet() {
betAmount.textContent = bet.toLocaleString();
var money = window.PeteGames.view();
if (dealBtn) dealBtn.disabled = bet <= 0 || !money || money.chips < bet;
}
root.querySelectorAll("[data-chip]").forEach(function (btn) {
btn.addEventListener("click", function () {
bet += parseInt(btn.dataset.chip, 10);
showBet();
});
});
var clearBtn = root.querySelector("[data-bet-clear]");
if (clearBtn) {
clearBtn.addEventListener("click", function () { bet = 0; showBet(); });
}
if (dealBtn) {
dealBtn.addEventListener("click", function () {
if (bet <= 0) { say("Put something on it first.", "bad"); return; }
send("/api/games/blackjack/deal", { bet: bet });
});
}
root.querySelectorAll("[data-move]").forEach(function (btn) {
btn.addEventListener("click", function () {
send("/api/games/blackjack/move", { move: btn.dataset.move });
});
});
document.addEventListener("keydown", function (e) {
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (/^(input|textarea|select)$/i.test((e.target.tagName || ""))) return;
if (!hand || hand.phase !== "player" || busy) return;
var move = { h: "hit", s: "stand", d: "double" }[e.key.toLowerCase()];
if (!move) return;
if (move === "double" && !hand.can_double) return;
e.preventDefault();
send("/api/games/blackjack/move", { move: move });
});
// The money bar owns the first fetch; the table picks up whatever it found,
// including a hand left sitting on the felt by a reload or a redeploy.
var resumed = false;
window.PeteGames.onUpdate(function (v) {
if (!resumed) {
resumed = true;
if (v.hand) paint(v.hand);
if (v.hand && v.hand.phase === "done") verdict(v.hand);
}
showBet();
});
})();

View File

@@ -0,0 +1,160 @@
// The money bar: chips, wallet, buying in, cashing out.
//
// Buying chips is not instant and cannot be. gogobee owns the euros and has no
// inbound API, so it polls Pete for the crossing, moves the money on its side,
// and pushes the verdict back — a few seconds, end to end. So the button does
// not lie about it: the chips show as "buying" until they are real, and this
// file polls until they are. Nothing spendable appears until gogobee has said
// it took the euros.
//
// Exposed as window.PeteGames so the table (blackjack.js) shares one view of
// the money rather than keeping a second copy that drifts from this one.
(function () {
"use strict";
var bar = document.querySelector("[data-chipbar]");
if (!bar) return;
var chipsEl = bar.querySelector("[data-chips]");
var pendingEl = bar.querySelector("[data-pending]");
var eurosEl = bar.querySelector("[data-euros]");
var amountEl = bar.querySelector("[data-buyin-amount]");
var buyBtn = bar.querySelector("[data-buyin]");
var cashBtn = bar.querySelector("[data-cashout]");
var msgEl = bar.querySelector("[data-chipbar-msg]");
var listeners = [];
var view = null;
var pollTimer = null;
var pollUntil = 0;
function money(n) {
return (n || 0).toLocaleString();
}
function say(text, tone) {
if (!msgEl) return;
if (!text) { msgEl.classList.add("hidden"); return; }
msgEl.textContent = text;
msgEl.classList.remove("hidden");
msgEl.style.color = tone === "bad" ? "#cc3d4a" : "";
}
function paint(v) {
view = v;
if (chipsEl) chipsEl.textContent = money(v.chips);
if (eurosEl) eurosEl.textContent = (v.euros || 0).toFixed(2);
if (pendingEl) {
if (v.pending > 0) {
pendingEl.textContent = "+" + money(v.pending) + " buying…";
pendingEl.classList.remove("hidden");
} else {
pendingEl.classList.add("hidden");
}
}
// You cannot cash out mid-hand: the stake is already on the table.
if (cashBtn) cashBtn.disabled = v.chips <= 0 || !!v.hand;
if (buyBtn) buyBtn.disabled = v.chips + v.pending >= v.cap;
listeners.forEach(function (fn) { fn(v); });
}
// pollPending keeps asking while a buy-in is in flight, and stops the moment
// it lands — or is refused, which looks the same from here (pending drops to
// zero) and is told apart by whether the chips arrived.
function pollPending() {
clearTimeout(pollTimer);
if (Date.now() > pollUntil) {
say("gogobee hasn't answered yet. Your euros are safe — give it a moment and reload.");
return;
}
pollTimer = setTimeout(function () {
get().then(function (v) {
if (!v) return;
if (v.pending > 0) { pollPending(); return; }
if (v.chips > (pollPending.was || 0)) {
say("Chips are yours. Good luck!");
} else {
say("gogobee wouldn't cover that — not enough euros in your wallet.", "bad");
}
});
}, 1200);
}
function request(path, body) {
return fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body || {}),
}).then(function (res) {
return res.json().catch(function () { return {}; }).then(function (data) {
if (!res.ok) throw new Error(data.error || "that didn't work");
return data;
});
});
}
function get() {
return fetch("/api/games/table", { headers: { "Accept": "application/json" } })
.then(function (res) { return res.ok ? res.json() : null; })
.then(function (v) { if (v) paint(v); return v; })
.catch(function () { return null; });
}
if (buyBtn) {
buyBtn.addEventListener("click", function () {
var amount = parseInt(amountEl && amountEl.value, 10);
if (!(amount > 0)) { say("How many chips?", "bad"); return; }
buyBtn.disabled = true;
say("Asking gogobee for " + money(amount) + " euros…");
pollPending.was = view ? view.chips : 0;
request("/api/games/buyin", { amount: amount })
.then(function (v) {
paint(v);
pollUntil = Date.now() + 60000;
pollPending();
})
.catch(function (err) {
say(err.message, "bad");
buyBtn.disabled = false;
});
});
}
if (cashBtn) {
cashBtn.addEventListener("click", function () {
cashBtn.disabled = true;
say("Cashing you out…");
request("/api/games/cashout", { amount: 0 })
.then(function (v) {
paint(v);
say("Chips are on their way back to euros. They'll show in your wallet shortly.");
// The euro balance Pete shows is whatever gogobee last told it, so it
// only moves once the credit has actually gone through over there.
setTimeout(get, 4000);
})
.catch(function (err) {
say(err.message, "bad");
cashBtn.disabled = false;
});
});
}
window.PeteGames = {
// onUpdate registers a listener called on every fresh view of the money.
onUpdate: function (fn) { listeners.push(fn); if (view) fn(view); },
// apply pushes a view the table already fetched (a deal answers with one),
// so playing a hand doesn't need a second round-trip to refresh the chips.
apply: paint,
refresh: get,
post: request,
say: say,
view: function () { return view; },
};
get();
})();

View File

@@ -0,0 +1,45 @@
{{define "_chipbar"}}
<section data-chipbar
class="rounded-3xl bg-[color:var(--card)] p-5 sm:p-6 shadow-pete border-2 border-[color:var(--ink)]/10">
<div class="flex flex-wrap items-center gap-x-6 gap-y-4">
<div class="min-w-0">
<div class="text-xs font-semibold uppercase tracking-wider text-[color:var(--ink)]/50">Chips in front of you</div>
<div class="flex items-baseline gap-2">
<span data-chips class="font-display text-3xl font-bold tabular-nums"></span>
<span data-pending class="hidden text-sm font-semibold text-[color:var(--ink)]/60 animate-pulse"></span>
</div>
</div>
<div class="min-w-0">
<div class="text-xs font-semibold uppercase tracking-wider text-[color:var(--ink)]/50">Your wallet</div>
<div class="flex items-baseline gap-1.5">
<span data-euros class="font-display text-2xl font-bold tabular-nums text-[color:var(--ink)]/70"></span>
<span class="text-sm text-[color:var(--ink)]/40" title="Pete reads this off the game box every couple of minutes, so it lags a little.">€, give or take</span>
</div>
</div>
<div class="ml-auto flex flex-wrap items-center gap-2">
<div class="flex items-center gap-1.5 rounded-full bg-[color:var(--ink)]/5 p-1.5">
<label for="buyin-amount" class="sr-only">How many chips?</label>
<input id="buyin-amount" data-buyin-amount type="number" min="1" step="1" value="100"
inputmode="numeric" enterkeyhint="go"
class="w-24 rounded-full bg-[color:var(--card)] px-3 py-1.5 text-sm font-semibold tabular-nums
border-2 border-[color:var(--ink)]/10 focus:outline-none focus:border-[color:var(--accent)]">
<button type="button" data-buyin
class="rounded-full bg-[color:var(--accent)] px-4 py-1.5 text-sm font-bold text-white shadow-pete
hover:brightness-105 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
Buy chips
</button>
</div>
<button type="button" data-cashout
class="rounded-full bg-[color:var(--card)] px-4 py-2 text-sm font-bold shadow-pete border-2 border-[color:var(--ink)]/10
hover:bg-[color:var(--ink)]/5 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
Cash out
</button>
</div>
</div>
<p data-chipbar-msg class="hidden mt-3 rounded-2xl bg-[color:var(--ink)]/5 px-4 py-2 text-sm font-semibold"></p>
</section>
{{end}}

View File

@@ -0,0 +1,113 @@
{{define "title"}}Blackjack · Pete's Casino{{end}}
{{define "main"}}
<div class="space-y-6" data-blackjack>
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-3 min-w-0">
<a href="/games" class="grid h-10 w-10 shrink-0 place-items-center rounded-full bg-[color:var(--card)] shadow-pete border-2 border-[color:var(--ink)]/10 hover:bg-[color:var(--ink)]/5 transition" title="Back to the casino">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-5 w-5" aria-hidden="true">
<path d="M19 12H5"></path><polyline points="12 19 5 12 12 5"></polyline>
</svg>
<span class="sr-only">Back to the casino</span>
</a>
<h1 class="font-display text-3xl font-bold">Blackjack</h1>
</div>
<p class="text-sm text-[color:var(--ink)]/50">Six decks · pays 3:2 · dealer hits soft 17</p>
</div>
{{template "_chipbar" .}}
<!-- The felt. -->
<section class="pete-felt relative overflow-hidden rounded-3xl p-6 sm:p-10 shadow-pete-lg border-2 border-[color:var(--ink)]/10">
<!-- The shoe every card flies out of. -->
<div class="pete-shoe" aria-hidden="true"></div>
<div class="relative space-y-8">
<!-- Dealer -->
<div>
<div class="mb-2 flex items-center gap-2">
<span class="text-xs font-bold uppercase tracking-wider text-white/60">Dealer</span>
<span data-dealer-total class="hidden rounded-full bg-black/25 px-2.5 py-0.5 text-xs font-bold tabular-nums text-white"></span>
</div>
<div data-dealer class="pete-hand" aria-live="polite"></div>
</div>
<!-- What just happened. -->
<div class="flex min-h-[2.75rem] items-center justify-center">
<p data-verdict class="hidden rounded-full bg-white/95 px-5 py-2 font-display text-lg font-bold shadow-pete"></p>
</div>
<!-- Player -->
<div>
<div class="mb-2 flex items-center gap-2">
<span class="text-xs font-bold uppercase tracking-wider text-white/60">You</span>
<span data-player-total class="hidden rounded-full bg-black/25 px-2.5 py-0.5 text-xs font-bold tabular-nums text-white"></span>
<span data-bet class="hidden ml-auto rounded-full bg-[color:var(--accent)] px-3 py-0.5 text-xs font-bold tabular-nums text-white"></span>
</div>
<div data-player class="pete-hand" aria-live="polite"></div>
</div>
</div>
</section>
<!-- Betting: shown between hands. -->
<section data-betting class="rounded-3xl bg-[color:var(--card)] p-5 sm:p-6 shadow-pete border-2 border-[color:var(--ink)]/10">
<div class="flex flex-wrap items-center gap-x-6 gap-y-4">
<div>
<div class="text-xs font-semibold uppercase tracking-wider text-[color:var(--ink)]/50">Your bet</div>
<div class="font-display text-3xl font-bold tabular-nums"><span data-bet-amount>25</span></div>
</div>
<div class="flex flex-wrap items-center gap-2">
{{range .Denominations}}
<button type="button" data-chip="{{.}}"
class="pete-chip h-12 w-12 rounded-full font-display text-sm font-bold text-white shadow-pete
hover:-translate-y-0.5 active:translate-y-0 transition">{{.}}</button>
{{end}}
<button type="button" data-bet-clear
class="rounded-full px-3 py-2 text-sm font-semibold text-[color:var(--ink)]/50 hover:text-[color:var(--ink)] transition">Clear</button>
</div>
<button type="button" data-deal
class="ml-auto rounded-full bg-[color:var(--accent)] px-8 py-3 font-display text-lg font-bold text-white shadow-pete
hover:brightness-105 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
Deal
</button>
</div>
<p data-table-msg class="hidden mt-3 rounded-2xl bg-[color:var(--ink)]/5 px-4 py-2 text-sm font-semibold"></p>
</section>
<!-- Playing: shown while a hand is live. -->
<section data-actions class="hidden rounded-3xl bg-[color:var(--card)] p-5 sm:p-6 shadow-pete border-2 border-[color:var(--ink)]/10">
<div class="flex flex-wrap items-center justify-center gap-3">
<button type="button" data-move="hit"
class="rounded-full bg-[color:var(--accent)] px-8 py-3 font-display text-lg font-bold text-white shadow-pete
hover:brightness-105 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
Hit
</button>
<button type="button" data-move="stand"
class="rounded-full bg-[color:var(--card)] px-8 py-3 font-display text-lg font-bold shadow-pete border-2 border-[color:var(--ink)]/10
hover:bg-[color:var(--ink)]/5 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
Stand
</button>
<button type="button" data-move="double"
class="rounded-full bg-[color:var(--card)] px-8 py-3 font-display text-lg font-bold shadow-pete border-2 border-[color:var(--ink)]/10
hover:bg-[color:var(--ink)]/5 active:translate-y-px disabled:opacity-40 disabled:pointer-events-none transition">
Double
</button>
</div>
<p class="mt-3 text-center text-xs text-[color:var(--ink)]/40">
<kbd>h</kbd> hit · <kbd>s</kbd> stand · <kbd>d</kbd> double
</p>
</section>
</div>
{{end}}
{{define "scripts"}}
<script src="/static/js/games.js" defer></script>
<script src="/static/js/blackjack.js" defer></script>
{{end}}

View File

@@ -0,0 +1,72 @@
{{define "title"}}Pete's Casino · {{.SiteTitle}}{{end}}
{{define "main"}}
<div class="space-y-8">
<section class="rounded-3xl bg-[color:var(--card)] p-6 sm:p-8 shadow-pete border-2 border-[color:var(--ink)]/10">
<div class="flex flex-wrap items-start justify-between gap-4">
<div class="min-w-0">
<h1 class="font-display text-3xl sm:text-4xl font-bold">Pete's Casino 🎲</h1>
<p class="mt-2 text-[color:var(--ink)]/70">
Real euros, from the same wallet as everything else. Chips are one euro each,
and whatever you don't spend goes straight back when you cash out.
</p>
</div>
<img src="/static/img/pete.avif" alt="" width="72" height="72"
class="hidden sm:block h-18 w-18 shrink-0 rounded-2xl object-cover shadow-pete border-2 border-[color:var(--ink)]/10">
</div>
</section>
{{template "_chipbar" .}}
<section>
<h2 class="font-display text-2xl font-bold mb-4">The tables</h2>
<div class="grid gap-4 sm:grid-cols-2">
<a href="/games/blackjack"
class="group rounded-3xl bg-[color:var(--card)] p-6 shadow-pete border-2 border-[color:var(--ink)]/10 hover:-translate-y-0.5 hover:shadow-pete-lg transition">
<div class="flex items-center gap-3">
<span class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-[color:var(--accent)]/25 text-2xl">🃏</span>
<div class="min-w-0">
<h3 class="font-display text-xl font-bold">Blackjack</h3>
<p class="text-sm text-[color:var(--ink)]/60">Six decks, blackjack pays 3:2.</p>
</div>
<span class="ml-auto shrink-0 rounded-full bg-theme-gaming px-3 py-1 text-xs font-bold uppercase tracking-wider text-white">Open</span>
</div>
<p class="mt-4 text-sm text-[color:var(--ink)]/70">
The dealer stands on 17 and hits a soft one. House takes {{.RakePct}}% of what you win,
and nothing at all when you lose or push.
</p>
</a>
{{range .Soon}}
<div class="rounded-3xl bg-[color:var(--card)]/60 p-6 shadow-pete border-2 border-dashed border-[color:var(--ink)]/15">
<div class="flex items-center gap-3">
<span class="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-[color:var(--ink)]/5 text-2xl grayscale">{{.Emoji}}</span>
<div class="min-w-0">
<h3 class="font-display text-xl font-bold text-[color:var(--ink)]/50">{{.Name}}</h3>
<p class="text-sm text-[color:var(--ink)]/40">{{.Blurb}}</p>
</div>
<span class="ml-auto shrink-0 rounded-full border-2 border-[color:var(--ink)]/10 px-3 py-1 text-xs font-bold uppercase tracking-wider text-[color:var(--ink)]/40">Soon</span>
</div>
</div>
{{end}}
</div>
</section>
<section class="rounded-3xl bg-[color:var(--card)] p-6 shadow-pete border-2 border-[color:var(--ink)]/10">
<h2 class="font-display text-xl font-bold mb-2">House rules</h2>
<ul class="space-y-1.5 text-sm text-[color:var(--ink)]/70">
<li>· A chip is a euro. Nothing is worth more here than it is out there.</li>
<li>· You can have {{.Cap}} chips in front of you at most. That's the limit for one sitting.</li>
<li>· The house takes {{.RakePct}}% of your winnings. Never your stake: a push hands your bet straight back.</li>
<li>· Walk away for half an hour and Pete cashes you out on his own, so your euros never sit in limbo.</li>
<li>· Every hand is logged with the seed it was dealt from, so any hand can be dealt again exactly as it fell.</li>
</ul>
</section>
</div>
{{end}}
{{define "scripts"}}<script src="/static/js/games.js" defer></script>{{end}}

View File

@@ -322,5 +322,6 @@
<script src="/static/js/settings.js" defer></script>
<script src="/static/js/reader.js" defer></script>
<script src="/static/js/pwa.js" defer></script>
{{block "scripts" .}}{{end}}
</body>
</html>{{end}}

View File

@@ -8,7 +8,7 @@ This plan reuses that seam wholesale and does not invent a second one.
---
## 0. Progress — last updated 2026-07-13
## 0. Progress — last updated 2026-07-14
A multi-session build. This section is the handover; read it before anything else.
@@ -58,17 +58,49 @@ A multi-session build. This section is the handover; read it before anything els
gogobee crash replays as a no-op: 13 tests across both repos, including a fake
Pete that offers the same row three times and a player who is charged once.
- **Identity.** `preferred_username` now rides in the signed session, and
`SessionUser.MatrixUser(server)` maps it to `@user:parodia.dev`. The session cookie
takes an opt-in `web.auth.cookie_domain`, so a sign-in on news is a sign-in on games;
the OAuth round-trip cookie deliberately stays host-only, and the redirect_uri is
derived per-request so a login that starts on games comes back to games. A Host we
don't own is never echoed into a redirect. *(pete `cb84e1d`)*
- **Blackjack, playable end to end.** `game_live_hands` (the hand in progress,
engine state and all, so a redeploy mid-hand is survivable), the session-authed play
surface (`internal/web/games_play.go`), the lobby and table pages, and the dealing
animation. Driven in a real browser: chips staked before the deal, hole card withheld
from the payload until the reveal, payout settled back into the stack.
### Next, in order
1. **Identity.** `PreferredUsername` into the OIDC claims struct and the signed cookie;
cookie `Domain: ".parodia.dev"` so a news session travels to games. Add the games
redirect URI to the `pete` app in Authentik.
2. **Frontend.** Host branching in the mux, lobby + blackjack table, animated dealing.
Nothing yet *opens* an escrow row from a browser — `RequestBuyIn`/`RequestCashOut`
have no HTTP surface, on purpose: they need a signed-in Matrix identity, which is
step 1.
1. **Make the table lively.** The mechanics are all there and the dealing animates, but
the presentation is thin: card faces are a rank and a small suit (no pips, no corner
indices), chips never physically move, and nothing celebrates. This is a *stated
requirement*, not polish — see the decisions above. Ideas already sketched: chips that
fly to a bet spot and back on a win, cards landing with weight, a dealer beat before
drawing out, a burst on a natural.
2. **Deploy.** Add the `games.parodia.dev` redirect URI to the `pete` app in Authentik,
point Caddy at the same port, set `[web.games]` + `web.auth.cookie_domain` on the
server. Nothing else is host-specific.
3. Then Phase 2 (trivia, hangman), 3 (UNO), 4 (hold'em) as below.
### How the browser half fits together
- `GET /games` (lobby), `GET /games/blackjack` (table) — signed-in only. On the games
host, the mux prefixes `/games` onto the path, so the lobby is that host's `/`. Shared
paths (`/api/`, `/auth/`, `/static/`) mean the same thing on every host and are left
alone.
- `GET /api/games/table`, `POST /api/games/{buyin,cashout}`,
`POST /api/games/blackjack/{deal,move}` — session-authed, JSON, all returning the same
`tableView` so the money and the felt can never disagree.
- **The browser never sees the shoe.** The dealer's hole card is *absent* from the
payload — not flagged hidden — until the reveal, and the deck lives only in
`game_live_hands`. The response carries the engine's events (one per card off the
shoe), which is what the table plays back as an animation.
- Money order-of-operations: stake leaves the stack *before* the hand is dealt, in the
same statement that checks it's there; the hand is *seated* (a plain INSERT on the
primary key) before it can settle, which is what makes a double-clicked Deal a 409 with
the stake refunded rather than a silently overwritten hand.
### Notes for whoever picks this up
- SQLite runs at `MaxOpenConns(1)` in *both* repos. Any `db.Get().Exec` inside an