Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

card.gno

// Package engine holds the duel rules. The same source compiles as Go and as Gno, so it
// stays inside the Go 1.17 subset: no generics, no min or max builtins, no range over
// an integer, no maps and no imports.
package engine

const beatsPerRound = 3

// Tier orders effects inside a phase.
type Tier int

const (
	Quick Tier = iota
	Normal
	Slow
)

type EffectKind int

const (
	GainBlock EffectKind = iota
	GainCounter
	Hit      // deal N damage
	HitBlock // deal damage equal to your Block
	ApplyVulnerable
	GainStrength
	VulnerableIfCancelled // apply N Vulnerable if this card cancelled a card this beat
	MoveVulnerable        // Block phase: move all your Vulnerable to the opponent
	GainVulnerable        // gain N Vulnerable yourself
	HitPerVulnerable      // deal N damage, and N more for each Vulnerable on you
	BlockPerVulnerable    // Block phase: gain N Block, and N more for each Vulnerable on you
	StripBlock            // the opponent loses all Block at the end of the step
	HitHardest            // deal the HP the hardest opponent hit took from you this round, up to N
	HitIfNotAttacked      // deal N damage if no opponent attack lands this beat
)

type Effect struct {
	Kind EffectKind
	N    int
}

// CardID indexes Ruleset.Cards.
type CardID int

type Card struct {
	Name      string
	Cost      int
	Tier      Tier
	Special   bool // spent once played; basics are not
	Rare      bool // the clan's signature card; a deck holds exactly one
	Interrupt bool
	Parry     int      // Parry N: attacks it cancels while active; 0 for no Parry
	Block     []Effect // Block phase
	Damage    []Effect // Damage phase, in printed order
	OnCancel  []Effect // Block phase of the beat the card is cancelled on
	// CancelDamage resolves in the card's tier, in the Damage phase of the beat it is
	// cancelled on.
	CancelDamage []Effect
}

// Attack reports whether the card's text deals damage, including when it is cancelled.
func (c *Card) Attack() bool {
	return dealsDamage(c.Damage) || dealsDamage(c.CancelDamage)
}

func dealsDamage(effects []Effect) bool {
	for _, e := range effects {
		if e.Kind.isHit() {
			return true
		}
	}
	return false
}

func (k EffectKind) isHit() bool {
	return k == Hit || k == HitBlock || k == HitPerVulnerable || k == HitHardest || k == HitIfNotAttacked
}

// Plan is the ordered cards of one round; their costs sum to 3.
type Plan []CardID

type Side int

const (
	SideA Side = iota
	SideB
)

deck.gno

package engine

// deckSize is the number of special cards in a deck.
const deckSize = 8

// LegalDeck reports whether deck, a bit set by CardID, is deckSize cards of clan's pool
// holding exactly one Rare.
func (rs *Ruleset) LegalDeck(clan Clan, deck uint64) bool {
	if deck&^clan.Pool != 0 {
		return false
	}
	cards, rares := 0, 0
	for i := range rs.Cards {
		if deck&(uint64(1)<<uint(i)) == 0 {
			continue
		}
		cards++
		if rs.Cards[i].Rare {
			rares++
		}
	}
	return cards == deckSize && rares == 1
}

gnomod.toml

module = "gno.land/p/g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz/gnomepit/engine"
gno = "0.9"

[addpkg]
  creator = "g188vafzutzvlfw6wt7u3s62xtuvm0epmu8ufmfz"
  height = 684811
  max_deposit = "10000000ugnot"

plans.gno

package engine

// LegalPlans lists every plan side can play from deck in state s: costs summing to 3,
// basics any number of times, each unspent special of deck at most once. Plans come in
// card order, depth first.
func (rs *Ruleset) LegalPlans(s State, side Side, deck uint64) []Plan {
	var buf [beatsPerRound]CardID
	return rs.extendPlans(nil, buf[:0], 0, deck&^s.Gnomes[side].Spent, 0)
}

func (rs *Ruleset) extendPlans(out []Plan, plan Plan, beats int, available, used uint64) []Plan {
	if beats == beatsPerRound {
		done := make(Plan, len(plan))
		copy(done, plan)
		return append(out, done)
	}
	for i := range rs.Cards {
		c := &rs.Cards[i]
		if beats+c.Cost > beatsPerRound {
			continue
		}
		bit := uint64(1) << uint(i)
		if c.Special && (available&bit == 0 || used&bit != 0) {
			continue
		}
		out = rs.extendPlans(out, append(plan, CardID(i)), beats+c.Cost, available, used|bit)
	}
	return out
}

resolve.gno

package engine

// Result is how a round left the match.
type Result int

const (
	Ongoing Result = iota
	AWins
	BWins
	Draw
)

// Outcome is the state after a round, and the match result once it has one.
type Outcome struct {
	State  State
	Result Result
}

const (
	lastRound   = 3
	maxPlanSize = beatsPerRound
)

// slot is the card of one plan occupying one beat.
type slot struct {
	index  int  // position of the card in the plan
	lands  bool // the card's last beat, where its effects resolve
	active bool // lands, or a Parry card, which acts on every beat it occupies
}

func (rs *Ruleset) slotsOf(p Plan) [beatsPerRound]slot {
	var out [beatsPerRound]slot
	beat := 0
	for i, id := range p {
		c := &rs.Cards[id]
		for k := 0; k < c.Cost; k++ {
			lands := k == c.Cost-1
			out[beat] = slot{index: i, lands: lands, active: lands || c.Parry > 0}
			beat++
		}
	}
	return out
}

// take applies damage through Block and returns what Block absorbed.
func (v *Vitals) take(damage int) int {
	absorbed := damage
	if v.Block < absorbed {
		absorbed = v.Block
	}
	v.Block -= absorbed
	v.HP -= damage - absorbed
	return absorbed
}

// gain applies a Block-phase effect and returns the change after the cap.
func (v *Vitals) gain(rs *Ruleset, e Effect) int {
	switch e.Kind {
	case GainBlock, BlockPerVulnerable:
		n := e.N
		if e.Kind == BlockPerVulnerable {
			n *= 1 + v.Vulnerable
		}
		before := v.Block
		v.Block = capped(v.Block+n, rs.BlockCap)
		return v.Block - before
	case GainCounter:
		before := v.Counter
		v.Counter = capped(v.Counter+e.N, rs.CounterCap)
		return v.Counter - before
	}
	return 0
}

func (rs *Ruleset) gainAll(v *Vitals, effects []Effect, tr *tracer, side Side, card CardID) {
	for _, e := range effects {
		n := v.gain(rs, e)
		switch e.Kind {
		case GainBlock, BlockPerVulnerable:
			tr.emit(BlockGained, side, card, n, 0, false)
		case GainCounter:
			tr.emit(CounterGained, side, card, n, 0, false)
		}
	}
}

func movesVulnerable(effects []Effect) bool {
	for _, e := range effects {
		if e.Kind == MoveVulnerable {
			return true
		}
	}
	return false
}

// moveVulnerable puts all of each mover's Vulnerable on the other gnome; movers[side] is
// nil when that side moves nothing. Both amounts are read before either changes, so two
// moves on one beat swap the tokens. The receiver's cap applies.
func (rs *Ruleset) moveVulnerable(f *[2]Vitals, movers [2]*Card, cards [2]CardID, tr *tracer, beat int) {
	var held [2]int
	for side := 0; side < 2; side++ {
		if movers[side] != nil {
			held[side], f[side].Vulnerable = f[side].Vulnerable, 0
		}
	}
	for side := 0; side < 2; side++ {
		if movers[side] == nil {
			continue
		}
		o := 1 - side
		f[o].Vulnerable = capped(f[o].Vulnerable+held[side], rs.VulnerableCap)
		tr.at(beat, BlockPhase, movers[side].Tier, 1)
		tr.emit(VulnerableMoved, Side(side), cards[side], held[side], 0, false)
	}
}

func capped(v, limit int) int {
	if v > limit {
		return limit
	}
	return v
}

// Resolve plays round s.Round. Both plans must be legal for their side in s
// (LegalPlans); an illegal plan is a caller error.
func (rs *Ruleset) Resolve(s State, a, b Plan) Outcome {
	return rs.resolve(s, a, b, nil)
}

func (rs *Ruleset) resolve(s State, a, b Plan, events *[]Event) Outcome {
	plans := [2]Plan{a, b}
	next := s
	next.Round = s.Round + 1
	tr := tracer{events: events}
	var f [2]Vitals
	var slots [2][beatsPerRound]slot
	var gone [2][maxPlanSize]bool   // cancelled, or a Parry that used up its cancels
	var parried [2][maxPlanSize]int // cancels made by each Parry card this round
	var hardest [2]int              // the most HP one opponent hit took from each gnome this round
	for side := 0; side < 2; side++ {
		g := s.Gnomes[side]
		f[side] = Vitals{HP: g.HP, Vulnerable: g.Vulnerable, Strength: g.Strength}
		slots[side] = rs.slotsOf(plans[side])
		for _, id := range plans[side] {
			if rs.Cards[id].Special {
				next.Gnomes[side].Spent |= uint64(1) << uint(id)
			}
		}
	}

	for beat := 0; beat < beatsPerRound; beat++ {
		var cur [2]*Card // nil once cancelled or ended
		var sl [2]slot
		var cards [2]CardID
		for side := 0; side < 2; side++ {
			sl[side] = slots[side][beat]
			cards[side] = plans[side][sl[side].index]
			if !gone[side][sl[side].index] {
				cur[side] = &rs.Cards[cards[side]]
			}
		}

		// Interrupt phase
		var cancelledNow [2]*Card
		var didCancel [2]bool
		for tier := Quick; tier <= Slow; tier++ {
			var hit, parryDone [2]bool
			for side := 0; side < 2; side++ {
				o := 1 - side
				me, op := cur[side], cur[o]
				if me == nil || op == nil || me.Tier != tier {
					continue
				}
				switch {
				case me.Interrupt && sl[side].lands && !sl[o].active:
					hit[o], didCancel[side] = true, true
				case me.Parry > 0 && sl[side].active && sl[o].lands && op.Attack():
					hit[o], didCancel[side] = true, true
					parried[side][sl[side].index]++
					parryDone[side] = parried[side][sl[side].index] >= me.Parry
				}
			}
			tr.at(beat+1, InterruptPhase, tier, 1)
			for side := 0; side < 2; side++ {
				if hit[side] {
					cancelledNow[side] = cur[side]
					gone[side][sl[side].index] = true
					cur[side] = nil
					tr.emit(Cancelled, Side(side), cards[side], 0, 0, false)
				}
				if parryDone[side] && cur[side] != nil {
					// Its later beats stay empty; this beat's effects still resolve.
					gone[side][sl[side].index] = true
					tr.emit(ParryEnded, Side(side), cards[side], 0, 0, false)
				}
			}
			tr.close(&f)
		}

		facts := beatFacts{didCancel: didCancel}
		for side := 0; side < 2; side++ {
			o := 1 - side
			facts.attacked[side] = cur[o] != nil && sl[o].lands && cur[o].Attack()
		}

		// Block phase
		var movers [2]*Card
		for side := 0; side < 2; side++ {
			if cur[side] != nil && sl[side].lands {
				tr.at(beat+1, BlockPhase, cur[side].Tier, 1)
				rs.gainAll(&f[side], cur[side].Block, &tr, Side(side), cards[side])
				if movesVulnerable(cur[side].Block) {
					movers[side] = cur[side]
				}
			}
			if cancelledNow[side] != nil {
				tr.at(beat+1, BlockPhase, cancelledNow[side].Tier, 1)
				rs.gainAll(&f[side], cancelledNow[side].OnCancel, &tr, Side(side), cards[side])
			}
		}
		rs.moveVulnerable(&f, movers, cards, &tr, beat+1)
		tr.close(&f)

		// Damage phase
		for tier := Quick; tier <= Slow; tier++ {
			var effects [2][]Effect
			for side := 0; side < 2; side++ {
				switch c := cancelledNow[side]; {
				case cur[side] != nil && sl[side].lands && cur[side].Tier == tier:
					effects[side] = cur[side].Damage
				case c != nil && c.Tier == tier:
					effects[side] = c.CancelDamage
				}
			}
			tr.at(beat+1, DamagePhase, tier, 0)
			if result := rs.resolveDamageTier(&f, &hardest, effects, cards, facts, &tr); result != Ongoing {
				return Outcome{State: rs.settle(next, f), Result: result}
			}
		}
	}

	next = rs.settle(next, f)
	if s.Round < lastRound {
		return Outcome{State: next, Result: Ongoing}
	}
	return Outcome{State: next, Result: byHP(next.Gnomes[SideA].HP, next.Gnomes[SideB].HP)}
}

// settle copies the round's carried values into the next state.
func (rs *Ruleset) settle(next State, f [2]Vitals) State {
	for side := 0; side < 2; side++ {
		next.Gnomes[side].HP = f[side].HP
		next.Gnomes[side].Vulnerable = f[side].Vulnerable
		next.Gnomes[side].Strength = f[side].Strength
		if rs.StrengthLastsTheRound {
			next.Gnomes[side].Strength = 0
		}
		if rs.VulnerableLastsTheRound {
			next.Gnomes[side].Vulnerable = 0
		}
	}
	return next
}

func byHP(a, b int) Result {
	switch {
	case a > b:
		return AWins
	case b > a:
		return BWins
	}
	return Draw
}

// beatFacts are what a beat's Damage phase reads from its Interrupt phase.
type beatFacts struct {
	didCancel [2]bool // the gnome's card cancelled an opponent card this beat
	attacked  [2]bool // an opponent attack lands on the gnome this beat, not cancelled
}

// resolveDamageTier resolves both gnomes' effects of one tier in steps: step k applies
// effect k of each card together, every value read at the start of the step. A gnome
// takes the opponent's hit before the Counter damage its own hit triggered. hardest
// carries each gnome's hardest hit taken this round across tiers and beats. It returns
// the knockout result as soon as a step leaves a gnome at 0 HP or less.
func (rs *Ruleset) resolveDamageTier(f *[2]Vitals, hardest *[2]int, effects [2][]Effect, cards [2]CardID, facts beatFacts, tr *tracer) Result {
	var hitsTotal, hitsDone [2]int
	var doubled, doubleDecided [2]bool
	for side := 0; side < 2; side++ {
		for _, e := range effects[side] {
			if e.Kind.isHit() && !skipsHit(e, facts, side) {
				hitsTotal[side]++
			}
		}
	}
	steps := len(effects[0])
	if len(effects[1]) > steps {
		steps = len(effects[1])
	}

	for k := 0; k < steps; k++ {
		tr.step = k + 1
		var hitIn, counterIn, addVulnerable, selfVulnerable, addStrength, usedVulnerable [2]int
		var strip [2]bool
		for side := 0; side < 2; side++ {
			if k >= len(effects[side]) {
				continue
			}
			o := 1 - side
			e := effects[side][k]
			switch e.Kind {
			case Hit, HitBlock, HitPerVulnerable, HitHardest, HitIfNotAttacked:
				if skipsHit(e, facts, side) {
					continue
				}
				if rs.VulnerableDoublesOneHit {
					doubled[side] = f[o].Vulnerable > 0
				} else if !doubleDecided[side] {
					doubled[side], doubleDecided[side] = f[o].Vulnerable > 0, true
				}
				amount := e.N
				switch e.Kind {
				case HitBlock:
					amount = f[side].Block
				case HitPerVulnerable:
					amount = e.N * (1 + f[side].Vulnerable)
				case HitHardest:
					amount = hardest[side]
					if amount > e.N {
						amount = e.N
					}
				}
				amount += f[side].Strength
				if doubled[side] {
					amount *= 2
				}
				hitIn[o] += amount
				counterIn[side] += f[o].Counter
				hitsDone[side]++
				if doubled[side] && (rs.VulnerableDoublesOneHit || hitsDone[side] == hitsTotal[side]) {
					usedVulnerable[o]++
				}
			case ApplyVulnerable:
				addVulnerable[o] += e.N
			case GainVulnerable:
				selfVulnerable[side] += e.N
			case GainStrength:
				addStrength[side] += e.N
			case VulnerableIfCancelled:
				if facts.didCancel[side] {
					addVulnerable[o] += e.N
				}
			case StripBlock:
				strip[o] = true
			}
		}
		// vulnerableGained counts tokens from the opponent, selfGained a gnome's own; the
		// opponent's count against the cap first.
		var hitAbsorbed, counterAbsorbed, vulnerableGained, selfGained, strengthGained, stripped [2]int
		for side := 0; side < 2; side++ {
			hitAbsorbed[side] = f[side].take(hitIn[side])
			counterAbsorbed[side] = f[side].take(counterIn[side])
			if taken := hitIn[side] - hitAbsorbed[side]; taken > hardest[side] {
				hardest[side] = taken
			}
			if strip[side] {
				stripped[side], f[side].Block = f[side].Block, 0
			}
			v := f[side].Vulnerable - usedVulnerable[side]
			if v < 0 {
				v = 0
			}
			applied := capped(v+addVulnerable[side], rs.VulnerableCap)
			f[side].Vulnerable = capped(applied+selfVulnerable[side], rs.VulnerableCap)
			vulnerableGained[side] = applied - v
			selfGained[side] = f[side].Vulnerable - applied
			before := f[side].Strength
			f[side].Strength = capped(before+addStrength[side], rs.StrengthCap)
			strengthGained[side] = f[side].Strength - before
		}
		for side := 0; side < 2; side++ {
			if k >= len(effects[side]) {
				continue
			}
			o := 1 - side
			switch e := effects[side][k]; e.Kind {
			case Hit, HitBlock, HitPerVulnerable, HitHardest, HitIfNotAttacked:
				if skipsHit(e, facts, side) {
					break
				}
				tr.emit(HitLanded, Side(side), cards[side], hitIn[o]-hitAbsorbed[o], hitAbsorbed[o], doubled[side])
				if counterIn[side] > 0 {
					tr.emit(CounterHit, Side(side), cards[side], counterIn[side]-counterAbsorbed[side], counterAbsorbed[side], false)
				}
			case ApplyVulnerable:
				tr.emit(VulnerableApplied, Side(side), cards[side], vulnerableGained[o], 0, false)
			case GainVulnerable:
				tr.emit(VulnerableGained, Side(side), cards[side], selfGained[side], 0, false)
			case StripBlock:
				tr.emit(BlockStripped, Side(side), cards[side], stripped[o], 0, false)
			case VulnerableIfCancelled:
				if facts.didCancel[side] {
					tr.emit(VulnerableApplied, Side(side), cards[side], vulnerableGained[o], 0, false)
				}
			case GainStrength:
				tr.emit(StrengthGained, Side(side), cards[side], strengthGained[side], 0, false)
			}
		}
		tr.close(f)
		outA, outB := f[SideA].HP <= 0, f[SideB].HP <= 0
		switch {
		case outA && outB:
			return Draw
		case outB:
			return AWins
		case outA:
			return BWins
		}
	}
	return Ongoing
}

// skipsHit reports whether a conditional hit of side's card deals nothing this beat.
func skipsHit(e Effect, facts beatFacts, side int) bool {
	return e.Kind == HitIfNotAttacked && facts.attacked[side]
}

ruleset.gno

package engine

// Clan is a named pool of special cards.
type Clan struct {
	Name string
	Pool uint64 // bit i set: Ruleset.Cards[i] is in the pool
}

// Ruleset holds every card and number the rules use, so the solver can sweep them.
type Ruleset struct {
	Cards         []Card
	Clans         []Clan
	HP            int // starting HP of both gnomes
	BlockCap      int
	CounterCap    int
	VulnerableCap int
	StrengthCap   int
	// VulnerableDoublesOneHit: each hit against a Vulnerable gnome deals double and uses a
	// token. Otherwise the next card to hit deals double on every hit and uses one token.
	VulnerableDoublesOneHit bool
	// StrengthLastsTheRound: Strength ends with the round, like Block and Counter. Otherwise
	// it lasts the match.
	StrengthLastsTheRound bool
	// VulnerableLastsTheRound: unused Vulnerable ends with the round. Otherwise it lasts
	// until hits use it.
	VulnerableLastsTheRound bool
}

// Gnome is one side's state between rounds; Block and Counter end with each round.
type Gnome struct {
	HP, Vulnerable, Strength int
	Spent                    uint64 // special cards played, by CardID bit
}

// State is the match between rounds. Round is the round about to be played, 1 to 3.
type State struct {
	Round  int
	Gnomes [2]Gnome
}

// Start is the state before round 1.
func (rs *Ruleset) Start() State {
	return State{Round: 1, Gnomes: [2]Gnome{{HP: rs.HP}, {HP: rs.HP}}}
}

func (rs *Ruleset) CardByName(name string) (CardID, bool) {
	for i := range rs.Cards {
		if rs.Cards[i].Name == name {
			return CardID(i), true
		}
	}
	return 0, false
}

// PlanOf looks each card up by name. It reports false when a name matches no card.
func (rs *Ruleset) PlanOf(names ...string) (Plan, bool) {
	plan := make(Plan, 0, len(names))
	for _, n := range names {
		id, ok := rs.CardByName(n)
		if !ok {
			return nil, false
		}
		plan = append(plan, id)
	}
	return plan, true
}

func (rs *Ruleset) ClanByName(name string) (Clan, bool) {
	for _, c := range rs.Clans {
		if c.Name == name {
			return c, true
		}
	}
	return Clan{}, false
}

func hits(n, damage int) []Effect {
	out := make([]Effect, n)
	for i := range out {
		out[i] = Effect{Hit, damage}
	}
	return out
}

// ProofOfConcept is the proof-of-concept ruleset: the two basics, the Pickers and
// Ironhide 10-card starter packs of the duel spec (candidate AS2-HB5-F4), and the Delvers
// pack, a draft not yet in the spec.
func ProofOfConcept() *Ruleset {
	cards := []Card{
		{Name: "Pick", Cost: 1, Tier: Normal, Damage: hits(1, 1)},
		{Name: "Brace", Cost: 1, Tier: Normal, Block: []Effect{{GainBlock, 1}}},

		{Name: "Pickaxe Flurry", Cost: 1, Tier: Quick, Special: true, Damage: hits(2, 1)},
		{Name: "Kneecap", Cost: 1, Tier: Quick, Special: true, Interrupt: true, Damage: hits(1, 1)},
		{Name: "Sling Stone", Cost: 1, Tier: Normal, Special: true, Damage: hits(1, 2)},
		{Name: "Dodge Roll", Cost: 2, Tier: Normal, Special: true, Parry: 1},
		{Name: "Chalk Dust", Cost: 1, Tier: Quick, Special: true, Damage: []Effect{{ApplyVulnerable, 1}}},
		{Name: "Double Tap", Cost: 2, Tier: Normal, Special: true, Damage: hits(3, 1)},
		{Name: "Momentum", Cost: 1, Tier: Normal, Special: true, Damage: []Effect{{GainStrength, 1}}},
		{Name: "Undermine", Cost: 1, Tier: Quick, Special: true, Rare: true, Interrupt: true, Damage: []Effect{{VulnerableIfCancelled, 2}}},
		{Name: "Hunker Down", Cost: 3, Tier: Normal, Special: true, Parry: 2},
		{Name: "Boot and Heel", Cost: 2, Tier: Slow, Special: true, Damage: hits(2, 2)},

		{Name: "Stone Guard", Cost: 3, Tier: Normal, Special: true, Parry: 2},
		{Name: "Bulwark", Cost: 2, Tier: Normal, Special: true, Block: []Effect{{GainBlock, 5}}},
		{Name: "Hammer Blow", Cost: 2, Tier: Slow, Special: true, Damage: hits(1, 5)},
		{Name: "Cobble Throw", Cost: 1, Tier: Slow, Special: true, Damage: hits(1, 2)},
		{Name: "Spiked Shield", Cost: 1, Tier: Normal, Special: true, Block: []Effect{{GainBlock, 1}, {GainCounter, 1}}},
		{Name: "Anvil Stomp", Cost: 2, Tier: Slow, Special: true, Damage: []Effect{{Hit, 2}, {ApplyVulnerable, 1}}},
		{Name: "Feint", Cost: 2, Tier: Normal, Special: true, Damage: hits(1, 4), OnCancel: []Effect{{GainBlock, 4}}},
		{Name: "Avalanche", Cost: 1, Tier: Slow, Special: true, Rare: true, Damage: []Effect{{HitBlock, 0}}},
		{Name: "Shield Catch", Cost: 2, Tier: Normal, Special: true, Parry: 1},
		{Name: "Loose Timbers", Cost: 2, Tier: Normal, Special: true, Block: []Effect{{GainBlock, 3}}, CancelDamage: hits(1, 4)},

		{Name: "Kickback", Cost: 1, Tier: Slow, Special: true, Rare: true, Damage: []Effect{{HitHardest, 5}}},
		{Name: "Overdig", Cost: 2, Tier: Normal, Special: true, Damage: []Effect{{Hit, 6}, {GainVulnerable, 1}}},
		{Name: "Ambush", Cost: 1, Tier: Normal, Special: true, Damage: []Effect{{GainVulnerable, 1}, {HitIfNotAttacked, 6}}},
		{Name: "Open Guard", Cost: 1, Tier: Normal, Special: true, Block: []Effect{{GainBlock, 4}}, Damage: []Effect{{GainVulnerable, 1}}},
		{Name: "Chisel Jab", Cost: 1, Tier: Normal, Special: true, Damage: hits(1, 2)},
		{Name: "Rockfall", Cost: 2, Tier: Slow, Special: true, Damage: hits(1, 5)},
		{Name: "Cribbing", Cost: 1, Tier: Normal, Special: true, Block: []Effect{{BlockPerVulnerable, 1}}},
		{Name: "Deadfall", Cost: 2, Tier: Normal, Special: true, Parry: 1, Damage: []Effect{{VulnerableIfCancelled, 1}}},
		{Name: "Blowback", Cost: 2, Tier: Normal, Special: true, Block: []Effect{{MoveVulnerable, 0}}},
		{Name: "Cave-In", Cost: 3, Tier: Slow, Special: true, Damage: []Effect{{StripBlock, 0}, {Hit, 5}}},
	}
	const firstPickers, firstIronhide, firstDelvers, end = 2, 12, 22, 32
	return &Ruleset{
		Cards: cards,
		Clans: []Clan{
			{Name: "Pickers", Pool: bitRange(firstPickers, firstIronhide)},
			{Name: "Ironhide", Pool: bitRange(firstIronhide, firstDelvers)},
			{Name: "Delvers", Pool: bitRange(firstDelvers, end)},
		},
		HP:            15,
		BlockCap:      20,
		CounterCap:    3,
		VulnerableCap: 3,
		StrengthCap:   8,

		VulnerableDoublesOneHit: true,
		StrengthLastsTheRound:   true,
	}
}

// bitRange sets bits from, from+1, ..., to-1.
func bitRange(from, to int) uint64 {
	var bits uint64
	for i := from; i < to; i++ {
		bits |= uint64(1) << uint(i)
	}
	return bits
}

trace.gno

package engine

// Vitals is one gnome's numbers during a round.
type Vitals struct {
	HP, Block, Counter, Vulnerable, Strength int
}

// Phase is the part of a beat an event belongs to.
type Phase int

const (
	InterruptPhase Phase = iota
	BlockPhase
	DamagePhase
)

type EventKind int

const (
	Cancelled         EventKind = iota // Card was cancelled by the opponent's Interrupt or Parry
	ParryEnded                         // Card made its last Parry cancel; its later beats stay empty
	BlockGained                        // Side gained N Block from Card
	CounterGained                      // Side gained Counter N from Card
	HitLanded                          // Card hit the opponent for N damage to HP, Blocked absorbed
	CounterHit                         // the opponent's Counter dealt N to Side's HP after Card hit
	VulnerableApplied                  // Card applied N Vulnerable to the opponent
	StrengthGained                     // Side gained N Strength from Card
	VulnerableMoved                    // Card moved Side's N Vulnerable to the opponent, who keeps up to the cap
	VulnerableGained                   // Side gained N Vulnerable from Card
	BlockStripped                      // Card took the opponent's N Block
)

// Event is one effect of a round's resolution. Side owns Card. A HitLanded, a
// VulnerableApplied or a BlockStripped lands on the other gnome, a VulnerableMoved changes
// both, and every other kind changes Side's own Vitals. N is the change after caps, the damage that
// reached HP, or the tokens that left the mover.
type Event struct {
	Beat    int // 1 to 3
	Phase   Phase
	Tier    Tier
	Step    int // from 1 within a beat, phase and tier; equal for effects that resolve together
	Kind    EventKind
	Side    Side
	Card    CardID
	N       int
	Blocked int       // HitLanded and CounterHit: damage absorbed by Block
	Doubled bool      // HitLanded: the defender's Vulnerable doubled it
	After   [2]Vitals // both gnomes once the whole step has resolved
}

// Trace resolves the round as Resolve does and also returns its events in order.
func (rs *Ruleset) Trace(s State, a, b Plan) (Outcome, []Event) {
	var events []Event
	o := rs.resolve(s, a, b, &events)
	return o, events
}

// tracer appends the events of one round. A nil events pointer records nothing.
type tracer struct {
	events *[]Event
	beat   int
	phase  Phase
	tier   Tier
	step   int
	first  int // index of the current step's first event
}

func (t *tracer) at(beat int, phase Phase, tier Tier, step int) {
	t.beat, t.phase, t.tier, t.step = beat, phase, tier, step
}

func (t *tracer) emit(kind EventKind, side Side, card CardID, n, blocked int, doubled bool) {
	if t.events == nil {
		return
	}
	*t.events = append(*t.events, Event{
		Beat: t.beat, Phase: t.phase, Tier: t.tier, Step: t.step,
		Kind: kind, Side: side, Card: card, N: n, Blocked: blocked, Doubled: doubled,
	})
}

// close stamps the state after the step on every event emitted since the last close.
func (t *tracer) close(f *[2]Vitals) {
	if t.events == nil {
		return
	}
	evs := *t.events
	for i := t.first; i < len(evs); i++ {
		evs[i].After = *f
	}
	t.first = len(evs)
}