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
+122
View File
@@ -0,0 +1,122 @@
package game
// BattleUnit is a pet on the battle line with its attached foods applied.
// Power (attack) is unaffected by damage; a unit dies when Damage >= Power.
type BattleUnit struct {
Card Card `json:"card"`
Foods []Card `json:"foods"`
Bonus int `json:"bonus"` // total power added by foods
Damage int `json:"damage"` // damage markers accumulated this battle
}
func (u *BattleUnit) Power() int { return u.Card.Power + u.Bonus }
func (u *BattleUnit) Alive() bool { return u.Damage < u.Power() }
// BattleEvent is one step of the battle, in order, for clients to animate.
type BattleEvent struct {
Type string `json:"type"` // "clash"
// Indexes into the initial lineups (per seat) of the two front pets.
Units []int `json:"units"` // one entry per seat
// Damage each front pet has accumulated after the clash, per seat.
Damage []int `json:"damage"`
// Whether each front pet died in the clash, per seat.
Died []bool `json:"died"`
}
// BattleResult is the full, public record of one round's battle.
type BattleResult struct {
Round int `json:"round"`
Lineups [][]BattleUnit `json:"lineups"` // initial lineups per seat
WastedFood [][]Card `json:"wastedFoods"` // foods with no pet beneath them, per seat
Events []BattleEvent `json:"events"`
WinnerSeat int `json:"winnerSeat"` // -1 = draw
Trophies int `json:"trophies"` // awarded to the winner
}
// buildLineup walks a deck top-to-bottom, attaching each run of foods to the
// next pet below it. Foods after the last pet affect nothing and are wasted.
func buildLineup(deck []Card) (units []BattleUnit, wasted []Card) {
var pendingFoods []Card
for _, c := range deck {
if c.IsFood() {
pendingFoods = append(pendingFoods, c)
continue
}
u := BattleUnit{Card: c, Foods: pendingFoods}
for _, f := range pendingFoods {
if f.Food == FoodApple {
u.Bonus++
}
}
pendingFoods = nil
units = append(units, u)
}
return units, pendingFoods
}
// resolveBattle simulates the battle from the players' arranged decks,
// records the event log, awards trophies, and moves to PhaseBattle.
//
// Combat: the two front pets deal their full Power to each other
// simultaneously as damage markers. A pet with Damage >= Power dies. Since
// remaining health never exceeds Power, at least one pet dies every clash,
// so the loop always terminates (until effects say otherwise).
func (g *Game) resolveBattle() {
res := &BattleResult{
Round: g.Round,
Lineups: make([][]BattleUnit, len(g.Players)),
WastedFood: make([][]Card, len(g.Players)),
WinnerSeat: -1,
}
live := make([][]BattleUnit, len(g.Players)) // working copies
front := make([]int, len(g.Players)) // index of each seat's front pet
for _, p := range g.Players {
units, wasted := buildLineup(p.Deck)
res.Lineups[p.Seat] = units
res.WastedFood[p.Seat] = wasted
live[p.Seat] = append([]BattleUnit(nil), units...)
}
// Two-player combat. Effects and >2 player battle formats come later;
// the surrounding state (lineups, events) is already per-seat.
a, b := 0, 1
for front[a] < len(live[a]) && front[b] < len(live[b]) {
ua, ub := &live[a][front[a]], &live[b][front[b]]
ua.Damage += ub.Power()
ub.Damage += ua.Power()
ev := BattleEvent{
Type: "clash",
Units: []int{front[a], front[b]},
Damage: []int{ua.Damage, ub.Damage},
Died: []bool{!ua.Alive(), !ub.Alive()},
}
res.Events = append(res.Events, ev)
if !ua.Alive() {
front[a]++
}
if !ub.Alive() {
front[b]++
}
}
trophies := 1
if g.Round == MaxRounds {
trophies = 2
}
switch {
case front[a] < len(live[a]):
res.WinnerSeat = a
case front[b] < len(live[b]):
res.WinnerSeat = b
}
if res.WinnerSeat >= 0 {
res.Trophies = trophies
g.Players[res.WinnerSeat].Trophies += trophies
}
g.Battle = res
g.Phase = PhaseBattle
for _, p := range g.Players {
p.Ready = false
}
}
+156
View File
@@ -0,0 +1,156 @@
package game
import "testing"
// testGame builds a started 2-player game without going through the lobby.
func testGame(t *testing.T) (*Game, *Player, *Player) {
t.Helper()
g := New()
p1, err := g.AddPlayer("Alice")
if err != nil {
t.Fatal(err)
}
p2, err := g.AddPlayer("Bob")
if err != nil {
t.Fatal(err)
}
if g.Phase != PhaseShop {
t.Fatalf("expected shop phase after both players join, got %s", g.Phase)
}
return g, p1, p2
}
func (g *Game) pet(name string, power int) Card {
return Card{ID: g.newCardID(), Kind: KindPet, Name: name, Tier: 1, Power: power, Suit: SuitSun}
}
// forceBattle sets both decks, arranges them in current order, and resolves.
func forceBattle(t *testing.T, g *Game, d1, d2 []Card) *BattleResult {
t.Helper()
g.Players[0].Deck = d1
g.Players[1].Deck = d2
g.Phase = PhaseArrange
g.Players[0].Ready = false
g.Players[1].Ready = false
for _, p := range g.Players {
ids := make([]string, len(p.Deck))
for i, c := range p.Deck {
ids[i] = c.ID
}
if err := g.SubmitOrder(p.ID, ids); err != nil {
t.Fatal(err)
}
}
if g.Phase != PhaseBattle {
t.Fatalf("expected battle phase, got %s", g.Phase)
}
return g.Battle
}
// The worked example from the rules: a 3-power pet fights a 5-power pet. The
// 3 dies, the 5 survives with 3 damage markers (2 health left, 5 attack).
// Then a 2-power pet trades with it: both die.
func TestBattleDamageMarkers(t *testing.T) {
g, _, _ := testGame(t)
res := forceBattle(t, g,
[]Card{g.pet("Three", 3), g.pet("Two", 2)},
[]Card{g.pet("Five", 5)},
)
if len(res.Events) != 2 {
t.Fatalf("expected 2 clashes, got %d", len(res.Events))
}
first := res.Events[0]
if !first.Died[0] || first.Died[1] {
t.Fatalf("first clash: 3-power should die, 5-power should survive: %+v", first)
}
if first.Damage[1] != 3 {
t.Fatalf("5-power pet should carry 3 damage, has %d", first.Damage[1])
}
second := res.Events[1]
if !second.Died[0] || !second.Died[1] {
t.Fatalf("second clash: both should die (5 attack kills the 2; 3+2 damage kills the 5): %+v", second)
}
if res.WinnerSeat != -1 {
t.Fatalf("battle should be a draw, winner=%d", res.WinnerSeat)
}
if g.Players[0].Trophies != 0 || g.Players[1].Trophies != 0 {
t.Fatal("no trophies on a draw")
}
}
func TestBattleEqualPowerBothDie(t *testing.T) {
g, _, _ := testGame(t)
res := forceBattle(t, g,
[]Card{g.pet("A", 4)},
[]Card{g.pet("B", 4)},
)
ev := res.Events[0]
if !ev.Died[0] || !ev.Died[1] {
t.Fatalf("equal power pets should both die: %+v", ev)
}
if res.WinnerSeat != -1 {
t.Fatal("expected a draw")
}
}
func TestBattleWinnerGetsTrophy(t *testing.T) {
g, _, p2 := testGame(t)
res := forceBattle(t, g,
[]Card{g.pet("Small", 1)},
[]Card{g.pet("Big", 5)},
)
if res.WinnerSeat != 1 {
t.Fatalf("seat 1 should win, got %d", res.WinnerSeat)
}
if res.Trophies != 1 || p2.Trophies != 1 {
t.Fatalf("round 1 win should award 1 trophy, got %d/%d", res.Trophies, p2.Trophies)
}
}
func TestBattleFinalRoundWorthTwoTrophies(t *testing.T) {
g, _, p2 := testGame(t)
g.Round = MaxRounds
res := forceBattle(t, g,
[]Card{g.pet("Small", 1)},
[]Card{g.pet("Big", 5)},
)
if res.Trophies != 2 || p2.Trophies != 2 {
t.Fatalf("final round win should award 2 trophies, got %d/%d", res.Trophies, p2.Trophies)
}
}
// Foods stack onto the next pet beneath them; each apple adds 1 power.
// Trailing foods with no pet under them are wasted.
func TestBattleApplesBuffNextPet(t *testing.T) {
g, _, _ := testGame(t)
apple1, apple2, apple3 := g.newApple(), g.newApple(), g.newApple()
res := forceBattle(t, g,
[]Card{apple1, apple2, g.pet("Buffed", 3), apple3}, // 3+2=5 power; apple3 wasted
[]Card{g.pet("Enemy", 5)},
)
u := res.Lineups[0][0]
if u.Bonus != 2 || u.Power() != 5 {
t.Fatalf("expected 2 apples for 5 total power, got bonus=%d power=%d", u.Bonus, u.Power())
}
if len(res.WastedFood[0]) != 1 || res.WastedFood[0][0].ID != apple3.ID {
t.Fatalf("trailing apple should be wasted: %+v", res.WastedFood[0])
}
if res.WinnerSeat != -1 {
t.Fatal("5 vs 5 should draw")
}
}
// A player with an empty lineup loses immediately with zero clashes.
func TestBattleEmptyLineupLoses(t *testing.T) {
g, _, _ := testGame(t)
res := forceBattle(t, g,
[]Card{g.pet("Solo", 1)},
[]Card{g.newApple()}, // food only, no pets
)
if len(res.Events) != 0 {
t.Fatalf("expected no clashes, got %d", len(res.Events))
}
if res.WinnerSeat != 0 {
t.Fatalf("seat 0 should win by default, got %d", res.WinnerSeat)
}
}
+120
View File
@@ -0,0 +1,120 @@
package game
import "fmt"
// Suit is the trade-in symbol printed on pet cards. Three pets of the same
// suit can be traded for a pick of the next tier's deck.
type Suit string
const (
SuitSun Suit = "sun"
SuitMoon Suit = "moon"
SuitStar Suit = "star"
SuitLeaf Suit = "leaf"
)
var suits = []Suit{SuitSun, SuitMoon, SuitStar, SuitLeaf}
// CardKind distinguishes pets from foods.
type CardKind string
const (
KindPet CardKind = "pet"
KindFood CardKind = "food"
)
// Food identifiers. Only apples exist for now; more foods come later.
const FoodApple = "apple"
// Card is a single physical card instance. IDs are unique per game.
type Card struct {
ID string `json:"id"`
Kind CardKind `json:"kind"`
Name string `json:"name"`
Tier int `json:"tier"`
Power int `json:"power,omitempty"`
Suit Suit `json:"suit,omitempty"`
// Effect is display text for the pet's ability. Effects are not yet
// implemented mechanically; the field keeps card data forward-compatible.
Effect string `json:"effect,omitempty"`
Food string `json:"food,omitempty"`
}
func (c Card) IsPet() bool { return c.Kind == KindPet }
func (c Card) IsFood() bool { return c.Kind == KindFood }
// petTemplate is the printed definition of a pet; each template appears as
// multiple card copies in its tier's shop deck.
type petTemplate struct {
Name string
Power int
}
const copiesPerPet = 2
// petTiers defines the shop decks. Index 0 is tier 1 (round 1) through
// index 5 for tier 6 (round 6). Suits are assigned round-robin per tier so
// every tier contains every suit.
var petTiers = [MaxRounds][]petTemplate{
{ // Tier 1
{"Ant", 1}, {"Cricket", 1}, {"Fish", 2}, {"Horse", 1},
{"Beaver", 2}, {"Otter", 1}, {"Pig", 3}, {"Mosquito", 2},
},
{ // Tier 2
{"Crab", 3}, {"Swan", 2}, {"Hedgehog", 3}, {"Peacock", 4},
{"Flamingo", 3}, {"Rat", 2}, {"Shrimp", 2}, {"Spider", 3},
},
{ // Tier 3
{"Dog", 4}, {"Badger", 4}, {"Camel", 3}, {"Giraffe", 3},
{"Kangaroo", 4}, {"Ox", 5}, {"Rabbit", 3}, {"Sheep", 4},
},
{ // Tier 4
{"Skunk", 5}, {"Hippo", 6}, {"Bison", 6}, {"Deer", 4},
{"Squirrel", 4}, {"Whale", 5}, {"Worm", 4}, {"Penguin", 5},
},
{ // Tier 5
{"Scorpion", 5}, {"Rhino", 7}, {"Monkey", 6}, {"Cow", 6},
{"Seal", 6}, {"Shark", 7}, {"Turkey", 5}, {"Crocodile", 8},
},
{ // Tier 6
{"Leopard", 8}, {"Boar", 9}, {"Fly", 7}, {"Gorilla", 9},
{"Mammoth", 10}, {"Snake", 8}, {"Tiger", 9}, {"Dragon", 10},
},
}
// newCardID mints a unique card ID within the game.
func (g *Game) newCardID() string {
g.NextCardID++
return fmt.Sprintf("c%d", g.NextCardID)
}
// buildShopDecks creates all six tier decks (unshuffled).
func (g *Game) buildShopDecks() {
g.ShopDecks = make([][]Card, MaxRounds)
for tierIdx, templates := range petTiers {
deck := make([]Card, 0, len(templates)*copiesPerPet)
for i, t := range templates {
for range copiesPerPet {
deck = append(deck, Card{
ID: g.newCardID(),
Kind: KindPet,
Name: t.Name,
Tier: tierIdx + 1,
Power: t.Power,
Suit: suits[i%len(suits)],
})
}
}
g.ShopDecks[tierIdx] = deck
}
}
// newApple mints an apple food card (from discarding, etc.).
func (g *Game) newApple() Card {
return Card{
ID: g.newCardID(),
Kind: KindFood,
Name: "Apple",
Food: FoodApple,
}
}
+533
View File
@@ -0,0 +1,533 @@
package game
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"math/big"
"slices"
)
// Tunable rules. The engine supports any player count >= 2; MinPlayers /
// MaxPlayers gate when a lobby can start (2 for now, more later).
const (
MaxRounds = 6
CoinsPerRound = 3
ShopRowSize = 4
MaxPets = 5
TradeInCount = 3
MinPlayers = 2
MaxPlayers = 2
)
// Phase is the game's top-level state.
type Phase string
const (
PhaseLobby Phase = "lobby" // waiting for players
PhaseShop Phase = "shop" // players take turns spending coins
PhaseCleanup Phase = "cleanup" // forced discard down to MaxPets pets
PhaseArrange Phase = "arrange" // players order their decks for battle
PhaseBattle Phase = "battle" // battle resolved; players review the log
PhaseGameOver Phase = "gameover" // all rounds played
)
// Player holds everything about one seat. All fields are exported so a Game
// serializes to JSON for persistence.
type Player struct {
ID string `json:"id"`
Token string `json:"token"` // secret; never sent in views
Name string `json:"name"`
Seat int `json:"seat"`
Coins int `json:"coins"`
Deck []Card `json:"deck"`
Trophies int `json:"trophies"`
Ready bool `json:"ready"` // arrange submitted / battle acknowledged
Connected bool `json:"connected"`
}
// PetCount counts pet cards in the player's deck.
func (p *Player) PetCount() int {
n := 0
for _, c := range p.Deck {
if c.IsPet() {
n++
}
}
return n
}
func (p *Player) cardIndex(cardID string) int {
return slices.IndexFunc(p.Deck, func(c Card) bool { return c.ID == cardID })
}
// PendingTrade is an in-progress trade-in: the trading player has paid and
// must now pick one of two revealed cards from the next tier's deck.
type PendingTrade struct {
PlayerID string `json:"playerId"`
Tier int `json:"tier"` // 1-based tier the options came from
Options [2]Card `json:"options"`
}
// Game is the complete authoritative state. It is a pure state machine: no
// goroutines, no clocks, no I/O. Callers are responsible for locking.
type Game struct {
ID string `json:"id"`
Code string `json:"code"`
Phase Phase `json:"phase"`
Round int `json:"round"` // 1-based
Players []*Player `json:"players"`
ShopDecks [][]Card `json:"shopDecks"` // index 0 = tier 1
ShopRow []Card `json:"shopRow"` // empty ID = empty slot
Turn int `json:"turn"` // seat with the current shop turn
Pending *PendingTrade `json:"pending,omitempty"`
Battle *BattleResult `json:"battle,omitempty"` // most recent battle
NextCardID int `json:"nextCardId"`
WinnerSeat int `json:"winnerSeat"` // set at gameover; -1 = tie
}
var (
ErrNotYourTurn = errors.New("not your turn")
ErrWrongPhase = errors.New("action not allowed in this phase")
ErrNoCoins = errors.New("no coins remaining")
ErrInvalidAction = errors.New("invalid action")
)
func randomID(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return hex.EncodeToString(b)
}
func randomCode() string {
const letters = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" // no easily-confused chars
code := make([]byte, 5)
for i := range code {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
panic(err)
}
code[i] = letters[n.Int64()]
}
return string(code)
}
func randInt(n int) int {
v, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
if err != nil {
panic(err)
}
return int(v.Int64())
}
func shuffle[T any](s []T) {
for i := len(s) - 1; i > 0; i-- {
j := randInt(i + 1)
s[i], s[j] = s[j], s[i]
}
}
// New creates a game in the lobby phase with its shop decks built and
// shuffled. All later "randomness" is just drawing from these decks, so the
// state is fully deterministic (and serializable) after this point.
func New() *Game {
g := &Game{
ID: randomID(16),
Code: randomCode(),
Phase: PhaseLobby,
WinnerSeat: -1,
}
g.buildShopDecks()
for i := range g.ShopDecks {
shuffle(g.ShopDecks[i])
}
return g
}
// AddPlayer seats a new player during the lobby phase and returns them (with
// their secret token). The game starts automatically once full.
func (g *Game) AddPlayer(name string) (*Player, error) {
if g.Phase != PhaseLobby {
return nil, fmt.Errorf("%w: game already started", ErrWrongPhase)
}
if len(g.Players) >= MaxPlayers {
return nil, errors.New("game is full")
}
if name == "" {
name = fmt.Sprintf("Player %d", len(g.Players)+1)
}
p := &Player{
ID: randomID(8),
Token: randomID(16),
Name: name,
Seat: len(g.Players),
}
g.Players = append(g.Players, p)
if len(g.Players) == MaxPlayers {
g.start()
}
return p, nil
}
// PlayerByID returns the player, or nil.
func (g *Game) PlayerByID(id string) *Player {
for _, p := range g.Players {
if p.ID == id {
return p
}
}
return nil
}
func (g *Game) start() {
g.Round = 1
g.startShopRound()
}
// startShopRound resets coins, deals the shop row from this round's tier
// deck, and rotates the starting player.
func (g *Game) startShopRound() {
g.Phase = PhaseShop
g.Pending = nil
for _, p := range g.Players {
p.Coins = CoinsPerRound
p.Ready = false
}
g.ShopRow = make([]Card, ShopRowSize)
for i := range g.ShopRow {
g.ShopRow[i] = g.drawFromTier(g.Round)
}
g.Turn = (g.Round - 1) % len(g.Players)
}
// drawFromTier pops the top card of the given tier's deck (1-based tier).
// Returns a zero Card if the deck is empty.
func (g *Game) drawFromTier(tier int) Card {
deck := g.ShopDecks[tier-1]
if len(deck) == 0 {
return Card{}
}
top := deck[0]
g.ShopDecks[tier-1] = deck[1:]
return top
}
// requireShopTurn validates that playerID may act in the shop right now.
func (g *Game) requireShopTurn(playerID string) (*Player, error) {
if g.Phase != PhaseShop {
return nil, ErrWrongPhase
}
p := g.PlayerByID(playerID)
if p == nil {
return nil, errors.New("unknown player")
}
if g.Players[g.Turn].ID != playerID {
return nil, ErrNotYourTurn
}
if g.Pending != nil {
return nil, fmt.Errorf("%w: finish your trade first", ErrInvalidAction)
}
if p.Coins <= 0 {
return nil, ErrNoCoins
}
return p, nil
}
// Buy spends one coin to take the card at rowIdx into the player's deck.
// The slot refills from the current round's tier deck.
func (g *Game) Buy(playerID string, rowIdx int) error {
p, err := g.requireShopTurn(playerID)
if err != nil {
return err
}
if rowIdx < 0 || rowIdx >= len(g.ShopRow) || g.ShopRow[rowIdx].ID == "" {
return fmt.Errorf("%w: no card in that shop slot", ErrInvalidAction)
}
p.Coins--
p.Deck = append(p.Deck, g.ShopRow[rowIdx])
g.ShopRow[rowIdx] = g.drawFromTier(g.Round)
g.advanceShopTurn()
return nil
}
// Discard spends one coin to convert any number (>=1) of the player's cards
// into that many apples.
func (g *Game) Discard(playerID string, cardIDs []string) error {
p, err := g.requireShopTurn(playerID)
if err != nil {
return err
}
if len(cardIDs) == 0 {
return fmt.Errorf("%w: choose at least one card to discard", ErrInvalidAction)
}
if err := g.convertToApples(p, cardIDs); err != nil {
return err
}
p.Coins--
g.advanceShopTurn()
return nil
}
// convertToApples removes the given cards from p's deck and adds one apple
// per removed card. It validates before mutating.
func (g *Game) convertToApples(p *Player, cardIDs []string) error {
if hasDuplicates(cardIDs) {
return fmt.Errorf("%w: duplicate card", ErrInvalidAction)
}
for _, id := range cardIDs {
if p.cardIndex(id) < 0 {
return fmt.Errorf("%w: card not in your deck", ErrInvalidAction)
}
}
for _, id := range cardIDs {
p.Deck = slices.Delete(p.Deck, p.cardIndex(id), p.cardIndex(id)+1)
}
for range cardIDs {
p.Deck = append(p.Deck, g.newApple())
}
return nil
}
// TradeStart spends one coin and three same-suit pets from the player's deck
// to reveal the top two cards of the next tier's deck. The player must then
// call TradeChoose before anything else happens.
func (g *Game) TradeStart(playerID string, cardIDs []string) error {
p, err := g.requireShopTurn(playerID)
if err != nil {
return err
}
if g.Round >= MaxRounds {
return fmt.Errorf("%w: no higher tier to trade into", ErrInvalidAction)
}
if len(cardIDs) != TradeInCount || hasDuplicates(cardIDs) {
return fmt.Errorf("%w: trade in exactly %d cards", ErrInvalidAction, TradeInCount)
}
var suit Suit
for i, id := range cardIDs {
idx := p.cardIndex(id)
if idx < 0 {
return fmt.Errorf("%w: card not in your deck", ErrInvalidAction)
}
c := p.Deck[idx]
if !c.IsPet() {
return fmt.Errorf("%w: only pets have suits", ErrInvalidAction)
}
if i == 0 {
suit = c.Suit
} else if c.Suit != suit {
return fmt.Errorf("%w: cards must share a suit", ErrInvalidAction)
}
}
nextTier := g.Round + 1
if len(g.ShopDecks[nextTier-1]) < 2 {
return fmt.Errorf("%w: next tier deck is exhausted", ErrInvalidAction)
}
// Validated; commit.
for _, id := range cardIDs {
p.Deck = slices.Delete(p.Deck, p.cardIndex(id), p.cardIndex(id)+1)
}
p.Coins--
g.Pending = &PendingTrade{
PlayerID: playerID,
Tier: nextTier,
Options: [2]Card{g.drawFromTier(nextTier), g.drawFromTier(nextTier)},
}
return nil
}
// TradeChoose resolves a pending trade: pick (0 or 1) joins the player's
// deck, the other goes to the bottom of its tier deck.
func (g *Game) TradeChoose(playerID string, pick int) error {
if g.Phase != PhaseShop || g.Pending == nil || g.Pending.PlayerID != playerID {
return fmt.Errorf("%w: no trade waiting on you", ErrInvalidAction)
}
if pick != 0 && pick != 1 {
return fmt.Errorf("%w: pick 0 or 1", ErrInvalidAction)
}
p := g.PlayerByID(playerID)
chosen, other := g.Pending.Options[pick], g.Pending.Options[1-pick]
p.Deck = append(p.Deck, chosen)
tierIdx := g.Pending.Tier - 1
g.ShopDecks[tierIdx] = append(g.ShopDecks[tierIdx], other)
g.Pending = nil
g.advanceShopTurn()
return nil
}
// Pass forfeits the player's remaining coins and ends their shopping.
func (g *Game) Pass(playerID string) error {
p, err := g.requireShopTurn(playerID)
if err != nil {
return err
}
p.Coins = 0
g.advanceShopTurn()
return nil
}
// advanceShopTurn hands the turn to the next player who still has coins, or
// moves the game onward when everyone is spent.
func (g *Game) advanceShopTurn() {
for i := 1; i <= len(g.Players); i++ {
seat := (g.Turn + i) % len(g.Players)
if g.Players[seat].Coins > 0 {
g.Turn = seat
return
}
}
g.endShop()
}
// endShop moves to forced discard if anyone is over the pet limit, otherwise
// straight to arranging.
func (g *Game) endShop() {
over := false
for _, p := range g.Players {
p.Ready = p.PetCount() <= MaxPets
if !p.Ready {
over = true
}
}
if over {
g.Phase = PhaseCleanup
return
}
g.beginArrange()
}
// CleanupDiscard performs the forced end-of-shop discard: the player must
// convert exactly their excess pets into apples.
func (g *Game) CleanupDiscard(playerID string, cardIDs []string) error {
if g.Phase != PhaseCleanup {
return ErrWrongPhase
}
p := g.PlayerByID(playerID)
if p == nil {
return errors.New("unknown player")
}
excess := p.PetCount() - MaxPets
if excess <= 0 {
return fmt.Errorf("%w: you are not over the pet limit", ErrInvalidAction)
}
if len(cardIDs) != excess {
return fmt.Errorf("%w: discard exactly %d pets", ErrInvalidAction, excess)
}
for _, id := range cardIDs {
idx := p.cardIndex(id)
if idx < 0 || !p.Deck[idx].IsPet() {
return fmt.Errorf("%w: pick pets from your deck", ErrInvalidAction)
}
}
if err := g.convertToApples(p, cardIDs); err != nil {
return err
}
p.Ready = true
if g.allReady() {
g.beginArrange()
}
return nil
}
func (g *Game) allReady() bool {
for _, p := range g.Players {
if !p.Ready {
return false
}
}
return true
}
func (g *Game) beginArrange() {
g.Phase = PhaseArrange
for _, p := range g.Players {
p.Ready = false
}
}
// SubmitOrder records the player's battle ordering (a permutation of their
// deck's card IDs, top of deck first). When everyone has submitted, the
// battle resolves.
func (g *Game) SubmitOrder(playerID string, orderedIDs []string) error {
if g.Phase != PhaseArrange {
return ErrWrongPhase
}
p := g.PlayerByID(playerID)
if p == nil {
return errors.New("unknown player")
}
if p.Ready {
return fmt.Errorf("%w: order already submitted", ErrInvalidAction)
}
if len(orderedIDs) != len(p.Deck) || hasDuplicates(orderedIDs) {
return fmt.Errorf("%w: order must include each of your cards exactly once", ErrInvalidAction)
}
ordered := make([]Card, 0, len(p.Deck))
for _, id := range orderedIDs {
idx := p.cardIndex(id)
if idx < 0 {
return fmt.Errorf("%w: card not in your deck", ErrInvalidAction)
}
ordered = append(ordered, p.Deck[idx])
}
p.Deck = ordered
p.Ready = true
if g.allReady() {
g.resolveBattle()
}
return nil
}
// AcknowledgeBattle marks the player done reviewing the battle. When all
// players acknowledge, the next round starts (or the game ends).
func (g *Game) AcknowledgeBattle(playerID string) error {
if g.Phase != PhaseBattle {
return ErrWrongPhase
}
p := g.PlayerByID(playerID)
if p == nil {
return errors.New("unknown player")
}
p.Ready = true
if !g.allReady() {
return nil
}
if g.Round >= MaxRounds {
g.finish()
return nil
}
g.Round++
g.startShopRound()
return nil
}
func (g *Game) finish() {
g.Phase = PhaseGameOver
best, bestSeat, tie := -1, -1, false
for _, p := range g.Players {
switch {
case p.Trophies > best:
best, bestSeat, tie = p.Trophies, p.Seat, false
case p.Trophies == best:
tie = true
}
}
if tie {
g.WinnerSeat = -1
} else {
g.WinnerSeat = bestSeat
}
}
func hasDuplicates(ids []string) bool {
seen := make(map[string]struct{}, len(ids))
for _, id := range ids {
if _, ok := seen[id]; ok {
return true
}
seen[id] = struct{}{}
}
return false
}
+335
View File
@@ -0,0 +1,335 @@
package game
import (
"testing"
)
func deckIDs(p *Player, filter func(Card) bool) []string {
var ids []string
for _, c := range p.Deck {
if filter == nil || filter(c) {
ids = append(ids, c.ID)
}
}
return ids
}
func current(g *Game) *Player { return g.Players[g.Turn] }
func TestLobbyStartsWhenFull(t *testing.T) {
g := New()
if g.Phase != PhaseLobby {
t.Fatalf("new game should be in lobby, got %s", g.Phase)
}
if _, err := g.AddPlayer("Alice"); err != nil {
t.Fatal(err)
}
if g.Phase != PhaseLobby {
t.Fatal("game should wait for second player")
}
if _, err := g.AddPlayer("Bob"); err != nil {
t.Fatal(err)
}
if g.Phase != PhaseShop || g.Round != 1 {
t.Fatalf("game should start round 1 shop, got phase=%s round=%d", g.Phase, g.Round)
}
if _, err := g.AddPlayer("Carol"); err == nil {
t.Fatal("third player should be rejected while MaxPlayers=2")
}
for _, p := range g.Players {
if p.Coins != CoinsPerRound {
t.Fatalf("player should start with %d coins", CoinsPerRound)
}
}
if len(g.ShopRow) != ShopRowSize {
t.Fatalf("shop row should have %d cards", ShopRowSize)
}
for _, c := range g.ShopRow {
if c.Tier != 1 {
t.Fatalf("round 1 shop should deal tier 1 cards, got tier %d", c.Tier)
}
}
}
func TestBuyTakesCardAndRefills(t *testing.T) {
g, _, _ := testGame(t)
p := current(g)
want := g.ShopRow[0]
deckBefore := len(g.ShopDecks[0])
if err := g.Buy(p.ID, 0); err != nil {
t.Fatal(err)
}
if p.Coins != CoinsPerRound-1 {
t.Fatalf("buy should cost 1 coin, coins=%d", p.Coins)
}
if len(p.Deck) != 1 || p.Deck[0].ID != want.ID {
t.Fatalf("bought card should be in deck")
}
if g.ShopRow[0].ID == "" || g.ShopRow[0].ID == want.ID {
t.Fatal("shop slot should refill with a new card")
}
if len(g.ShopDecks[0]) != deckBefore-1 {
t.Fatal("refill should come from the tier deck")
}
if current(g).ID == p.ID {
t.Fatal("turn should pass after an action")
}
}
func TestTurnValidation(t *testing.T) {
g, _, _ := testGame(t)
other := g.Players[(g.Turn+1)%2]
if err := g.Buy(other.ID, 0); err == nil {
t.Fatal("acting out of turn should fail")
}
}
func TestDiscardConvertsToApples(t *testing.T) {
g, _, _ := testGame(t)
p := current(g)
if err := g.Buy(p.ID, 0); err != nil {
t.Fatal(err)
}
// Skip opponent back to p.
if err := g.Buy(current(g).ID, 0); err != nil {
t.Fatal(err)
}
if err := g.Discard(p.ID, deckIDs(p, Card.IsPet)); err != nil {
t.Fatal(err)
}
if p.Coins != CoinsPerRound-2 {
t.Fatalf("discard should cost 1 coin, coins=%d", p.Coins)
}
if p.PetCount() != 0 || len(p.Deck) != 1 || p.Deck[0].Food != FoodApple {
t.Fatalf("discarded pet should become an apple: %+v", p.Deck)
}
}
func TestTradeInThreeMatchingSuits(t *testing.T) {
g, _, _ := testGame(t)
p := current(g)
// Hand p three same-suit tier-1 pets directly.
for range 3 {
c := g.pet("Fodder", 1)
c.Suit = SuitMoon
p.Deck = append(p.Deck, c)
}
nextDeckBefore := len(g.ShopDecks[1])
if err := g.TradeStart(p.ID, deckIDs(p, nil)); err != nil {
t.Fatal(err)
}
if g.Pending == nil || g.Pending.Tier != 2 {
t.Fatalf("trade should reveal two tier-2 cards: %+v", g.Pending)
}
if len(p.Deck) != 0 {
t.Fatal("traded cards should leave the deck")
}
if current(g).ID != p.ID {
t.Fatal("turn should not pass until the trade is chosen")
}
if err := g.Buy(p.ID, 0); err == nil {
t.Fatal("other actions should be blocked while a trade is pending")
}
chosen := g.Pending.Options[0]
rejected := g.Pending.Options[1]
if err := g.TradeChoose(p.ID, 0); err != nil {
t.Fatal(err)
}
if len(p.Deck) != 1 || p.Deck[0].ID != chosen.ID {
t.Fatal("chosen card should join the deck")
}
deck2 := g.ShopDecks[1]
if len(deck2) != nextDeckBefore-1 {
t.Fatalf("tier 2 deck should be down exactly one card, was %d now %d", nextDeckBefore, len(deck2))
}
if deck2[len(deck2)-1].ID != rejected.ID {
t.Fatal("rejected card should go to the bottom of the tier deck")
}
if p.Coins != CoinsPerRound-1 {
t.Fatalf("trade should cost 1 coin, coins=%d", p.Coins)
}
}
func TestTradeRequiresMatchingSuit(t *testing.T) {
g, _, _ := testGame(t)
p := current(g)
a, b, c := g.pet("A", 1), g.pet("B", 1), g.pet("C", 1)
a.Suit, b.Suit, c.Suit = SuitSun, SuitSun, SuitMoon
p.Deck = append(p.Deck, a, b, c)
if err := g.TradeStart(p.ID, []string{a.ID, b.ID, c.ID}); err == nil {
t.Fatal("mismatched suits should be rejected")
}
if len(p.Deck) != 3 || p.Coins != CoinsPerRound {
t.Fatal("failed trade must not mutate state")
}
}
func TestTradeBlockedOnFinalRound(t *testing.T) {
g, _, _ := testGame(t)
g.Round = MaxRounds
p := current(g)
for range 3 {
c := g.pet("Fodder", 1)
c.Suit = SuitMoon
p.Deck = append(p.Deck, c)
}
if err := g.TradeStart(p.ID, deckIDs(p, nil)); err == nil {
t.Fatal("trading should be impossible in the final round")
}
}
// spendAllCoins has both players pass until the shop ends.
func spendAllCoins(t *testing.T, g *Game) {
t.Helper()
for g.Phase == PhaseShop {
if err := g.Pass(current(g).ID); err != nil {
t.Fatal(err)
}
}
}
func TestShopEndsIntoArrange(t *testing.T) {
g, _, _ := testGame(t)
spendAllCoins(t, g)
if g.Phase != PhaseArrange {
t.Fatalf("shop should end into arrange when no one is over the pet limit, got %s", g.Phase)
}
}
func TestForcedDiscardOverPetLimit(t *testing.T) {
g, p1, _ := testGame(t)
for range MaxPets + 2 {
p1.Deck = append(p1.Deck, g.pet("Extra", 1))
}
spendAllCoins(t, g)
if g.Phase != PhaseCleanup {
t.Fatalf("player with %d pets must be forced to discard, got phase %s", MaxPets+2, g.Phase)
}
// Wrong count rejected.
if err := g.CleanupDiscard(p1.ID, deckIDs(p1, Card.IsPet)[:1]); err == nil {
t.Fatal("must discard exactly the excess")
}
if err := g.CleanupDiscard(p1.ID, deckIDs(p1, Card.IsPet)[:2]); err != nil {
t.Fatal(err)
}
if p1.PetCount() != MaxPets {
t.Fatalf("expected %d pets after cleanup, got %d", MaxPets, p1.PetCount())
}
apples := 0
for _, c := range p1.Deck {
if c.Food == FoodApple {
apples++
}
}
if apples != 2 {
t.Fatalf("discarded pets should become apples, got %d", apples)
}
if g.Phase != PhaseArrange {
t.Fatalf("cleanup should flow into arrange, got %s", g.Phase)
}
}
func TestArrangeRejectsBadPermutation(t *testing.T) {
g, p1, _ := testGame(t)
p1.Deck = append(p1.Deck, g.pet("A", 1), g.pet("B", 2))
spendAllCoins(t, g)
if err := g.SubmitOrder(p1.ID, []string{p1.Deck[0].ID}); err == nil {
t.Fatal("partial order should be rejected")
}
if err := g.SubmitOrder(p1.ID, []string{p1.Deck[0].ID, p1.Deck[0].ID}); err == nil {
t.Fatal("duplicate IDs should be rejected")
}
if err := g.SubmitOrder(p1.ID, []string{p1.Deck[1].ID, p1.Deck[0].ID}); err != nil {
t.Fatal(err)
}
if p1.Deck[0].Name != "B" {
t.Fatal("submitted order should be applied to the deck")
}
}
// Full game: six rounds of pass-through shops and battles, trophy totals,
// and game over with a winner.
func TestFullGameFlow(t *testing.T) {
g, p1, p2 := testGame(t)
p1.Deck = append(p1.Deck, g.pet("Champ", 9))
p2.Deck = append(p2.Deck, g.pet("Chump", 1))
for round := 1; round <= MaxRounds; round++ {
if g.Round != round || g.Phase != PhaseShop {
t.Fatalf("expected shop of round %d, got round %d phase %s", round, g.Round, g.Phase)
}
if g.Turn != (round-1)%len(g.Players) {
t.Fatalf("round %d should rotate the starting player, turn=%d", round, g.Turn)
}
for _, c := range g.ShopRow {
if c.ID != "" && c.Tier != round {
t.Fatalf("round %d shop dealt tier %d card", round, c.Tier)
}
}
spendAllCoins(t, g)
for _, p := range g.Players {
if err := g.SubmitOrder(p.ID, deckIDs(p, nil)); err != nil {
t.Fatal(err)
}
}
if g.Phase != PhaseBattle {
t.Fatalf("expected battle after both arrange, got %s", g.Phase)
}
if g.Battle.WinnerSeat != p1.Seat {
t.Fatalf("round %d: seat 0 should win", round)
}
for _, p := range g.Players {
if err := g.AcknowledgeBattle(p.ID); err != nil {
t.Fatal(err)
}
}
}
if g.Phase != PhaseGameOver {
t.Fatalf("game should be over after %d rounds, got %s", MaxRounds, g.Phase)
}
// 1 trophy for rounds 1-5, 2 for round 6.
if p1.Trophies != 7 {
t.Fatalf("winner should have 7 trophies, got %d", p1.Trophies)
}
if g.WinnerSeat != p1.Seat {
t.Fatalf("winner seat should be %d, got %d", p1.Seat, g.WinnerSeat)
}
}
func TestViewHidesSecrets(t *testing.T) {
g, p1, p2 := testGame(t)
p1.Deck = append(p1.Deck, g.pet("Secret", 3))
v := g.ViewFor(p2.ID)
if v.YouSeat != p2.Seat {
t.Fatalf("view should identify the viewer's seat")
}
for _, pv := range v.Players {
if pv.Seat == p1.Seat && pv.Deck != nil {
t.Fatal("opponent deck contents must be hidden")
}
if pv.Seat == p1.Seat && pv.DeckSize != 1 {
t.Fatal("opponent deck size should be visible")
}
}
// Pending trade options hidden from the opponent.
for range 3 {
c := g.pet("Fodder", 1)
c.Suit = SuitLeaf
p1.Deck = append(p1.Deck, c)
}
g.Turn = p1.Seat
var fodder []string
for _, c := range p1.Deck {
if c.Name == "Fodder" {
fodder = append(fodder, c.ID)
}
}
if err := g.TradeStart(p1.ID, fodder); err != nil {
t.Fatal(err)
}
if opts := g.ViewFor(p2.ID).Pending.Options; opts[0].ID != "" || opts[1].ID != "" {
t.Fatal("trade options must be hidden from opponents")
}
if opts := g.ViewFor(p1.ID).Pending.Options; opts[0].ID == "" {
t.Fatal("trade options must be visible to the trader")
}
}
+85
View File
@@ -0,0 +1,85 @@
package game
// PlayerView is what any player may know about a seat. Deck contents are
// only included for the viewer's own seat; opponents see counts.
type PlayerView struct {
ID string `json:"id"`
Name string `json:"name"`
Seat int `json:"seat"`
Coins int `json:"coins"`
Trophies int `json:"trophies"`
Ready bool `json:"ready"`
Connected bool `json:"connected"`
DeckSize int `json:"deckSize"`
PetCount int `json:"petCount"`
Deck []Card `json:"deck,omitempty"` // self only
}
// View is the full game state as seen by one player.
type View struct {
GameID string `json:"gameId"`
Code string `json:"code"`
Phase Phase `json:"phase"`
Round int `json:"round"`
MaxRounds int `json:"maxRounds"`
MaxPets int `json:"maxPets"`
YouSeat int `json:"youSeat"`
Turn int `json:"turn"`
ShopRow []Card `json:"shopRow"`
DeckCounts []int `json:"deckCounts"` // remaining shop cards per tier
Players []PlayerView `json:"players"`
// Pending is included for everyone so opponents see a trade is in
// progress, but the revealed options are only shown to the trader.
Pending *PendingTrade `json:"pending,omitempty"`
Battle *BattleResult `json:"battle,omitempty"`
WinnerSeat int `json:"winnerSeat"`
}
// ViewFor builds the state visible to the given player.
func (g *Game) ViewFor(playerID string) View {
v := View{
GameID: g.ID,
Code: g.Code,
Phase: g.Phase,
Round: g.Round,
MaxRounds: MaxRounds,
MaxPets: MaxPets,
YouSeat: -1,
Turn: g.Turn,
ShopRow: g.ShopRow,
WinnerSeat: g.WinnerSeat,
}
for _, deck := range g.ShopDecks {
v.DeckCounts = append(v.DeckCounts, len(deck))
}
for _, p := range g.Players {
pv := PlayerView{
ID: p.ID,
Name: p.Name,
Seat: p.Seat,
Coins: p.Coins,
Trophies: p.Trophies,
Ready: p.Ready,
Connected: p.Connected,
DeckSize: len(p.Deck),
PetCount: p.PetCount(),
}
if p.ID == playerID {
v.YouSeat = p.Seat
pv.Deck = p.Deck
}
v.Players = append(v.Players, pv)
}
if g.Pending != nil {
pending := *g.Pending
if pending.PlayerID != playerID {
pending.Options = [2]Card{} // hide the revealed cards
}
v.Pending = &pending
}
// Battle results (lineups, events) are public once resolved. Keep the
// battle around during the following shop phase too, so late joiners /
// reconnects can still see the last result.
v.Battle = g.Battle
return v
}