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

characters.gno

package engine

// CharKeys are the 48 character tokens a player can pick.
var CharKeys = []string{
	"andy", "axe", "banker", "barkeep", "border_rider", "cattle_baron",
	"chief", "clerk", "driver", "dude", "eagle", "el_jefe", "fast_draw",
	"fast_eddie", "floozy", "foreman", "gambler", "guard", "gun_artist",
	"happy", "hawk", "ike", "innocente", "john_henry", "lady", "lightning",
	"ling_ho", "little_ernie", "lucky", "marshal", "mountain_man", "nco",
	"old_man", "owner", "prospector", "quiet_man", "reb", "running_boy",
	"slim", "smith", "sodbuster", "texas", "the_drifter", "the_kid",
	"u_s_scout", "veteran", "woman", "yankee",
}

// IsCharKey reports whether s names one of the character tokens.
func IsCharKey(s string) bool {
	for _, k := range CharKeys {
		if k == s {
			return true
		}
	}
	return false
}

deck.gno

package engine

import (
	"crypto/sha256"
	"encoding/binary"
	"math/rand"
	"strings"

	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
)

// Result is one line of a result card: a number of points, or a named
// penalty (rules 14.1, 14.21). Points are 0 or more; penalties are negative.
type Result int

const (
	// LoseAim: the character loses its aim (no aim is tracked yet).
	LoseAim Result = -1
	// WildShot: every cocked gun goes off without hitting anything, is
	// uncocked and loses a shell; the aim is lost.
	WildShot Result = -2
	// Drop: an upright character turns DOWN, draws 3 delay cards and loses
	// its aim; no effect when already DOWN.
	Drop Result = -3
)

// IsPoints reports whether the line is a number of points.
func (r Result) IsPoints() bool { return r >= 0 }

// String returns the penalty name used in events and JSON, or "" for points.
func (r Result) String() string {
	switch r {
	case LoseAim:
		return "lose_aim"
	case WildShot:
		return "wild_shot"
	case Drop:
		return "drop"
	}
	return ""
}

// ResultCard is one of the 108 result cards (rule 2.4): N is its number on
// the card. Delay and Wound are the DELAY and WOUND lines and Hex the HEX
// line (direction cards, 14.3: a relative direction, hex.Same or hex.Long).
// The upper block is either a FIRE hit chart with its Target Status letters
// (cards 1-100, see fire.gno) or a MALFUNCTION block (cards 101-108). The
// TAC line (optional rule 9) is not used by this game.
type ResultCard struct {
	N      int
	Delay  Result
	Wound  Result
	Hex    hex.Rel
	Fire   *Chart       // the hit chart of a FIRE card, nil on a MALFUNCTION
	Status string       // Target Status letters of a FIRE card (StatusMove...)
	Malf   *Malfunction // the block of a MALFUNCTION card, nil on a FIRE card
}

// IsFire reports whether the card is a FIRE card (13.2).
func (c ResultCard) IsFire() bool { return c.Malf == nil }

// DeckSize is the number of result cards.
const DeckSize = 108

// Cards is the result deck in card order, index 0 = card 1.
var Cards = buildCards()

func buildCards() (cards [DeckSize]ResultCard) {
	// Each row is a run of consecutive cards sharing the same three lines,
	// transcribed from the card images (assets/result_card_NNN.png).
	runs := []struct {
		from, to     int
		delay, wound Result
		hex          hex.Rel
	}{
		{1, 18, 0, 0, hex.Same},
		{19, 36, 0, 1, hex.Long},
		{37, 54, 1, 2, hex.Long},
		{55, 60, 1, 3, hex.AheadLeft},
		{61, 69, 2, 3, hex.Same},
		{70, 78, 2, 4, hex.Long},
		{79, 84, 2, 5, hex.AheadRight},
		{85, 87, 2, 6, hex.Ahead},
		{88, 93, LoseAim, 1, hex.BackRight},
		{94, 99, LoseAim, WildShot, hex.BackLeft},
		{100, 100, WildShot, Drop, hex.Back},
		{101, 103, WildShot, Drop, hex.Back},
		{104, 106, 1, Drop, hex.Ahead},
		{107, 108, Drop, Drop, hex.Back},
	}
	n := 0
	for _, r := range runs {
		for i := r.from; i <= r.to; i++ {
			c := ResultCard{N: i, Delay: r.delay, Wound: r.wound, Hex: r.hex}
			if i <= len(fireCards) {
				c.Fire = parseChart(fireCards[i-1].chart)
				c.Status = fireCards[i-1].status
			} else {
				c.Malf = &malfunctions[i-1-len(fireCards)]
			}
			cards[i-1] = c
			n++
		}
	}
	if n != DeckSize {
		panic("result deck: wrong card count")
	}
	return cards
}

// Card returns result card n (1 to 108).
func Card(n int) ResultCard { return Cards[n-1] }

// Drawer hands out result cards to Resolve.
type Drawer interface {
	// Draw returns the next result card.
	Draw() ResultCard
}

// Seed hashes the given parts into shuffle seed material.
func Seed(parts ...string) [32]byte {
	return sha256.Sum256([]byte(strings.Join(parts, "|")))
}

// Deck is the result deck shuffled once from a seed and dealt in order
// (rule 5.7: the deck is reshuffled when exhausted). The same seed always
// deals the same cards, so a turn can be replayed from its stored seed.
type Deck struct {
	r     *rand.Rand
	order [DeckSize]int // card numbers in deal order
	next  int
	drawn []int // every card dealt so far, in order
}

// NewDeck shuffles the 108 cards with the seed.
func NewDeck(seed [32]byte) *Deck {
	s1 := binary.BigEndian.Uint64(seed[0:8])
	s2 := binary.BigEndian.Uint64(seed[8:16])
	d := &Deck{r: rand.New(rand.NewPCG(s1, s2))}
	d.shuffle()
	return d
}

func (d *Deck) shuffle() {
	for i := range d.order {
		d.order[i] = i + 1
	}
	d.r.Shuffle(DeckSize, func(i, j int) { d.order[i], d.order[j] = d.order[j], d.order[i] })
	d.next = 0
}

// Draw implements Drawer: the next card of the shuffle, reshuffling the
// whole deck once every card has been dealt.
func (d *Deck) Draw() ResultCard {
	if d.next >= DeckSize {
		d.shuffle()
	}
	c := Cards[d.order[d.next]-1]
	d.next++
	d.drawn = append(d.drawn, c.N)
	return c
}

// Order returns the card numbers in the order the deck deals them.
func (d *Deck) Order() [DeckSize]int { return d.order }

// Drawn returns the numbers of every card dealt so far, in order: the trace
// of a turn's draws.
func (d *Deck) Drawn() []int { return d.drawn }

// Fixed is a Drawer that always deals the same card; tests use Fixed(37)
// (DELAY 1) to match the BGA reference engine's stub.
type Fixed int

// Draw implements Drawer.
func (f Fixed) Draw() ResultCard { return Card(int(f)) }

// Sequence is a Drawer dealing the given card numbers in order, then the
// last one forever; for tests.
type Sequence []int

// Draw implements Drawer.
func (s *Sequence) Draw() ResultCard {
	q := *s
	n := q[0]
	if len(q) > 1 {
		*s = q[1:]
	}
	return Card(n)
}

encode.gno

package engine

import (
	"strconv"
	"strings"

	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/cards/v0"
	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
)

// Compact text encodings of the engine's values, for what a realm keeps
// per turn: a struct stored on chain costs every field its type and
// value, so a turn's events as structs weigh over ten kilobytes, as one
// string a tenth of that. Fields are joined with '|', records with ';',
// gun slots with ',' and gun fields with ':'; none of the values (codes,
// hex ids, numbers) contain those characters. Decoding is lenient: a
// malformed number reads as 0, so a damaged record never breaks a view.

// EncodeEvents packs events into one string; DecodeEvents unpacks it.
func EncodeEvents(evs []Event) string {
	var b strings.Builder
	for i, e := range evs {
		if i > 0 {
			b.WriteByte(';')
		}
		b.WriteString(strings.Join([]string{
			strconv.Itoa(e.Seg), strconv.Itoa(e.Player), e.Kind, string(e.Action), e.From, e.To,
			strconv.Itoa(int(e.Facing)), boolStr(e.Down), strconv.Itoa(e.N), strconv.Itoa(e.Delay),
			e.Reason, strconv.Itoa(e.Card), e.Result, strconv.Itoa(e.Endurance), strconv.Itoa(e.Target),
			e.Hit, strconv.Itoa(e.Range), string(e.Gun), strconv.Itoa(e.GunID), strconv.Itoa(e.Step),
			e.Chart, e.Status,
		}, "|"))
	}
	return b.String()
}

// DecodeEvents unpacks what EncodeEvents produced.
func DecodeEvents(s string) []Event {
	if s == "" {
		return nil
	}
	recs := strings.Split(s, ";")
	evs := make([]Event, 0, len(recs))
	for _, r := range recs {
		f := strings.Split(r, "|")
		if len(f) != 22 {
			continue
		}
		evs = append(evs, Event{
			Seg: atoi(f[0]), Player: atoi(f[1]), Kind: f[2], Action: cards.Code(f[3]), From: f[4], To: f[5],
			Facing: hex.Dir(atoi(f[6])), Down: f[7] == "1", N: atoi(f[8]), Delay: atoi(f[9]),
			Reason: f[10], Card: atoi(f[11]), Result: f[12], Endurance: atoi(f[13]), Target: atoi(f[14]),
			Hit: f[15], Range: atoi(f[16]), Gun: GunType(f[17]), GunID: atoi(f[18]), Step: atoi(f[19]),
			Chart: f[20], Status: f[21],
		})
	}
	return evs
}

// EncodeCharacter packs a character, guns included; DecodeCharacter unpacks it.
func EncodeCharacter(c Character) string {
	guns := make([]string, 0, MaxGuns)
	for _, g := range c.Guns {
		if g.Type != NoGun {
			guns = append(guns, encodeGun(g))
		}
	}
	var killers [MaxPlayers]int
	for q, k := range c.Killers {
		if k {
			killers[q] = 1
		}
	}
	return strings.Join([]string{
		c.Hex, strconv.Itoa(int(c.Facing)), boolStr(c.Down), strconv.Itoa(c.Delay), strconv.Itoa(int(c.Status)),
		boolStr(c.PlayedFoot), boolStr(c.PlayedRun), boolStr(c.RanLastTurn), boolStr(c.Dropped),
		strconv.Itoa(c.Aim), c.AimHex, strconv.Itoa(c.Endurance), strconv.Itoa(c.Exhausted),
		strconv.Itoa(c.Serious), strconv.Itoa(c.GunArm), strconv.Itoa(c.OtherArm), strconv.Itoa(c.Leg),
		strings.Join(guns, ","),
		strconv.Itoa(c.AimAt), perSeat(killers), perSeat(c.SeriousFrom), perSeat(c.LegFrom),
		perSeat(c.Hurt),
	}, "|")
}

// perSeat packs one number per seat, "/"-separated.
func perSeat(v [MaxPlayers]int) string {
	s := make([]string, len(v))
	for i, n := range v {
		s[i] = strconv.Itoa(n)
	}
	return strings.Join(s, "/")
}

// seatValues unpacks what perSeat packed.
func seatValues(f string) (out [MaxPlayers]int) {
	if f == "" {
		return out
	}
	for i, n := range strings.Split(f, "/") {
		if i < MaxPlayers {
			out[i] = atoi(n)
		}
	}
	return out
}

// DecodeCharacter unpacks what EncodeCharacter produced.
func DecodeCharacter(s string) Character {
	f := strings.Split(s, "|")
	if len(f) != 23 {
		return Character{}
	}
	c := Character{
		Hex: f[0], Facing: hex.Dir(atoi(f[1])), Down: f[2] == "1", Delay: atoi(f[3]), Status: Status(atoi(f[4])),
		PlayedFoot: f[5] == "1", PlayedRun: f[6] == "1", RanLastTurn: f[7] == "1", Dropped: f[8] == "1",
		Aim: atoi(f[9]), AimHex: f[10], Endurance: atoi(f[11]), Exhausted: atoi(f[12]),
		Serious: atoi(f[13]), GunArm: atoi(f[14]), OtherArm: atoi(f[15]), Leg: atoi(f[16]),
		AimAt: atoi(f[18]),
	}
	for q, k := range seatValues(f[19]) {
		c.Killers[q] = k != 0
	}
	c.SeriousFrom = seatValues(f[20])
	c.LegFrom = seatValues(f[21])
	c.Hurt = seatValues(f[22])
	if f[17] != "" {
		for i, rec := range strings.Split(f[17], ",") {
			g, ok := decodeGun(rec)
			if i >= MaxGuns || !ok {
				break
			}
			c.Guns[i] = g
		}
	}
	return c
}

// EncodeChars packs the characters of a state (a turn's starting
// snapshot), seats in order; DecodeChars unpacks them.
func EncodeChars(cs []Character) string {
	parts := make([]string, len(cs))
	for i, c := range cs {
		parts[i] = EncodeCharacter(c)
	}
	return strings.Join(parts, ";")
}

// DecodeChars unpacks what EncodeChars produced.
func DecodeChars(s string) []Character {
	if s == "" {
		return nil
	}
	parts := strings.Split(s, ";")
	cs := make([]Character, len(parts))
	for i, part := range parts {
		cs[i] = DecodeCharacter(part)
	}
	return cs
}

// encodeGun packs a gun's fields, ':'-separated; decodeGun unpacks them.
func encodeGun(g Gun) string {
	return strings.Join([]string{
		strconv.Itoa(g.ID), string(g.Type), strconv.Itoa(int(g.Location)), boolStr(g.Cocked),
		strconv.Itoa(g.Shells), boolStr(g.Jammed), boolStr(g.Exploded),
	}, ":")
}

func decodeGun(s string) (Gun, bool) {
	g := strings.Split(s, ":")
	if len(g) != 7 {
		return Gun{}, false
	}
	return Gun{
		ID: atoi(g[0]), Type: GunType(g[1]), Location: GunLocation(atoi(g[2])), Cocked: g[3] == "1",
		Shells: atoi(g[4]), Jammed: g[5] == "1", Exploded: g[6] == "1",
	}, true
}

// EncodeGround packs the weapons lying on the board (a turn's ground at its
// start), ';'-separated records of id, hex and gun ("1|A-G6|1:colt45:0:0:6:0:0");
// DecodeGround unpacks them, skipping a malformed record.
func EncodeGround(ground []GroundGun) string {
	recs := make([]string, len(ground))
	for i, gg := range ground {
		recs[i] = strconv.Itoa(gg.ID) + "|" + gg.Hex + "|" + encodeGun(gg.Gun)
	}
	return strings.Join(recs, ";")
}

// DecodeGround unpacks what EncodeGround produced.
func DecodeGround(s string) []GroundGun {
	if s == "" {
		return nil
	}
	var out []GroundGun
	for _, rec := range strings.Split(s, ";") {
		f := strings.SplitN(rec, "|", 3)
		if len(f) != 3 {
			continue
		}
		if g, ok := decodeGun(f[2]); ok {
			out = append(out, GroundGun{ID: atoi(f[0]), Hex: f[1], Gun: g})
		}
	}
	return out
}

// EncodeInts packs numbers (the cards drawn in a turn); DecodeInts unpacks them.
func EncodeInts(ns []int) string {
	parts := make([]string, len(ns))
	for i, n := range ns {
		parts[i] = strconv.Itoa(n)
	}
	return strings.Join(parts, ",")
}

// DecodeInts unpacks what EncodeInts produced.
func DecodeInts(s string) []int {
	if s == "" {
		return nil
	}
	parts := strings.Split(s, ",")
	ns := make([]int, len(parts))
	for i, p := range parts {
		ns[i] = atoi(p)
	}
	return ns
}

func boolStr(b bool) string {
	if b {
		return "1"
	}
	return "0"
}

fire.gno

package engine

import (
	"strconv"
	"strings"
)

// HitLoc is a hit location on a FIRE card's hit chart (rule 13.5).
type HitLoc string

const (
	Miss     HitLoc = "-"
	Bullseye HitLoc = "BE" // the shooter picks the location (13.7)
	LegHit   HitLoc = "LEG"
	GunHit   HitLoc = "GUN"  // the gun arm
	ArmHit   HitLoc = "ARM"  // the other arm
	SideHit  HitLoc = "SIDE" // a flesh wound
	BodyHit  HitLoc = "BODY"
	CritHit  HitLoc = "CRIT"
	VitalHit HitLoc = "VITAL"
	HeadHit  HitLoc = "HEAD"
)

// Target statuses a FIRE card may list (rule 13.6), as the letters of a
// card's status string.
const (
	StatusMove = 'M' // played a foot action or dropped this turn (13.61)
	StatusRun  = 'R' // played a Run this turn (13.62)
	StatusDown = 'D' // is DOWN (13.63)
	StatusHead = 'H' // head counter shot at (13.64, not played)
)

// Band is an inclusive range of aim times or ranges; Hi < 0 is open-ended.
type Band struct{ Lo, Hi int }

// Contains reports whether n falls in the band.
func (b Band) Contains(n int) bool { return n >= b.Lo && (b.Hi < 0 || n <= b.Hi) }

// Chart is the hit chart of a FIRE card: a hit location per aim-time row
// and range column.
type Chart struct {
	Cols []Band
	Rows []ChartRow
}

// ChartRow is one aim-time row of a Chart.
type ChartRow struct {
	Aim   Band
	Cells []HitLoc
}

// Lookup is the preliminary hit location for an aim time and a range; off
// the chart is a miss (rule 13.5).
func (c *Chart) Lookup(aim, rng int) HitLoc {
	col := -1
	for i, b := range c.Cols {
		if b.Contains(rng) {
			col = i
			break
		}
	}
	if col < 0 {
		return Miss
	}
	for _, r := range c.Rows {
		if r.Aim.Contains(aim) {
			return r.Cells[col]
		}
	}
	return Miss
}

// Lesser is the hit the card's Target Status entries name: the chart's hit
// location other than a bullseye (every card has exactly one).
func (c *Chart) Lesser() HitLoc {
	for _, r := range c.Rows {
		for _, h := range r.Cells {
			if h != Miss && h != Bullseye {
				return h
			}
		}
	}
	return Miss
}

// Malfunction is the upper block of cards 101-108 (rule 13.3): whether the
// shot misfires per shell type, and the gun's fate on a second malfunction
// drawn after a misfire (13.31).
type Malfunction struct {
	Storebought bool // misfire with storebought shells
	Handloaded  bool // misfire with handloaded shells (the Colt 45's)
	CapAndBall  bool // misfire with cap-and-ball shells
	Second      string
}

// Second-draw penalties.
const (
	GunJams     = "jams"     // all shells crossed off; cannot fire until reloaded
	GunExplodes = "explodes" // cannot fire for the rest of the game
)

// fireCard is the transcription of a FIRE card's upper block: the hit chart
// as "<range bands>|<aim band>:<cell per column>|..." (bands "n", "n-m",
// "n+" or "n-m+") and the Target Status letters (M move, R run, D down,
// H head), each of which turns the card's lesser hit into a miss and, for
// M and R, a bullseye into the lesser hit.
type fireCard struct {
	chart, status string
}

// fireCards are cards 1 to 100, from the card images (assets/result_card_NNN.png).
var fireCards = [100]fireCard{
	{"0,1-5,6-12+|2-5:BE,-,-|6-8:BE,SIDE,-|9+:BE,BE,SIDE", "H"},         // 1
	{"0,1-5,6-9|3-6:BE,-,-|7:BE,SIDE,-|8+:BE,BE,SIDE", "M"},             // 2
	{"0-1,2-4|1-3:SIDE,-|4+:BE,SIDE", "H"},                              // 3
	{"0-2,3-7|1-6:SIDE,-|7+:BE,SIDE", "H"},                              // 4
	{"0-5,6-8|2-4:SIDE,-|5+:BE,SIDE", "D"},                              // 5
	{"0,1|3-4:BE,-|5-7:BE,SIDE|8+:BE,BE", "H"},                          // 6
	{"0,1-3|1-4:SIDE,-|5:BE,SIDE|6+:BE,BE", "H"},                        // 7
	{"0,1-4|2-6:BE,-|7+:BE,SIDE", ""},                                   // 8
	{"0-1,2-6|1-5:SIDE,-|6+:BE,SIDE", "D"},                              // 9
	{"0-3,4-5|2-6:SIDE,-|7-8:BE,-|9+:BE,SIDE", "H"},                     // 10
	{"0-2,3-6|4-8:SIDE,-|9+:BE,BE", ""},                                 // 11
	{"0-1,2-3,4-5|3-4:SIDE,SIDE,-|5-8:BE,SIDE,SIDE|9+:BE,BE,SIDE", "D"}, // 12
	{"0,1-3,4-7|6-8:BE,SIDE,-|9+:BE,BE,SIDE", ""},                       // 13
	{"0-7|4-6:SIDE|7+:BE", "M"},                                         // 14
	{"0,1,2-5|1-2:BE,-,-|3-7:BE,BE,-|8-9:BE,BE,SIDE", "D"},              // 15
	{"0-4|1-3:SIDE|4+:BE", "D"},                                         // 16
	{"0-5,6-11|8:SIDE,-|9+:BE,BE", ""},                                  // 17
	{"0-6|3-5:SIDE|6+:BE", ""},                                          // 18
	{"0,1|3-4:BE,-|5-7:BE,BODY|8+:BE,BE", ""},                           // 19
	{"0,1-5,6-12+|2-5:BE,-,-|6-8:BE,BODY,-|9+:BE,BE,BODY", ""},          // 20
	{"0-1,2,3|1-2:BODY,-,-|3-8:BE,BODY,-|9+:BE,BE,BODY", ""},            // 21
	{"0,1-3|2-6:BODY,-|7+:BE,BE", ""},                                   // 22
	{"0-3,4-7|2-7:BODY,-|8+:BE,BODY", ""},                               // 23
	{"0-4,5-10|4-6:BODY,-|7:BE,BODY|8+:BE,BE", ""},                      // 24
	{"0-5,6-8|2-4:BODY,-|5+:BE,BODY", "D"},                              // 25
	{"0-6|3-5:BODY|6+:BE", ""},                                          // 26
	{"0-1,2,3-5|1-2:BE,BODY,BODY|3-4:BE,BE,BODY|5+:BE,BE,BE", "R"},      // 27
	{"0-2,3-9|2-8:BODY,-|9+:BE,BE", ""},                                 // 28
	{"0,1-4|2-6:BE,-|7+:BE,BODY", "H"},                                  // 29
	{"0-1,2,3|8:BE,BODY,-|9+:BE,BE,BODY", ""},                           // 30
	{"0,1-3|1-4:BODY,-|5:BE,BODY|6+:BE,BE", "H"},                        // 31
	{"0-5,6-11|8:BODY,-|9+:BE,BE", ""},                                  // 32
	{"0-1,2-3,4|2-7:BE,-,-|8:BE,BODY,-|9+:BE,BE,BODY", "H"},             // 33
	{"0,1-2,3-6|1-2:BODY,-,-|3-7:BE,BODY,-|8+:BE,BE,BODY", "H"},         // 34
	{"0,1-4,5-8|1-5:BE,-,-|6-8:BE,BODY,-|9+:BE,BE,BODY", "H"},           // 35
	{"0,1-5,6-9|3-6:BE,-,-|7:BE,BODY,-|8+:BE,BE,BODY", "H"},             // 36
	{"0,1-2,3-4|1-4:BODY,-,-|5+:BE,BE,BODY", "DH"},                      // 37
	{"0-4|3-7:BODY|8+:BE", "D"},                                         // 38
	{"0-1,2-3,4-5|3-4:BODY,BODY,-|5-8:BE,BODY,BODY|9+:BE,BE,BODY", "D"}, // 39
	{"0-2,3-7|1-6:BODY,-|7+:BE,BODY", "MH"},                             // 40
	{"0-1,2-6|1-5:BODY,-|6+:BE,BODY", "H"},                              // 41
	{"0-1,2,3|8:BE,BODY,-|9+:BE,BE,BODY", ""},                           // 42
	{"0-2,3-4|5+:BE,BODY", "H"},                                         // 43
	{"0,1-4|2-6:BE,-|7+:BE,CRIT", "R"},                                  // 44
	{"0-3,4-9|1-5:CRIT,-|6+:BE,CRIT", "DH"},                             // 45
	{"0,1-2,3-6|1-2:CRIT,-,-|3-7:BE,CRIT,-|8+:BE,BE,CRIT", "DH"},        // 46
	{"0-5,6-11|2-7:CRIT,-|8+:BE,CRIT", ""},                              // 47
	{"0-1,2-3|4-7:CRIT,-|8+:BE,BE", "M"},                                // 48
	{"0,1,2-4|1-2:BE,-,-|3+:BE,BE,CRIT", "D"},                           // 49
	{"0-1,2-5|3-7:CRIT,-|8+:BE,CRIT", "H"},                              // 50
	{"0-3,4-6|5+:BE,CRIT", "MD"},                                        // 51
	{"0-1,2-3,4|2-3:BE,-,-|4-8:BE,CRIT,-|9+:BE,BE,CRIT", "D"},           // 52
	{"0-3,4-5|2-6:CRIT,-|7-8:BE,-|9+:BE,CRIT", "H"},                     // 53
	{"0,1-3|2-6:CRIT,-|7+:BE,BE", "M"},                                  // 54
	{"0-1,2,3|1-2:CRIT,-,-|3-8:BE,CRIT,-|9+:BE,BE,CRIT", "M"},           // 55
	{"0,1-3,4-7|6-8:BE,CRIT,-|9+:BE,BE,CRIT", "R"},                      // 56
	{"0-2,3-9|2-8:CRIT,-|9+:BE,BE", "M"},                                // 57
	{"0-7|4-6:CRIT|7+:BE", "H"},                                         // 58
	{"0,1-2,3-6|1-4:VITAL,-,-|5-8:BE,BE,-|9+:BE,BE,BE", "M"},            // 59
	{"0-2,3,4-7|2-5:BE,VITAL,-|6-8:BE,VITAL,VITAL|9+:BE,BE,BE", "R"},    // 60
	{"0-1,2,3-4|1-2:BE,VITAL,-|3+:BE,VITAL,VITAL", "M"},                 // 61
	{"0-1,2,3-5|3:VITAL,-,-|4-8:BE,VITAL,-|9+:BE,BE,VITAL", "DH"},       // 62
	{"0-2,3-4|2-4:VITAL,-|5-6:VITAL,VITAL|7+:BE,VITAL", "DH"},           // 63
	{"0-1,2-3,4-7|1-5:VITAL,-,-|6-7:VITAL,VITAL,-|8+:BE,BE,VITAL", "H"}, // 64
	{"0-1,2,3-6|4-6:VITAL,-,-|7-8:BE,VITAL,VITAL|9+:BE,BE,VITAL", "M"},  // 65
	{"0-1,2-5|1-5:BE,-|6-8:BE,HEAD|9+:BE,BE", "M"},                      // 66
	{"0,1-4,5-8|1-5:BE,-,-|6-8:BE,HEAD,-|9+:BE,BE,HEAD", ""},            // 67
	{"0-1,2-6|3:HEAD,-|4-6:BE,-|7+:BE,HEAD", "R"},                       // 68
	{"0-2,3-5|1-6:HEAD,-|7-8:BE,-|9+:BE,HEAD", "R"},                     // 69
	{"0-3|4-7:HEAD|8+:BE", ""},                                          // 70
	{"0,1-4|2-6:BE,-|7+:BE,HEAD", ""},                                   // 71
	{"0-1,2-4|1-3:HEAD,-|4+:BE,HEAD", "M"},                              // 72
	{"0-2,3-5,6+|1-4:BE,LEG,LEG|5+:BE,BE,LEG", "H"},                     // 73
	{"0-5,6-11|2-7:LEG,-|8+:BE,LEG", "RH"},                              // 74
	{"0-3,4-6|5+:BE,LEG", "MD"},                                         // 75
	{"0-3,4-9|1-5:LEG,-|6+:BE,LEG", "MH"},                               // 76
	{"0-2,3-4|2:BE,-|3+:BE,LEG", "MH"},                                  // 77
	{"0-2,3-4|5+:BE,LEG", "H"},                                          // 78
	{"0-4|1-3:LEG|4+:BE", "DH"},                                         // 79
	{"0-4,5-10|4-6:LEG,-|7:BE,LEG|8+:BE,BE", "DH"},                      // 80
	{"0,1-2|1-3:GUN,-|4-7:BE,GUN|8+:BE,BE", ""},                         // 81
	{"0-3,4-5,6-7|3-8:BE,GUN,-|9+:BE,BE,BE", "M"},                       // 82
	{"0-1,2-8|2-7:GUN,-|8+:BE,BE", "R"},                                 // 83
	{"0-1|3-8:GUN|9+:BE", ""},                                           // 84
	{"0-3,4-5|5-8:GUN,-|9+:BE,GUN", ""},                                 // 85
	{"0-3,4-5|1-6:GUN,-|7+:BE,GUN", "MD"},                               // 86
	{"0-2,3-6|1-5:GUN,-|6-7:BE,-|8+:BE,GUN", "R"},                       // 87
	{"0-1,2-3|5-6:BE,-|7+:BE,GUN", ""},                                  // 88
	{"0-4|2-8:GUN|9+:BE", "R"},                                          // 89
	{"0-2,3-6|4+:BE,GUN", "RD"},                                         // 90
	{"0,1-2|1-3:ARM,-|4-7:BE,ARM|8+:BE,BE", "H"},                        // 91
	{"0-3,4-5,6-7|3-8:BE,ARM,-|9+:BE,BE,BE", "MH"},                      // 92
	{"0-1,2-8|2-7:ARM,-|8+:BE,BE", "RH"},                                // 93
	{"0-1|3-8:ARM|9+:BE", "H"},                                          // 94
	{"0-3,4-5|5-8:ARM,-|9+:BE,ARM", "H"},                                // 95
	{"0-3,4-7|1-6:ARM,-|8+:BE,ARM", "MDH"},                              // 96
	{"0-2,3-6|1-5:ARM,-|6-7:BE,-|8+:BE,ARM", "RH"},                      // 97
	{"0-1,2-3|5-6:BE,-|7+:BE,ARM", "H"},                                 // 98
	{"0-4|2-8:ARM|9+:BE", "RH"},                                         // 99
	{"0-2,3-6|4+:BE,ARM", "RDH"},                                        // 100
}

// malfunctions are the blocks of cards 101 to 108.
var malfunctions = [8]Malfunction{
	{false, false, true, GunJams},    // 101
	{false, false, true, GunJams},    // 102
	{false, false, true, GunJams},    // 103
	{true, true, true, GunJams},      // 104
	{true, true, true, GunJams},      // 105
	{true, true, true, GunJams},      // 106
	{false, true, true, GunExplodes}, // 107
	{false, true, true, GunExplodes}, // 108
}

func parseChart(s string) *Chart {
	parts := strings.Split(s, "|")
	c := &Chart{}
	for _, b := range strings.Split(parts[0], ",") {
		c.Cols = append(c.Cols, parseBand(b))
	}
	for _, row := range parts[1:] {
		i := strings.IndexByte(row, ':')
		r := ChartRow{Aim: parseBand(row[:i])}
		for _, cell := range strings.Split(row[i+1:], ",") {
			r.Cells = append(r.Cells, HitLoc(cell))
		}
		if len(r.Cells) != len(c.Cols) {
			panic("fire chart row/column mismatch: " + s)
		}
		c.Rows = append(c.Rows, r)
	}
	return c
}

func parseBand(s string) Band {
	open := strings.HasSuffix(s, "+")
	s = strings.TrimSuffix(s, "+")
	lo, hi := s, s
	if i := strings.IndexByte(s, '-'); i >= 0 {
		lo, hi = s[:i], s[i+1:]
	}
	b := Band{Lo: atoi(lo), Hi: atoi(hi)}
	if open {
		b.Hi = -1
	}
	return b
}

func atoi(s string) int {
	n, err := strconv.Atoi(s)
	if err != nil {
		panic("fire chart: bad number " + strconv.Quote(s))
	}
	return n
}

gnomod.toml

module = "gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
gno = "0.9"

[addpkg]
  creator = "g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2"
  height = 758901
  max_deposit = "150000000ugnot"

guns.gno

package engine

// GunType identifies a weapon model.
type GunType string

const (
	// NoGun marks an empty gun slot.
	NoGun GunType = ""
	// Colt45 is the one-handed six-shooter every character starts with.
	Colt45 GunType = "colt45"
)

// GunSpec is the static data of a gun model (rules section 10 and the
// WEAPON LISTS).
type GunSpec struct {
	Name      string
	Capacity  int
	OneHanded bool
	Impact    byte // its line of the IMPACT TABLE (see Impact)
	Wielding  int  // its wielding factor: how far it can be thrown (16.21, 17.2)
	Striking  byte // its line of the STRIKING TABLE (see Striking)
}

// Spec returns the model's static data.
func (t GunType) Spec() GunSpec {
	switch t {
	case Colt45:
		return GunSpec{Name: "Colt 45", Capacity: 6, OneHanded: true, Impact: 'B', Wielding: 4, Striking: 'B'}
	}
	return GunSpec{}
}

// GunLocation is where a character keeps a gun (the boxes of the sheet).
type GunLocation int

const (
	Holstered GunLocation = iota
	GunHand
	OtherHand
	BothHands
)

// Hand codes used in plan strings: 0 = gun hand, 1 = other hand, 2 = both
// hands; HandGround, "g" in a gun move, is the hex the character stands in.
const (
	HandGun    = 0
	HandOther  = 1
	HandBoth   = 2
	HandGround = 3
)

// HandLocation maps a plan hand code to the location it designates.
func HandLocation(code int) (GunLocation, bool) {
	switch code {
	case HandGun:
		return GunHand, true
	case HandOther:
		return OtherHand, true
	case HandBoth:
		return BothHands, true
	}
	return 0, false
}

// String returns the location name used in JSON views.
func (l GunLocation) String() string {
	switch l {
	case Holstered:
		return "holstered"
	case GunHand:
		return "gun_hand"
	case OtherHand:
		return "other_hand"
	case BothHands:
		return "both_hands"
	}
	return "?"
}

// Gun is one weapon carried by a character. ID identifies it for the whole
// game (plans refer to it), even among several guns of the same model.
type Gun struct {
	ID       int
	Type     GunType
	Location GunLocation
	Cocked   bool
	Shells   int
	Jammed   bool // every shell crossed off; fires again once completely reloaded (13.31)
	Exploded bool // cannot fire for the rest of the game (13.31)
}

// CanFireFrom reports whether the gun is in a box it can shoot from (13.1):
// a one-handed gun in the gun hand or both hands, a two-handed one in both
// hands.
func (g Gun) CanFireFrom() bool {
	if g.Type == NoGun {
		return false
	}
	if g.Type.Spec().OneHanded {
		return g.Location == GunHand || g.Location == BothHands
	}
	return g.Location == BothHands
}

// MaxGuns is how many guns a character can carry (hands and holsters).
const MaxGuns = 3

// Guns is a character's weapons; empty slots have Type NoGun.
type Guns [MaxGuns]Gun

// Find returns the slot of the gun with the given id, or -1.
func (g Guns) Find(id int) int {
	for i, gun := range g {
		if gun.Type != NoGun && gun.ID == id {
			return i
		}
	}
	return -1
}

// NextID is a free id for a gun added to this character.
func (g Guns) NextID() int {
	n := 0
	for _, gun := range g {
		if gun.Type != NoGun && gun.ID > n {
			n = gun.ID
		}
	}
	return n + 1
}

// At returns the slot of the gun held at a location, or -1.
func (g Guns) At(loc GunLocation) int {
	for i, gun := range g {
		if gun.Type != NoGun && gun.Location == loc {
			return i
		}
	}
	return -1
}

// Firing returns the slot of the gun held in a box it can shoot from
// (rule 11.3), or -1.
func (g Guns) Firing() int {
	for i, gun := range g {
		if gun.CanFireFrom() {
			return i
		}
	}
	return -1
}

// Blocked reports whether a gun other than the one in slot except holds
// loc, or a hand box overlapping it: BOTH HANDS takes the gun hand and the
// other hand, and either hand is taken by a gun in BOTH HANDS.
func (g Guns) Blocked(loc GunLocation, except int) bool {
	for i, gun := range g {
		if i == except || gun.Type == NoGun || gun.Location == Holstered {
			continue
		}
		if gun.Location == loc || gun.Location == BothHands || loc == BothHands {
			return true
		}
	}
	return false
}

// Free returns an empty slot, or -1 when the character carries MaxGuns.
func (g Guns) Free() int {
	for i, gun := range g {
		if gun.Type == NoGun {
			return i
		}
	}
	return -1
}

// Count is the number of guns carried.
func (g Guns) Count() int {
	n := 0
	for _, gun := range g {
		if gun.Type != NoGun {
			n++
		}
	}
	return n
}

// startingGuns is the fixed loadout at game creation: a loaded, uncocked
// Colt 45 in the holster, gun 1.
func startingGuns() Guns {
	return Guns{{ID: 1, Type: Colt45, Location: Holstered, Cocked: false, Shells: 6}}
}

impact.gno

package engine

// PenaltyKind names the combat results of the IMPACT TABLE (rules 14.11,
// 14.12).
type PenaltyKind string

const (
	Kill          PenaltyKind = "kill"       // killed, out of the game
	Stun          PenaltyKind = "stun"       // draws N wound cards and loses aim
	Stagger       PenaltyKind = "stagger"    // thrown to a hex and facing drawn on two direction cards, then drops
	Serious       PenaltyKind = "serious"    // N fatigue cards at the start of every turn; may kill at the end
	DropGunHand   PenaltyKind = "gun_hand"   // the weapon in the gun hand drops in the hex
	GunArm        PenaltyKind = "gun_arm"    // -N aim time with the gun hand
	DropOtherHand PenaltyKind = "other_hand" // the weapon in the other hand drops in the hex
	OtherArm      PenaltyKind = "other_arm"  // -N aim time with the other hand
	LegWound      PenaltyKind = "leg"        // N fatigue cards per hex moved while upright
	Light         PenaltyKind = "light"      // draws N fatigue cards
	LoseAimHit    PenaltyKind = "lose_aim"   // loses the aim (STRIKING TABLE)
)

// Penalty is one combat result, with its number when the kind takes one.
type Penalty struct {
	Kind PenaltyKind
	N    int
}

// Impact is the IMPACT TABLE: the penalties a hit location inflicts for a
// gun's table line (rule 13.8). Only line B, the Colt 45's, is transcribed
// (from the VASSAL module's table); other lines come with their guns.
func Impact(line byte, loc HitLoc) []Penalty {
	if line != 'B' {
		return nil
	}
	switch loc {
	case VitalHit, CritHit:
		return []Penalty{{Kill, 0}}
	case BodyHit:
		return []Penalty{{Stun, 4}, {Stagger, 0}, {Serious, 2}}
	case SideHit:
		return []Penalty{{Stun, 2}, {Stagger, 0}}
	case HeadHit:
		return []Penalty{{Stun, 8}}
	case GunHit:
		return []Penalty{{Stun, 4}, {DropGunHand, 0}, {Serious, 1}, {GunArm, 4}}
	case ArmHit:
		return []Penalty{{Stun, 3}, {DropOtherHand, 0}, {Serious, 1}, {OtherArm, 4}}
	case LegHit:
		return []Penalty{{Stun, 3}, {Stagger, 0}, {Serious, 2}, {LegWound, 4}}
	}
	return nil
}

// Striking is the STRIKING TABLE (16.23): the penalties a throw (or, later,
// an attack) inflicts for a weapon's table line and the hit location. Only
// line B, the one-handed guns' (with the pail, dynamite, bottle and ammo
// sources), is transcribed; other lines come with their weapons.
func Striking(line byte, loc HitLoc) []Penalty {
	if line != 'B' {
		return nil
	}
	switch loc {
	case VitalHit:
		return []Penalty{{Light, 5}, {LoseAimHit, 0}}
	case CritHit:
		return []Penalty{{Light, 4}, {LoseAimHit, 0}}
	case BodyHit:
		return []Penalty{{Light, 3}}
	case SideHit:
		return []Penalty{{Light, 1}}
	case HeadHit:
		return []Penalty{{Light, 6}, {LoseAimHit, 0}}
	case GunHit:
		return []Penalty{{Light, 2}, {DropGunHand, 0}}
	case ArmHit:
		return []Penalty{{Light, 2}, {DropOtherHand, 0}}
	case LegHit:
		return []Penalty{{Light, 2}}
	}
	return nil
}

// StrikingBullseye is where a thrower's bullseye lands, its choice (the
// summary of actions): the location of the weapon's STRIKING TABLE line
// that hurts most, the HEAD for line B (LIGHT 6 and LOSE AIM).
func StrikingBullseye(line byte) HitLoc {
	return HeadHit
}

// Strengthen adds a STRENGTH's damage to each GUN ARM, OTHER ARM, LEG,
// SERIOUS, LIGHT and STUN penalty of a hit (20.21); the others are left as
// they are.
func Strengthen(pens []Penalty, n int) []Penalty {
	if n == 0 {
		return pens
	}
	out := make([]Penalty, len(pens))
	for i, pen := range pens {
		switch pen.Kind {
		case GunArm, OtherArm, LegWound, Serious, Light, Stun:
			pen.N += n
		}
		out[i] = pen
	}
	return out
}

plan.gno

package engine

import (
	"errors"
	"strconv"
	"strings"

	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/cards/v0"
	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
)

const (
	// MaxPlanEntries bounds the number of actions in a plan; five 1-point
	// actions already fill the budget.
	MaxPlanEntries = MaxActionPoints
	// MaxPlanLen bounds the plan string length.
	MaxPlanLen = 128
)

// Action is one card side chosen for the turn, with its committed choice.
type Action struct {
	Card   int
	Side   byte // cards.FrontSide or cards.BackSide
	Code   cards.Code
	Cost   int
	Dir    hex.Rel // committed relative direction, "" when the side takes none
	Gun    int     // id of the character's gun for a gun choice (Draw & Cock), 0 when none
	Ground int     // id of the gun on the ground to pick up (Draw & Cock, "g<id>"), 0 when none
	Hand   int     // destination hand code for a gun choice (HandGun...), -1 when the side takes none
	Opt    string  // option of Cock/Aim/Shoot, Shoot and Throw (OptCock...) or Strength (OptDamage, OptWield), "" when the side takes none
	Hex    string  // the hex named by an aim, a shot or a throw at a hex
	Target int     // the seat named by an aim, a shot or a throw at a character; -1 otherwise
	// Wield and Damage are what the STRENGTHs played on top of a Throw add
	// to the weapon's wielding factor and to the penalties (20.2), set by
	// Combine.
	Wield  int
	Damage int
	// Moves are the gun moves done when the action is revealed (10.22),
	// written before it in the plan string.
	Moves []GunMove
}

// GunMove is what a character may do with its guns, for free, each time it
// reveals an action (10.22): move the gun in BOTH HANDS to one hand, or drop
// a gun from a hand box into its hex. The other hand, like Draw & Cock's,
// comes with a second gun: Validate refuses it for now. Its plan string entry, "h<gun id>:<to>",
// comes before the action it goes with: To is HandGun (0) or HandOther (1),
// or "g" (HandGround) to drop it ("h1:g,1f:ahead": drop the Colt as the
// Advance is revealed). Whether the gun is there, where the move needs
// it, is checked when it is done: it may be one picked up earlier in the
// plan.
type GunMove struct {
	Gun int // id of the gun on the character's sheet
	To  int // HandGun, HandOther or HandGround
}

// String is the move's plan string entry.
func (m GunMove) String() string {
	to := strconv.Itoa(m.To)
	if m.To == HandGround {
		to = "g"
	}
	return "h" + strconv.Itoa(m.Gun) + ":" + to
}

// Shoot options: what a Cock/Aim/Shoot does (11.3), or a Shoot (shoot or
// nothing). Aiming and shooting name their target (11.31): a hex of the
// aim zone ("5f:aim:A-F6", "7f:shoot:A-F6") or a character by seat
// ("5f:aim:@1", "7f:shoot:@1"). A shot at a hex hits the character standing
// there when it goes off, and is wasted otherwise.
const (
	OptCock    = "cock"
	OptUncock  = "uncock"
	OptAim     = "aim"
	OptShoot   = "shoot"
	OptNothing = "nothing"
	// OptThrow is what a Throw does instead of nothing (17.1), naming its
	// target like a shot ("6b:throw:@1"; a bare "6b" does nothing).
	OptThrow = "throw"
)

// Strength options (20.2): a STRENGTH adds to the penalties ("7b:damage",
// also a bare "7b", what a STRENGTH does when its use is not stated) or
// to the wielding factor ("7b:wield") of the Throw it is played on top of.
const (
	OptDamage = "damage"
	OptWield  = "wield"
)

// Card 7's STRENGTH adds 4 to the wielding factor or 2 to the penalties.
const (
	StrengthWield  = 4
	StrengthDamage = 2
)

// IsShot reports whether the action fires the gun.
func (a Action) IsShot() bool { return cards.IsShooting(a.Code) && a.Opt == OptShoot }

// IsThrow reports whether the action throws the weapon in hand (17.1).
func (a Action) IsThrow() bool { return a.Code == cards.Throw && a.Opt == OptThrow }

// AimTime is the aim time printed on a shooting action or a Throw for a
// one- or two-handed weapon (13.52, 17.3).
func (a Action) AimTime(oneHanded bool) int {
	switch a.Code {
	case cards.Throw:
		if oneHanded {
			return 2
		}
		return 1
	case cards.CockAimShoot:
		if oneHanded {
			return 2
		}
		return 1
	case cards.Shoot:
		if oneHanded {
			return 1
		}
		return 0
	}
	return 0
}

// validHex is a loose check of a hex id in a plan string ("A-F6", "A-I11*"
// for a half-hex); the board decides whether it exists.
func validHex(h string) bool {
	if len(h) < 3 || len(h) > 8 {
		return false
	}
	for i := 0; i < len(h); i++ {
		c := h[i]
		if !(c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '*') {
			return false
		}
	}
	return true
}

func validOpt(code cards.Code, opt string) bool {
	switch code {
	case cards.CockAimShoot:
		return opt == OptCock || opt == OptUncock || opt == OptAim || opt == OptShoot
	case cards.Shoot:
		return opt == OptShoot || opt == OptNothing
	case cards.Throw:
		return opt == OptThrow || opt == OptNothing
	case cards.Strength:
		return opt == OptDamage || opt == OptWield
	}
	return false
}

// takesTarget reports whether the option names a target.
func takesTarget(opt string) bool { return opt == OptAim || opt == OptShoot || opt == OptThrow }

// Plan is the ordered stack of actions a player committed for the turn.
//
// Its string form, used as the transaction argument, is a comma-separated
// list of entries "<card><f|b>[:<choice>]", the choice being a relative
// direction for move and turn cards ("1f:ahead_left"), for Draw & Cock a
// gun and the hand it goes to ("9f:1:0": the character's gun 1 to the gun
// hand, "9f:g2:0": the gun lying in its hex with ground id 2; hand codes: 0
// gun hand, 1 other hand, 2 both hands), or for Cock/Aim/Shoot and
// Shoot the option ("5f:aim:A-F6", "7f:shoot:@1"; a bare "7f" does
// nothing), for Throw the same ("6b:throw:@1", a bare "6b" does nothing),
// for Strength its use ("7b:damage", "7b:wield"), e.g.
// "1f:ahead_left,2f:ahead,3f"; gun moves ("h1:g", GunMove) come before the
// action they go with and do not count as actions. An empty string is a
// pass.
type Plan []Action

// ParsePlan parses the plan string. It checks the syntax and that every card
// side exists; Validate checks the game rules.
func ParsePlan(s string) (Plan, error) {
	if s == "" {
		return Plan{}, nil
	}
	if len(s) > MaxPlanLen {
		return nil, errors.New("plan is too long")
	}
	entries := strings.Split(s, ",")
	plan := make(Plan, 0, len(entries))
	var moves []GunMove
	for _, e := range entries {
		if strings.HasPrefix(e, "h") {
			m, err := parseMove(e)
			if err != nil {
				return nil, err
			}
			if len(moves) >= MaxGuns {
				return nil, errors.New("too many gun moves before an action")
			}
			moves = append(moves, m)
			continue
		}
		a, err := parseEntry(e)
		if err != nil {
			return nil, err
		}
		a.Moves, moves = moves, nil
		plan = append(plan, a)
		if len(plan) > MaxPlanEntries {
			return nil, errors.New("too many actions in plan")
		}
	}
	if len(moves) > 0 {
		return nil, errors.New("a gun move goes before an action: it is done when that action comes up")
	}
	return plan, nil
}

// parseMove parses a gun move entry, "h<gun id>:<0|1|g>".
func parseMove(e string) (GunMove, error) {
	parts := strings.Split(e[1:], ":")
	if len(parts) != 2 {
		return GunMove{}, errors.New("gun move must be h<gun id>:<to> in " + strconv.Quote(e))
	}
	id, err := strconv.Atoi(parts[0])
	if err != nil || id < 1 {
		return GunMove{}, errors.New("invalid gun id in " + strconv.Quote(e))
	}
	switch parts[1] {
	case "0":
		return GunMove{Gun: id, To: HandGun}, nil
	case "1":
		return GunMove{Gun: id, To: HandOther}, nil
	case "g":
		return GunMove{Gun: id, To: HandGround}, nil
	}
	return GunMove{}, errors.New("a gun moves to 0 (gun hand), 1 (other hand) or g (the ground) in " + strconv.Quote(e))
}

func parseEntry(e string) (Action, error) {
	if e == "" {
		return Action{}, errors.New("empty action in plan")
	}
	choice := ""
	if i := strings.IndexByte(e, ':'); i >= 0 {
		e, choice = e[:i], e[i+1:]
		if choice == "" {
			return Action{}, errors.New("missing choice in " + strconv.Quote(e+":"))
		}
	}
	if len(e) < 2 {
		return Action{}, errors.New("invalid action " + strconv.Quote(e))
	}
	side := e[len(e)-1]
	num, err := strconv.Atoi(e[:len(e)-1])
	if err != nil || (side != cards.FrontSide && side != cards.BackSide) {
		return Action{}, errors.New("invalid action " + strconv.Quote(e))
	}
	def, ok := cards.Lookup(num, side)
	if !ok {
		return Action{}, errors.New("invalid action card " + strconv.Quote(e))
	}
	a := Action{Card: num, Side: side, Code: def.Code, Cost: def.Cost, Hand: -1, Target: -1}
	switch {
	case def.Code == cards.Strength:
		if choice == "" { // a STRENGTH whose use is not stated adds to the damage (20.2)
			choice = OptDamage
		}
		if !validOpt(def.Code, choice) {
			return Action{}, errors.New("invalid option " + strconv.Quote(choice) + " for " + def.Name + " (damage or wield)")
		}
		a.Opt = choice
	case cards.TakesTarget(def.Code):
		if choice == "" && (def.Code == cards.Shoot || def.Code == cards.Throw) {
			choice = OptNothing
		}
		opt, arg := choice, ""
		if i := strings.IndexByte(choice, ':'); i >= 0 {
			opt, arg = choice[:i], choice[i+1:]
		}
		if !validOpt(def.Code, opt) {
			return Action{}, errors.New("invalid option " + strconv.Quote(opt) + " for " + def.Name)
		}
		if takesTarget(opt) {
			switch {
			case strings.HasPrefix(arg, "@"):
				seat, err := strconv.Atoi(arg[1:])
				if err != nil || seat < 0 || seat >= MaxPlayers {
					return Action{}, errors.New("invalid character " + strconv.Quote(arg) + " to " + opt + " at")
				}
				a.Target = seat
			case validHex(arg):
				a.Hex = arg
			default:
				return Action{}, errors.New(opt + " needs a hex or a character to " + opt + " at, e.g. " + strconv.Quote(e+":"+opt+":A-F6") + " or " + strconv.Quote(e+":"+opt+":@1"))
			}
		} else if arg != "" {
			return Action{}, errors.New("option " + strconv.Quote(opt) + " takes no argument")
		}
		a.Opt = opt
	case choice == "":
	case def.Choice.NeedsGun():
		parts := strings.Split(choice, ":")
		if len(parts) != 2 {
			return Action{}, errors.New("gun choice must be <gun id>:<hand> in " + strconv.Quote(e+":"+choice))
		}
		ref := strings.TrimPrefix(parts[0], "g")
		id, err := strconv.Atoi(ref)
		if err != nil || id < 1 {
			return Action{}, errors.New("invalid gun id " + strconv.Quote(parts[0]))
		}
		hand, err := strconv.Atoi(parts[1])
		if _, ok := HandLocation(hand); err != nil || !ok {
			return Action{}, errors.New("invalid hand " + strconv.Quote(parts[1]) + " (0 gun hand, 1 other hand, 2 both hands)")
		}
		if ref != parts[0] {
			a.Ground = id
		} else {
			a.Gun = id
		}
		a.Hand = hand
	default:
		r, ok := hex.ParseRel(choice)
		if !ok {
			return Action{}, errors.New("invalid direction " + strconv.Quote(choice))
		}
		a.Dir = r
	}
	return a, nil
}

// String is the canonical plan string, parseable by ParsePlan.
func (p Plan) String() string {
	var b strings.Builder
	for i, a := range p {
		if i > 0 {
			b.WriteByte(',')
		}
		for _, m := range a.Moves {
			b.WriteString(m.String())
			b.WriteByte(',')
		}
		b.WriteString(strconv.Itoa(a.Card))
		b.WriteByte(a.Side)
		if a.Gun > 0 || a.Ground > 0 {
			b.WriteByte(':')
			if a.Ground > 0 {
				b.WriteByte('g')
				b.WriteString(strconv.Itoa(a.Ground))
			} else {
				b.WriteString(strconv.Itoa(a.Gun))
			}
			b.WriteByte(':')
			b.WriteString(strconv.Itoa(a.Hand))
		} else if a.Opt != "" && !((a.Code == cards.Shoot || a.Code == cards.Throw) && a.Opt == OptNothing) {
			b.WriteByte(':')
			b.WriteString(a.Opt)
			if takesTarget(a.Opt) {
				b.WriteByte(':')
				if a.Target >= 0 {
					b.WriteByte('@')
					b.WriteString(strconv.Itoa(a.Target))
				} else {
					b.WriteString(a.Hex)
				}
			}
		} else if a.Dir != "" {
			b.WriteByte(':')
			b.WriteString(string(a.Dir))
		}
	}
	return b.String()
}

// Cost is the total time points of the plan.
func (p Plan) Cost() int {
	n := 0
	for _, a := range p {
		n += a.Cost
	}
	return n
}

// Has reports whether the plan holds the action.
func (p Plan) Has(code cards.Code) bool {
	for _, a := range p {
		if a.Code == code {
			return true
		}
	}
	return false
}

// PlayedFoot reports whether the plan holds any foot action ([H12]).
func (p Plan) PlayedFoot() bool {
	for _, a := range p {
		if def, ok := cards.Lookup(a.Card, a.Side); ok && def.Kind == cards.KindFoot {
			return true
		}
	}
	return false
}

// Validate checks the plan against the selection rules for the character
// that will play it (port of the BGA actConfirmPlan checks).
func (p Plan) Validate(c Character) error {
	used := map[int]bool{}
	for i, a := range p {
		def, ok := cards.Lookup(a.Card, a.Side)
		if !ok {
			return errors.New("invalid action card")
		}
		if !cards.Enabled(def.Code) {
			return errors.New("that action is not available yet")
		}
		if used[a.Card] { // rule 7.2: one side per card, once per turn
			return errors.New("you cannot use both sides of a card")
		}
		used[a.Card] = true
		// The gun may be one the plan picks up first (its id is the sheet's
		// next): whether it is there is checked when the move is done.
		for _, m := range a.Moves {
			if m.To == HandOther { // the other hand comes with a second gun, as for Draw & Cock
				return errors.New("a gun moves to the gun hand or the ground for now")
			}
			if m.To != HandGun && m.To != HandGround {
				return errors.New("a gun moves to the gun hand or the ground")
			}
		}
		switch {
		case def.Code == cards.Strength:
			if !validOpt(def.Code, a.Opt) {
				return errors.New("choose what the strength adds to")
			}
			// Played just before (on top of) the action it combines with
			// (20.1): a Throw, until the attacks come.
			if i+1 >= len(p) || p[i+1].Code != cards.Throw {
				return errors.New("strength is played just before a throw")
			}
		case cards.TakesTarget(def.Code):
			if !validOpt(def.Code, a.Opt) {
				if def.Code == cards.Throw {
					return errors.New("choose whether to throw")
				}
				return errors.New("choose what to do with the gun")
			}
			if takesTarget(a.Opt) && a.Hex == "" && a.Target < 0 {
				return errors.New("choose what to " + a.Opt + " at")
			}
		case def.Choice.IsAheadRel():
			if !a.Dir.IsAhead() {
				return errors.New("choose a forward direction")
			}
		case def.Choice.IsBackRel():
			if !a.Dir.IsBack() {
				return errors.New("choose a backward direction")
			}
		case def.Choice.NeedsGun():
			if a.Gun == 0 && a.Ground == 0 {
				return errors.New("choose the gun to draw")
			}
			if a.Hand == HandOther { // the other hand comes with a second gun
				return errors.New("only the gun hand or both hands can take a gun for now")
			}
			dest, _ := HandLocation(a.Hand)
			slot := -1
			if a.Gun != 0 { // a gun on the ground is checked against the hex when the action executes
				if slot = c.Guns.Find(a.Gun); slot < 0 {
					return errors.New("you have no such gun")
				}
				if c.Guns[slot].Location == dest {
					return errors.New("that gun is already there")
				}
			}
			if c.Guns.Blocked(dest, slot) {
				return errors.New("that hand already holds a gun")
			}
		default:
			if a.Dir != "" {
				return errors.New("that action takes no direction")
			}
			if a.Gun != 0 || a.Ground != 0 {
				return errors.New("that action takes no gun")
			}
		}
	}
	budget := MaxActionPoints - c.Delay // [H5]
	if p.Cost() > budget {
		return errors.New("those actions cost more time points than you have")
	}
	// Prerequisite chains (rule 9.21).
	if p.Has(cards.Run) && !p.Has(cards.Advance) {
		return errors.New("run can only be played together with advance")
	}
	if p.Has(cards.Sprint) {
		if !p.Has(cards.Run) {
			return errors.New("sprint can only be played together with run")
		}
		if !c.RanLastTurn { // rule 9.23: speed is built up over two turns
			return errors.New("sprint can only be played after a run on the previous turn")
		}
	}
	return nil
}

// Combine folds each run of STRENGTHs into the Throw it is played on top
// of (20.1): treated as part of that action, revealed with it, their time
// points added to its own, their bonuses in its Wield and Damage, their
// gun moves done as it is revealed. Validate has checked that each
// STRENGTH comes just before a Throw; one that does not is dropped.
func (p Plan) Combine() Plan {
	out := make(Plan, 0, len(p))
	var (
		cost, wield, damage int
		moves               []GunMove
	)
	for _, a := range p {
		if a.Code == cards.Strength {
			cost += a.Cost
			if a.Opt == OptWield {
				wield += StrengthWield
			} else {
				damage += StrengthDamage
			}
			moves = append(moves, a.Moves...)
			continue
		}
		if a.Code == cards.Throw {
			a.Cost += cost
			a.Wield += wield
			a.Damage += damage
			if len(moves) > 0 {
				a.Moves = append(moves, a.Moves...)
			}
		}
		cost, wield, damage, moves = 0, 0, 0, nil
		out = append(out, a)
	}
	return out
}

resolve.gno

package engine

import (
	"strings"

	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/cards/v0"
	"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
)

// Event kinds.
const (
	EvMove         = "move"          // From, To, Facing, Down, Action (Reason "stagger" when thrown by a hit)
	EvTurn         = "turn"          // Facing, Action (Reason "stagger" when thrown by a hit)
	EvFlip         = "flip"          // Down, Action (empty for a DROP penalty)
	EvDelay        = "delay"         // N gained, Reason, Card drawn (0 for crawl), Result penalty, Endurance crossed off, Delay = running total once this card is counted
	EvCancel       = "cancel"        // Action, Reason (To = the obstacle in the way for no_los)
	EvDraw         = "draw"          // Gun moved from From (holster, a hand, or "ground" with N = its ground id) to To (a hand) and cocked, unless jammed (Result "jammed")
	EvLoad         = "load"          // a shell loaded in the gun in both hands, N shells now, uncocked; Result "unjammed" when that completes a jammed gun
	EvCock         = "cock"          // Gun cocked
	EvUncock       = "uncock"        // Gun uncocked
	EvAim          = "aim"           // N = AIM points after aiming, To = the hex they sit on, Target = the seat they follow (-1 for a hex)
	EvLoseAim      = "lose_aim"      // Reason (To = the obstacle in the way for no_los)
	EvNothing      = "nothing"       // a Shoot used to do nothing, or a shot held at a hex nobody stands in (Reason empty_hex, To = the hex) or at a target out of sight (Reason no_los, To = its hex, Target = its seat) or out of the fight (Reason out_of_fight, To = its hex, Target = its seat): keeps the aim
	EvShot         = "shot"          // Card, Target = the seat shot at (whoever stood in the hex named, for a shot at a hex), To = the hex shot at, Hit (final location or Miss), Range, N = aim time, Reason "" | out_of_zone | misfire
	EvThrow        = "throw"         // like a shot: Card, Target, To = the hex thrown at, Hit, Range, N = aim time, Chart, Status, Gun, GunID, Reason "" | out_of_zone; the weapon then lands (EvDropGun, Reason throw)
	EvMalfunction  = "malfunction"   // Card, Result (no_effect, misfire, jams, explodes, no_penalty), Gun, GunID
	EvWildShot     = "wild_shot"     // Gun went off without hitting anything: uncocked, one shell less
	EvWound        = "wound"         // Player hit: Result = penalty kind (Kill, Stun...), N
	EvDirection    = "direction"     // Card drawn as a direction card: To = its HEX line
	EvDropGun      = "drop_gun"      // Gun fell from From (hand) to the hex To, N = its ground id; Reason throw for a thrown weapon landing, gun_move for one let go (10.22)
	EvMoveGun      = "move_gun"      // a gun move (10.22): Gun moved from From (both hands) to To (a hand), as it was
	EvPassOut      = "pass_out"      // end of turn: more delay than endurance two turns in a row
	EvSeriousCheck = "serious_check" // end of showdown: Card, N = DELAY + SERIOUS points (4 kills)
	EvVP           = "vp"            // end of turn: victory points (rule 15), N = points (< 0 for a loss), Reason = the award (VPSurvive...)
	EvRunAway      = "run_away"      // the character moved off the map (15.5): From = the edge hex it left, Facing = the way it went, Action
)

// Delay and cancel reasons.
const (
	ReasonCrawl      = "crawl"        // moving while down (rule 9.2)
	ReasonSprint     = "sprint"       // sprinting draws a delay card (rule 9.23)
	ReasonLeap       = "leap"         // leap/drop draws two delay cards (rule 9.4)
	ReasonOccupied   = "occupied"     // ending a move in an occupied hex (rule 9.24)
	ReasonFence      = "fence"        // moving or staggering across a fence (rule 35.2)
	ReasonObstacle   = "obstacle"     // moving or staggering onto or off an obstacle (rule 36.4)
	ReasonDrop       = "drop"         // a DROP penalty draws three delay cards (rule 14.11)
	ReasonStun       = "stun"         // a STUN draws wound cards (14.11)
	ReasonLight      = "light"        // a LIGHT draws fatigue cards (14.11)
	ReasonSerious    = "serious"      // fatigue cards at the start of the turn (14.12)
	ReasonLeg        = "leg"          // fatigue cards per hex moved upright (14.12)
	ReasonTime       = "time"         // not executed by the end of segment 5 (rule 7.53)
	ReasonNoGun      = "no_gun"       // no gun in the box the action needs (11.3); a gun move of a gun the character no longer has
	ReasonNotInHand  = "not_in_hand"  // a gun move dropping a gun that is not in a hand box (10.22)
	ReasonNotBoth    = "not_both"     // a gun move to a hand of a gun that is not in both hands (10.22)
	ReasonGunDropped = "gun_dropped"  // a gun move dropped the gun the character aims with: its AIM points go
	ReasonHandFull   = "hand_full"    // the destination hand already holds a gun
	ReasonNoRoom     = "no_room"      // the character already carries MaxGuns weapons
	ReasonNotCocked  = "not_cocked"   // shooting an uncocked gun (13.1)
	ReasonEmpty      = "empty"        // shooting a gun without shells (13.1)
	ReasonJammed     = "jammed"       // shooting or cocking a jammed gun not completely reloaded yet (13.31)
	ReasonFull       = "full"         // loading a gun already holding its Ammo limit (10.42)
	ReasonBroken     = "broken"       // using or loading an exploded gun (13.31)
	ReasonNoTarget   = "no_target"    // the character named is out of the fight (12.6), or is the shooter, or no such seat
	ReasonOutOfZone  = "out_of_zone"  // the target is in the blind zone (8.32, 12.41)
	ReasonNoLOS      = "no_los"       // no line of sight to the target, an obstacle in the way by the heights (31): an aim is cancelled, a shot is held, AIM points are lost
	ReasonReveal     = "reveal"       // revealing an action other than Turn or a gun action (12.44)
	ReasonTransfer   = "transfer"     // a new target more than one hex from the markers (12.5)
	ReasonOwnHex     = "own_hex"      // a new target moving the markers into or out of the character's own hex (12.5)
	ReasonNoHex      = "no_hex"       // aiming at a hex that is not on the board
	ReasonShot       = "shot"         // aim spent by a shot (12.43)
	ReasonStagger    = "stagger"      // thrown by a STAGGER penalty
	ReasonMisfire    = "misfire"      // the shot was cancelled by a MALFUNCTION
	ReasonEmptyHex   = "empty_hex"    // a shot at a hex nobody stood in: held (EvNothing)
	ReasonOutOfFight = "out_of_fight" // a shot at a character killed, passed out, surrendered or run away: held (EvNothing)
	ReasonOutOfRange = "out_of_range" // a throw farther than the weapon's wielding factor (17.2)
	ReasonThrow      = "throw"        // aim spent by a throw (16.13); a thrown weapon landing (17.4)
	ReasonGunMove    = "gun_move"     // a gun move dropping the gun in the hex (10.22)
)

// Malfunction results.
const (
	MalfNoEffect  = "no_effect"  // discarded, another card drawn (13.3)
	MalfMisfire   = "misfire"    // the shot is cancelled (13.3)
	MalfNoPenalty = "no_penalty" // second draw was a FIRE: the gun is fine (13.32)
)

// LoadUnjammed is the Result of a load that completes a jammed gun (13.31).
const LoadUnjammed = "unjammed"

// DrawJammed is the Result of a Draw & Cock that moves a jammed gun: it is
// not cocked (13.31).
const DrawJammed = "jammed"

func jammedResult(g Gun) string {
	if g.Jammed {
		return DrawJammed
	}
	return ""
}

// Event is one thing that happened during resolution, in order. Seg is 0
// for turn-start events and EndOfTurn for those after segment 5.
type Event struct {
	Seg       int
	Player    int
	Kind      string
	Action    cards.Code
	From      string
	To        string
	Facing    hex.Dir
	Down      bool
	N         int
	Delay     int
	Reason    string
	Card      int     // the result card drawn (0 when none)
	Result    string  // a card's penalty, a malfunction result or a wound's penalty kind
	Endurance int     // endurance boxes crossed off by a wound or fatigue card
	Target    int     // the seat shot at, for shots
	Hit       string  // the final hit location of a shot (Miss "-")
	Range     int     // the range of a shot, in hexes
	Gun       GunType // the gun's model, for gun events
	GunID     int     // the gun's id, for gun events
	Step      int     // which part of the segment it belongs to (StepShots, StepEnd, StepAction+seat), 0 outside the segments
	Chart     string  // a shot's preliminary hit read on the FIRE card's chart, before Target Status ("" when no chart was read)
	Status    string  // the Target Status letters (StatusMove...) that changed a shot's hit, "" when none did
}

// Steps of a segment, in the order they resolve: the shots (7.52), each
// seat's action in seat order, then the end of the segment (the
// occupied-hex penalty, combat results, aims out of the zone). Events of
// one step happened together; a replay shows the steps one after the
// other. Turn-start and end-of-turn events have no step (0).
const (
	StepShots  = 1
	StepEnd    = 2
	StepAction = 3 // + the seat acting
)

// stamp marks the events with their step.
func stamp(evs []Event, step int) {
	for i := range evs {
		evs[i].Step = step
	}
}

// pending is the combat results a shot inflicts on a seat, applied at the
// end of the segment (14.1), with the shooter for STAGGER's "Long" hex.
type pending struct {
	from int
	pens []Penalty
}

// Resolve plays the plans, one per seat, over the five segments of a turn
// (rules 5.5, 6, 7, 9, 12, 13, 14), deterministic for a given Drawer; the
// state given is left as it is. Choices were committed up front and are
// resolved against each character's live state as the stacks play out.
//
// Each segment, every alive character whose next action is due
// (usedTime + cost + delay <= segment) executes it once, shots first
// (7.52), in seat order. Delay gained during a segment and the results of
// hits take effect from the end of the segment ([H6], 14.1). Actions still
// pending after segment 5 are cancelled.
func Resolve(board *hex.Board, st State, plans []Plan, d Drawer) (State, []Event) {
	st.Chars = CloneChars(st.Chars)
	n := len(st.Chars)
	// A STRENGTH is part of the Throw it is played on top of (20.1).
	combined := make([]Plan, n)
	for p := 0; p < n && p < len(plans); p++ { // a seat without a plan passes
		combined[p] = plans[p].Combine()
	}
	plans = combined
	var (
		used = make([]int, n)
		idx  = make([]int, n)
		evs  []Event
	)
	// Turn start: SERIOUS wounds draw fatigue cards (5.3), on the sheet
	// before segment 1.
	startDelay := make([]int, n)
	for p := range st.Chars {
		c := &st.Chars[p]
		startDelay[p] = c.Delay
		if c.Status != Alive {
			continue
		}
		// Each SERIOUS point draws a fatigue card, put down to the seat whose wound gave it.
		for i := 0; i < c.Serious; i++ {
			c.Delay += drawCard(p, c, 0, ReasonSerious, fatigueLine, pointFrom(c.SeriousFrom, i), d, &evs)
		}
	}
	runningDelay(evs, startDelay)
	// Reveal the first actions (5.4): aim may be lost or moved (12.44, 12.5).
	for p := range st.Chars {
		if st.Chars[p].Status == Alive && len(plans[p]) > 0 {
			reveal(board, p, &st, plans[p][0], 0, &evs)
		}
	}
	due := func(p int, seg int) bool {
		c := &st.Chars[p]
		return c.Status == Alive && idx[p] < len(plans[p]) && used[p]+plans[p][idx[p]].Cost+c.Delay <= seg
	}
	advance := func(p int, seg int) {
		used[p] += plans[p][idx[p]].Cost
		idx[p]++
		if st.Chars[p].Status == Alive && idx[p] < len(plans[p]) {
			reveal(board, p, &st, plans[p][idx[p]], seg, &evs)
		}
	}
	for seg := 1; seg <= Segments; seg++ {
		var (
			gained  = make([]int, n)
			moved   = make([]bool, n)
			shot    = make([]bool, n)
			results = make([][]pending, n)
			first   = len(evs) // events of this segment start here
		)
		// Shots and throws are resolved before the other actions (7.52,
		// 16.14), simultaneously.
		for p := 0; p < n; p++ {
			if !due(p, seg) || !(plans[p][idx[p]].IsShot() || plans[p][idx[p]].IsThrow()) {
				continue
			}
			var (
				target int
				pens   []Penalty
			)
			if plans[p][idx[p]].IsThrow() {
				target, pens = throw(board, p, &st, plans[p][idx[p]], seg, d, &evs)
			} else {
				target, pens = shoot(board, p, &st, plans[p][idx[p]], seg, d, &evs)
			}
			if target >= 0 && len(pens) > 0 {
				results[target] = append(results[target], pending{from: p, pens: pens})
			}
			shot[p] = true
			advance(p, seg)
		}
		stamp(evs[first:], StepShots)
		for p := 0; p < n; p++ {
			if shot[p] || !due(p, seg) {
				continue
			}
			from := len(evs)
			a := plans[p][idx[p]]
			g, executed := execute(board, p, a, &st, seg, d, &evs)
			gained[p] += g
			advance(p, seg)
			if executed && cards.IsMove(a.Code) {
				moved[p] = true
			}
			stamp(evs[from:], StepAction+p)
		}
		end := len(evs)

		// Occupied-hex penalty (9.24): when a mover ends the segment in
		// another character's hex, both draw one delay card (once each).
		for p := 0; p < n; p++ {
			if st.Chars[p].Status != Alive {
				continue
			}
			for o := 0; o < n; o++ {
				if o == p || st.Chars[o].Status != Alive || st.Chars[p].Hex != st.Chars[o].Hex || !(moved[p] || moved[o]) {
					continue
				}
				gained[p] += drawDelay(p, &st.Chars[p], seg, ReasonOccupied, d, &evs)
				break
			}
		}

		// Combat results go into effect at the end of the segment (14.1).
		for p := 0; p < n; p++ {
			for _, r := range results[p] {
				gained[p] += applyPenalties(board, p, &st, r, seg, d, &evs)
			}
		}
		// A target out of the aim zone (12.41) or out of sight (31.1) at the
		// end of the segment loses the aim.
		for p := 0; p < n; p++ {
			c := &st.Chars[p]
			if c.Status != Alive || c.Aim == 0 {
				continue
			}
			var t *Character // the markers follow a character...
			if c.AimAt >= 0 {
				t = st.char(c.AimAt)
				if t == nil {
					loseAim(p, c, seg, ReasonNoTarget, &evs)
					continue
				}
				if t.Status == RanAway { // gone off the map: nothing left to aim at
					loseAim(p, c, seg, ReasonNoTarget, &evs)
					continue
				}
				if t.Status != Alive { // the aim stays on a fallen target (12.6)
					continue
				}
			}
			if !board.InAimZone(c.Hex, c.Facing, aimTarget(c, &st)) {
				loseAim(p, c, seg, ReasonOutOfZone, &evs)
				continue
			}
			if clear, blocker := canSee(board, c, c.AimHex, t); !clear { // ...or sit on a hex
				loseAimAt(p, c, seg, ReasonNoLOS, blocker, &evs)
			}
		}

		stamp(evs[end:], StepEnd)

		// Delay gained this segment takes effect next segment (6.1, [H6]);
		// the events carry the running total as the cards come.
		for p := 0; p < n; p++ {
			startDelay[p] = st.Chars[p].Delay
			if st.Chars[p].Status == Killed {
				continue // the delay gained before the kill is moot
			}
			st.Chars[p].Delay += gained[p]
		}
		runningDelay(evs[first:], startDelay)
	}

	// Cancel any action not executed by the end of segment 5 (7.53).
	for p := 0; p < n; p++ {
		if st.Chars[p].Status != Alive {
			continue
		}
		for i := idx[p]; i < len(plans[p]); i++ {
			evs = append(evs, Event{Seg: EndOfTurn, Player: p, Kind: EvCancel, Action: plans[p][i].Code, Reason: ReasonTime})
		}
	}
	return st, evs
}

// aimTarget is the hex the AIM markers of c sit on: the hex of the
// character they follow, or a hex.
func aimTarget(c *Character, st *State) string {
	if t := st.char(c.AimAt); c.AimAt >= 0 && t != nil {
		return t.Hex
	}
	return c.AimHex
}

// standingIn is the seat of the first alive character but seat p standing
// in hex id, NoSeat when nobody does (two characters may share a hex:
// a shot at the hex finds the first in seat order).
func standingIn(st *State, id string, p int) int {
	for q := range st.Chars {
		if q != p && st.Chars[q].Status == Alive && st.Chars[q].Hex == id {
			return q
		}
	}
	return NoSeat
}

// runningDelay stamps each delay event with the delay points its player
// holds once that card is counted, starting from the given totals.
func runningDelay(evs []Event, start []int) {
	total := append([]int(nil), start...)
	for i := range evs {
		if evs[i].Kind == EvDelay {
			total[evs[i].Player] += evs[i].N
			evs[i].Delay = total[evs[i].Player]
		}
	}
}

// reveal applies rules 12.44, 12.5 and 17.11 when an action becomes the
// next one: the aim is lost unless the action is a Turn, an aim, a shot or
// a throw (which spend it when they go off); cocking, uncocking or doing
// nothing with a gun lose it like any other action. An aim, a shot or a
// throw naming a new target keeps the markers only within one hex of their
// place, and never moves them into or out of the character's own hex (both
// targets in it, or both out of it); a shot or a throw moves them onto its
// target.
func reveal(board *hex.Board, p int, st *State, a Action, seg int, evs *[]Event) {
	for _, m := range a.Moves {
		moveGun(p, st, m, seg, evs)
	}
	c := &st.Chars[p]
	if c.Aim == 0 {
		return
	}
	switch {
	case a.Code == cards.Turn:
	case !cards.TakesTarget(a.Code) || !takesTarget(a.Opt):
		loseAim(p, c, seg, ReasonReveal, evs)
	default:
		// The target named: the markers move onto it within one hex (12.5).
		named := a.Hex
		if t := st.char(a.Target); a.Target >= 0 && t != nil {
			named = t.Hex
		}
		old := aimTarget(c, st)
		same := (a.Target >= 0 && a.Target == c.AimAt) || (a.Target < 0 && c.AimAt < 0 && a.Hex == c.AimHex)
		if board.Distance(old, named) > 1 {
			loseAim(p, c, seg, ReasonTransfer, evs)
		} else if !same && (old == c.Hex) != (named == c.Hex) {
			loseAim(p, c, seg, ReasonOwnHex, evs)
		} else if a.Opt == OptShoot || a.Opt == OptThrow {
			c.AimHex = a.Hex // "" when the shot names a character
			c.AimAt = a.Target
		}
	}
}

// pointFrom is the seat that gave the i-th of a wound's points, counted
// seat by seat through from; NoSeat past them (points nobody is put down
// for).
func pointFrom(from [MaxPlayers]int, i int) int {
	for q, n := range from {
		if i < n {
			return q
		}
		i -= n
	}
	return NoSeat
}

// hasKill tells whether a hit's penalties include a KILL.
func hasKill(pens []Penalty) bool {
	for _, pen := range pens {
		if pen.Kind == Kill {
			return true
		}
	}
	return false
}

func loseAim(p int, c *Character, seg int, reason string, evs *[]Event) {
	loseAimAt(p, c, seg, reason, "", evs)
}

// loseAimAt is loseAim with the hex the event names: the obstacle in the
// way when the target is out of sight.
func loseAimAt(p int, c *Character, seg int, reason, to string, evs *[]Event) {
	if c.Aim == 0 {
		return
	}
	clearAim(c)
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvLoseAim, Reason: reason, To: to})
}

// cardLine is which line of a drawn result card is read.
type cardLine int

const (
	delayLine   cardLine = iota // delay card (14.21): DELAY line, no endurance
	fatigueLine                 // fatigue card (14.22): DELAY line, crosses off endurance
	woundLine                   // wound card (14.23): WOUND line, crosses off endurance
)

// drawCard draws one result card for c and reads the chosen line: a number
// is delay points (and endurance boxes for fatigue and wound cards, put
// down to seat by, the enemy whose hit they come from, NoSeat for none); a
// penalty applies as in rule 14.11 (LOSE AIM, WILD SHOT fires every cocked
// gun, DROP turns the character DOWN and draws three more delay cards). One
// delay event is recorded per card drawn. It returns the delay points gained.
func drawCard(p int, c *Character, seg int, reason string, line cardLine, by int, d Drawer, evs *[]Event) (gained int) {
	card := d.Draw()
	res := card.Delay
	if line == woundLine {
		res = card.Wound
	}
	ev := Event{Seg: seg, Player: p, Kind: EvDelay, Reason: reason, Card: card.N, Result: res.String()}
	if res.IsPoints() {
		gained = int(res)
		ev.N = gained
		if line != delayLine {
			ev.Endurance = gained
			lost := gained
			if lost > c.Endurance {
				lost = c.Endurance
			}
			c.Endurance -= lost
			if by >= 0 && by < MaxPlayers {
				c.Hurt[by] += lost
			}
		}
	}
	*evs = append(*evs, ev)
	switch res {
	case LoseAim:
		loseAim(p, c, seg, res.String(), evs)
	case WildShot:
		wildShot(p, c, seg, evs)
		loseAim(p, c, seg, res.String(), evs)
	case Drop:
		gained += drop(p, c, seg, d, evs)
	}
	return gained
}

// drawDelay draws one delay card (14.21).
func drawDelay(p int, c *Character, seg int, reason string, d Drawer, evs *[]Event) int {
	return drawCard(p, c, seg, reason, delayLine, NoSeat, d, evs)
}

// drop is the DROP penalty (14.11): an upright character turns DOWN, draws
// three delay cards and loses its aim; no effect when already DOWN.
func drop(p int, c *Character, seg int, d Drawer, evs *[]Event) (gained int) {
	if c.Down {
		return 0
	}
	c.Down = true
	c.Dropped = true
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvFlip, Down: true})
	for i := 0; i < 3; i++ {
		gained += drawDelay(p, c, seg, ReasonDrop, d, evs)
	}
	loseAim(p, c, seg, ReasonDrop, evs)
	return gained
}

// wildShot fires every cocked gun of c without effect (rule 14.11).
func wildShot(p int, c *Character, seg int, evs *[]Event) {
	for i := range c.Guns {
		if c.Guns[i].Type != NoGun && c.Guns[i].Cocked {
			fireHarmlessly(p, &c.Guns[i], seg, evs)
		}
	}
}

// fireHarmlessly is one gun going off without hitting anything: uncocked,
// one shell less.
func fireHarmlessly(p int, g *Gun, seg int, evs *[]Event) {
	g.Cocked = false
	if g.Shells > 0 {
		g.Shells--
	}
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvWildShot, From: g.Location.String(), Gun: g.Type, GunID: g.ID})
}

// shoot resolves a shot (13): the gun must be cocked, loaded and in a box it
// fires from, else the action is cancelled; the target is hit only inside
// the aim zone, a shot out of it still draws its card and misses (11.32,
// 13.1, 13.2). A MALFUNCTION with no effect is replaced; a
// misfire cancels the shot and a second draw may jam or blow up the gun.
// The shooter then uncocks, spends a shell and loses the aim (13.9). A shot
// at a hex nobody stands in when it comes up, at a target out of sight
// (31), or at a character out of the fight (killed or passed out, 12.6,
// 14.6; surrendered or run away), is held, as a Shoot doing nothing: no card, no shell, the gun stays
// cocked and the aim is kept. It returns the seat shot at (NoSeat when
// nobody was) and the IMPACT TABLE results of a hit, inflicted at the end
// of the segment.
func shoot(board *hex.Board, p int, st *State, a Action, seg int, d Drawer, evs *[]Event) (int, []Penalty) {
	c := &st.Chars[p]
	cancelAt := func(reason, to string) []Penalty {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvCancel, Action: a.Code, Reason: reason, To: to})
		return nil
	}
	cancel := func(reason string) []Penalty { return cancelAt(reason, "") }
	// The target: the character named, or whoever stands in the hex named
	// when the shot comes up; nobody there, the shot is held.
	target := a.Target
	at := a.Hex
	if target < 0 {
		if !board.Has(at) {
			return NoSeat, cancel(ReasonNoHex)
		}
		target = standingIn(st, at, p)
		if target < 0 {
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code, To: at, Reason: ReasonEmptyHex})
			return NoSeat, nil
		}
	}
	t := st.char(target)
	if t != nil {
		at = t.Hex
	}
	// A character named who fell before the shot came up can no longer be
	// shot at (12.6, 14.6): the player would have named another target, or
	// done nothing (11.3), when revealing it; a plan fixed at the start of
	// the turn cannot, so the shot is held.
	if t != nil && target != p && t.Status != Alive {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code, To: at, Target: target, Reason: ReasonOutOfFight})
		return NoSeat, nil
	}
	// The target, a character either way by now, out of sight (31) holds
	// the shot like an empty hex: nothing fires, the aim stays where it is.
	if t != nil && t.Status == Alive && target != p {
		if clear, _ := canSee(board, c, at, t); !clear {
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code, To: at, Target: target, Reason: ReasonNoLOS})
			return target, nil
		}
	}
	slot := c.Guns.Firing()
	if slot < 0 {
		return target, cancel(ReasonNoGun)
	}
	g := &c.Guns[slot]
	switch {
	case g.Exploded:
		return target, cancel(ReasonBroken)
	case g.Jammed:
		return target, cancel(ReasonJammed)
	case g.Shells == 0:
		return target, cancel(ReasonEmpty)
	case !g.Cocked:
		return target, cancel(ReasonNotCocked)
	case t == nil || target == p || t.Status != Alive:
		return target, cancel(ReasonNoTarget)
	}
	spec := g.Type.Spec()
	aim := a.AimTime(spec.OneHanded) + c.Aim
	if g.Location == GunHand || g.Location == BothHands {
		aim -= c.GunArm
	}
	if g.Location == OtherHand || g.Location == BothHands {
		aim -= c.OtherArm
	}
	rng := board.Distance(c.Hex, at)
	// Out of the aim zone the shot automatically misses, but the card is
	// drawn all the same (11.32, 13.1, 13.2).
	inZone := board.InAimZone(c.Hex, c.Facing, at)

	// Draw (13.2): a MALFUNCTION with no effect is replaced; a misfire
	// cancels the shot and draws again for the gun (13.3, 13.31).
	var card ResultCard
	var malfs []Event // logged after the shot
	misfire := false
	for tries := 0; tries < DeckSize; tries++ {
		card = d.Draw()
		if card.IsFire() {
			break
		}
		if !card.Malf.Handloaded { // the Colt 45 takes handloaded shells (26.2)
			malfs = append(malfs, Event{Seg: seg, Player: p, Kind: EvMalfunction, Card: card.N, Result: MalfNoEffect, Gun: g.Type, GunID: g.ID})
			continue
		}
		misfire = true
		malfs = append(malfs, Event{Seg: seg, Player: p, Kind: EvMalfunction, Card: card.N, Result: MalfMisfire, Gun: g.Type, GunID: g.ID})
		second := d.Draw()
		result := MalfNoPenalty
		if !second.IsFire() {
			result = second.Malf.Second
			if result == GunJams {
				g.Shells = 0
				g.Jammed = true
			} else {
				g.Exploded = true
			}
		}
		malfs = append(malfs, Event{Seg: seg, Player: p, Kind: EvMalfunction, Card: second.N, Result: result, Gun: g.Type, GunID: g.ID})
		break
	}
	hit := Miss
	ev := Event{Seg: seg, Player: p, Kind: EvShot, Action: a.Code, Card: card.N, Target: target, To: at, Range: rng, N: aim, Gun: g.Type, GunID: g.ID}
	switch {
	case misfire:
		ev.Reason = ReasonMisfire
	case !inZone:
		ev.Reason = ReasonOutOfZone
	default:
		prelim := card.Fire.Lookup(aim, rng)
		ev.Chart = string(prelim)
		hit, ev.Status = targetStatus(card, prelim, t)
		if hit == Bullseye { // the shooter picks the location (13.7): the deadliest
			hit = VitalHit
		}
	}
	ev.Hit = string(hit)
	// The shot first, then the MALFUNCTION cards it drew.
	*evs = append(*evs, ev)
	*evs = append(*evs, malfs...)

	// After the shot (13.9), even on a misfire.
	g.Cocked = false
	if g.Shells > 0 {
		g.Shells--
	}
	loseAim(p, c, seg, ReasonShot, evs)
	if hit == Miss {
		return target, nil
	}
	return target, Impact(spec.Impact, hit)
}

// throw resolves a THROW (17): the weapon in the proper box (one-handed in
// the gun hand or both hands, 16.2) is thrown at the target named, a
// character or whoever stands in the hex named when it comes up, held like
// a shot when there is nobody to hit (an empty hex, a target out of sight
// or out of the fight: nothing thrown, the aim kept). Bare hands cannot
// throw, and a target farther than the weapon's wielding factor (plus
// STRENGTH, 20.22) cannot be thrown at (17.2): both cancel it. A hit card
// is drawn, MALFUNCTION cards ignored (17.3); aim time and range read the
// hit chart, Target Status applies, a bullseye goes where it hurts most,
// and a target out of the aim zone is missed (17.12). The weapon lands in
// the target's hex on a hit, else in the hex next to it a direction card
// names (17.4): from the target's facing for a character named, towards
// the thrower being ahead for a hex named; "long" carries on the thrower's
// line, "same" and a hex off the map leave it in the target's hex. The
// thrower then loses its aim (16.13). It returns the seat thrown at and
// the STRIKING TABLE results of a hit, with STRENGTH's damage (20.21),
// inflicted at the end of the segment.
func throw(board *hex.Board, p int, st *State, a Action, seg int, d Drawer, evs *[]Event) (int, []Penalty) {
	c := &st.Chars[p]
	cancel := func(reason string) []Penalty {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvCancel, Action: a.Code, Reason: reason})
		return nil
	}
	target := a.Target
	at := a.Hex
	if target < 0 {
		if !board.Has(at) {
			return NoSeat, cancel(ReasonNoHex)
		}
		target = standingIn(st, at, p)
		if target < 0 {
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code, To: at, Reason: ReasonEmptyHex})
			return NoSeat, nil
		}
	}
	t := st.char(target)
	if t == nil || target == p {
		return NoSeat, cancel(ReasonNoTarget)
	}
	at = t.Hex
	if t.Status != Alive {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code, To: at, Target: target, Reason: ReasonOutOfFight})
		return NoSeat, nil
	}
	if clear, _ := canSee(board, c, at, t); !clear {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code, To: at, Target: target, Reason: ReasonNoLOS})
		return target, nil
	}
	slot := c.Guns.Firing()
	if slot < 0 {
		return target, cancel(ReasonNoGun)
	}
	g := c.Guns[slot]
	spec := g.Type.Spec()
	rng := board.Distance(c.Hex, at)
	if rng > spec.Wielding+a.Wield {
		return target, cancel(ReasonOutOfRange)
	}
	aim := a.AimTime(spec.OneHanded) + c.Aim
	if g.Location == GunHand || g.Location == BothHands {
		aim -= c.GunArm
	}
	if g.Location == OtherHand || g.Location == BothHands {
		aim -= c.OtherArm
	}
	inZone := board.InAimZone(c.Hex, c.Facing, at)
	var card ResultCard
	for tries := 0; tries < DeckSize; tries++ {
		if card = d.Draw(); card.IsFire() {
			break
		}
	}
	hit := Miss
	ev := Event{Seg: seg, Player: p, Kind: EvThrow, Action: a.Code, Card: card.N, Target: target, To: at, Range: rng, N: aim, Gun: g.Type, GunID: g.ID}
	if !inZone {
		ev.Reason = ReasonOutOfZone
	} else if card.IsFire() {
		prelim := card.Fire.Lookup(aim, rng)
		ev.Chart = string(prelim)
		hit, ev.Status = targetStatus(card, prelim, t)
		if hit == Bullseye { // the thrower's choice
			hit = StrikingBullseye(spec.Striking)
		}
	}
	ev.Hit = string(hit)
	*evs = append(*evs, ev)
	lands := at
	if hit == Miss {
		dirCard := d.Draw()
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDirection, Card: dirCard.N, To: string(dirCard.Hex)})
		if dir, ok := landing(board, c, t, a.Target >= 0, dirCard.Hex); ok {
			if to, ok := board.Neighbor(at, dir); ok {
				lands = to
			}
		}
	}
	putDown(p, c, slot, lands, ReasonThrow, seg, st, evs)
	loseAim(p, c, seg, ReasonThrow, evs)
	if hit == Miss {
		return target, nil
	}
	return target, Strengthen(Striking(spec.Striking, hit), a.Damage)
}

// landing turns the direction card drawn for a missed throw into the
// direction from the target to the hex where the weapon lands (17.4):
// relative to the facing of a character named, or to the direction
// towards the thrower for a hex named; "long" carries on the thrower's
// line, "same" names no direction.
func landing(board *hex.Board, thrower, t *Character, named bool, h hex.Rel) (hex.Dir, bool) {
	if named || h == hex.Same || h == hex.Long {
		return directionOf(board, t, thrower, h)
	}
	back := (board.LongDir(thrower.Hex, t.Hex, thrower.Facing) + 3) % 6
	return hex.Resolve(back, h), true
}

// targetStatus applies the card's Target Status entries to a preliminary
// hit (13.6): for Move and Run, a bullseye becomes the card's lesser hit
// and any other hit a miss; for Down, any hit but a bullseye misses. Head
// counters are not played. It also returns the letters of the entries
// that changed the hit.
func targetStatus(card ResultCard, hit HitLoc, t *Character) (HitLoc, string) {
	if hit == Miss {
		return Miss, ""
	}
	applied := ""
	lesser := card.Fire.Lesser()
	listed := func(s byte) bool { return strings.IndexByte(card.Status, s) >= 0 }
	for _, s := range []struct {
		letter byte
		on     bool
	}{{StatusMove, t.PlayedFoot || t.Dropped}, {StatusRun, t.PlayedRun}} {
		if !listed(s.letter) || !s.on {
			continue
		}
		applied += string(s.letter)
		if hit != Bullseye {
			return Miss, applied
		}
		hit = lesser
	}
	if listed(StatusDown) && t.Down && hit != Bullseye {
		return Miss, applied + string(StatusDown)
	}
	return hit, applied
}

// applyPenalties inflicts the results of a hit on seat p (14.11, 14.12),
// stopping once the character is out of the fight; the shooter is put down
// as the one who did it (15.2, 15.3). It returns the delay points gained.
func applyPenalties(board *hex.Board, p int, st *State, r pending, seg int, d Drawer, evs *[]Event) (gained int) {
	c := &st.Chars[p]
	// Killed by an earlier shooter's KILL of this same segment (a character
	// already out cannot be shot): this KILL lands simultaneously, they
	// share the kill (15.2).
	if c.Status == Killed && hasKill(r.pens) {
		c.Killers[r.from] = true
	}
	for _, pen := range r.pens {
		if c.Status != Alive {
			break
		}
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvWound, Result: string(pen.Kind), N: pen.N})
		switch pen.Kind {
		case Kill:
			kill(c, seat(r.from))
			dropAllGuns(p, c, seg, st, evs)
		case Stun:
			for i := 0; i < pen.N; i++ {
				gained += drawCard(p, c, seg, ReasonStun, woundLine, r.from, d, evs)
			}
			loseAim(p, c, seg, string(Stun), evs)
		case Stagger:
			gained += stagger(board, p, c, &st.Chars[r.from], seg, d, evs)
		case Serious:
			c.Serious += pen.N
			c.SeriousFrom[r.from] += pen.N
		case DropGunHand:
			dropHand(p, c, GunHand, OtherHand, seg, st, evs)
			loseAim(p, c, seg, string(DropGunHand), evs)
		case DropOtherHand:
			dropHand(p, c, OtherHand, GunHand, seg, st, evs)
			loseAim(p, c, seg, string(DropOtherHand), evs)
		case GunArm:
			c.GunArm += pen.N
		case OtherArm:
			c.OtherArm += pen.N
		case LegWound:
			c.Leg += pen.N
			c.LegFrom[r.from] += pen.N
		case Light:
			for i := 0; i < pen.N; i++ {
				gained += drawCard(p, c, seg, ReasonLight, fatigueLine, r.from, d, evs)
			}
		case LoseAimHit:
			loseAim(p, c, seg, string(LoseAimHit), evs)
		}
	}
	return gained
}

// stagger is the STAGGER penalty (14.11): an upright character is thrown to
// the hex named by a first direction card, turns as named by a second one,
// and drops. A hex off the board keeps it in place.
func stagger(board *hex.Board, p int, c *Character, shooter *Character, seg int, d Drawer, evs *[]Event) (gained int) {
	if c.Down {
		return 0
	}
	first, second := d.Draw(), d.Draw()
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDirection, Card: first.N, To: string(first.Hex)})
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDirection, Card: second.N, To: string(second.Hex)})
	if dir, ok := directionOf(board, c, shooter, first.Hex); ok {
		if to, ok := board.Neighbor(c.Hex, dir); ok {
			from := c.Hex
			c.Hex = to
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvMove, From: from, To: to, Facing: c.Facing, Down: c.Down, Reason: ReasonStagger})
			gained += terrain(board, p, c, from, dir, seg, d, evs)
		}
	}
	if dir, ok := directionOf(board, c, shooter, second.Hex); ok && dir != c.Facing {
		c.Facing = dir
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvTurn, Facing: c.Facing, Reason: ReasonStagger})
	}
	return gained + drop(p, c, seg, d, evs)
}

// terrain is the penalty of the ground crossed by a move or a stagger from
// the hex from in direction dir, to c's hex: two delay cards across a fence
// (35.2), two more onto or off an obstacle (36.4; none from one obstacle
// hex to another).
func terrain(board *hex.Board, p int, c *Character, from string, dir hex.Dir, seg int, d Drawer, evs *[]Event) (gained int) {
	if board.Fenced(from, dir) {
		for i := 0; i < 2; i++ {
			gained += drawDelay(p, c, seg, ReasonFence, d, evs)
		}
	}
	if board.Obstacle(from) != board.Obstacle(c.Hex) {
		for i := 0; i < 2; i++ {
			gained += drawDelay(p, c, seg, ReasonObstacle, d, evs)
		}
	}
	return gained
}

// directionOf turns a direction card's HEX line into an absolute direction
// from the target c (14.3): relative lines are taken from its facing,
// "long" continues the shooter's line, "same" names no direction.
func directionOf(board *hex.Board, c *Character, shooter *Character, h hex.Rel) (hex.Dir, bool) {
	switch h {
	case hex.Same:
		return 0, false
	case hex.Long:
		return board.LongDir(shooter.Hex, c.Hex, shooter.Facing), true
	}
	return hex.Resolve(c.Facing, h), true
}

// dropHand is the GUN HAND / OTHER HAND penalty (14.11): the weapon in that
// hand falls in the hex (a cocked gun going off), and a weapon in both
// hands moves to the other hand.
func dropHand(p int, c *Character, hand, other GunLocation, seg int, st *State, evs *[]Event) {
	if i := c.Guns.At(hand); i >= 0 {
		dropGun(p, c, i, true, "", seg, st, evs)
	}
	if i := c.Guns.At(BothHands); i >= 0 {
		c.Guns[i].Location = other
	}
}

// ActionGunMove names a gun move in its cancel event.
const ActionGunMove cards.Code = "gun_move"

// moveGun does a gun move as its action is revealed (10.22): the gun in
// BOTH HANDS to one hand, as it is, or a gun in a hand box dropped in the
// hex (a cocked one going off harmlessly). Dropping the gun it would fire
// (gun hand or both hands) loses the aim, the points spent aiming it (as a
// GUN HAND wound does, 12.42). A move the gun no longer allows (gone, not
// in a hand, not in both hands) is cancelled.
func moveGun(p int, st *State, m GunMove, seg int, evs *[]Event) {
	c := &st.Chars[p]
	cancel := func(reason string) {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvCancel, Action: ActionGunMove, Reason: reason, GunID: m.Gun})
	}
	i := c.Guns.Find(m.Gun)
	if i < 0 {
		cancel(ReasonNoGun)
		return
	}
	g := &c.Guns[i]
	if m.To == HandGround {
		if g.Location == Holstered {
			cancel(ReasonNotInHand)
			return
		}
		aimed := g.Location == GunHand || g.Location == BothHands
		dropGun(p, c, i, true, ReasonGunMove, seg, st, evs)
		if aimed && c.Aim > 0 {
			loseAim(p, c, seg, ReasonGunDropped, evs)
		}
		return
	}
	if g.Location != BothHands {
		cancel(ReasonNotBoth)
		return
	}
	// A gun in BOTH HANDS leaves no hand to another gun: the hand is free.
	to, _ := HandLocation(m.To)
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvMoveGun, From: g.Location.String(), To: to.String(), Gun: g.Type, GunID: g.ID})
	g.Location = to
}

// dropGun lets the gun in slot i fall in the character's hex, where it lies
// unowned with a fresh ground id; fire makes a cocked gun go off as it
// falls (a released or knocked-out gun, 10.22, 14.11); reason goes on the
// drop event, ReasonGunMove for a gun let go.
func dropGun(p int, c *Character, i int, fire bool, reason string, seg int, st *State, evs *[]Event) {
	if fire && c.Guns[i].Cocked {
		fireHarmlessly(p, &c.Guns[i], seg, evs)
	}
	putDown(p, c, i, c.Hex, reason, seg, st, evs)
}

// putDown takes the gun in slot i off c's sheet and lays it in hex at,
// unowned with a fresh ground id, as it is.
func putDown(p int, c *Character, i int, at, reason string, seg int, st *State, evs *[]Event) {
	g := &c.Guns[i]
	dropped := *g
	dropped.Location = Holstered
	st.GroundSeq++
	st.Ground = append(st.Ground, GroundGun{ID: st.GroundSeq, Hex: at, Gun: dropped})
	*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDropGun, From: g.Location.String(), To: at, Gun: g.Type, GunID: g.ID, N: st.GroundSeq, Reason: reason})
	*g = Gun{}
}

// dropAllGuns is what happens to the weapons of a character killed or
// passed out (14.6): they all fall in the hex as they are, where anyone can
// take them; nothing goes off.
func dropAllGuns(p int, c *Character, seg int, st *State, evs *[]Event) {
	for i := range c.Guns {
		if c.Guns[i].Type != NoGun {
			dropGun(p, c, i, false, "", seg, st, evs)
		}
	}
}

// execute runs one action other than a shot, mutating seat p's character
// (and st for the guns on the ground). It returns the delay points gained
// and whether the action took effect.
func execute(board *hex.Board, p int, a Action, st *State, seg int, d Drawer, evs *[]Event) (gained int, executed bool) {
	c := &st.Chars[p]
	cancelAt := func(reason, to string) (int, bool) {
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvCancel, Action: a.Code, Reason: reason, To: to})
		return gained, false
	}
	cancel := func(reason string) (int, bool) { return cancelAt(reason, "") }
	// move takes the character one hex in dir; off the map it runs away
	// (15.5): it leaves the showdown, guns and all, and the move counts as
	// done.
	move := func(dir hex.Dir) bool {
		to, ok := board.Neighbor(c.Hex, dir)
		if !ok {
			c.Status = RanAway
			clearAim(c)
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvRunAway, Action: a.Code, From: c.Hex, Facing: dir})
			return true
		}
		from := c.Hex
		c.Hex = to
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvMove, Action: a.Code, From: from, To: to, Facing: c.Facing, Down: c.Down})
		if c.Down { // crawl penalty (9.2): a fixed 2 delay, no card
			gained += 2
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDelay, N: 2, Reason: ReasonCrawl})
		} else {
			for i := 0; i < c.Leg; i++ { // LEG wound (14.12), each card put down to the seat whose wound gave it
				gained += drawCard(p, c, seg, ReasonLeg, fatigueLine, pointFrom(c.LegFrom, i), d, evs)
			}
		}
		gained += terrain(board, p, c, from, dir, seg, d, evs)
		return true
	}

	switch a.Code {
	case cards.Advance, cards.Run, cards.BackUp:
		ok := move(hex.Resolve(c.Facing, a.Dir))
		return gained, ok
	case cards.Sprint:
		if !move(c.Facing) || c.Status != Alive { // straight ahead (9.23); gone off the map, nothing more
			return gained, true
		}
		gained += drawDelay(p, c, seg, ReasonSprint, d, evs)
		return gained, true
	case cards.Turn, cards.SpinAround:
		c.Facing = hex.Resolve(c.Facing, a.Dir)
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvTurn, Action: a.Code, Facing: c.Facing})
		return 0, true
	case cards.GetUpDown:
		c.Down = !c.Down
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvFlip, Action: a.Code, Down: c.Down})
		return 0, true
	case cards.LeapDrop:
		c.Down = !c.Down
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvFlip, Action: a.Code, Down: c.Down})
		// Two delay cards (9.4).
		gained += drawDelay(p, c, seg, ReasonLeap, d, evs)
		gained += drawDelay(p, c, seg, ReasonLeap, d, evs)
		return gained, true
	case cards.DrawAndCock:
		dest, ok := HandLocation(a.Hand)
		if !ok {
			return cancel(ReasonNoGun)
		}
		if a.Ground > 0 {
			// Pick a weapon up from the hex into the hand and cock it (11.1,
			// 11.11): it gets a fresh id on this character's sheet.
			gi := -1
			for i, gg := range st.Ground {
				if gg.ID == a.Ground && gg.Hex == c.Hex {
					gi = i
				}
			}
			if gi < 0 {
				return cancel(ReasonNoGun)
			}
			if c.Guns.At(dest) >= 0 {
				return cancel(ReasonHandFull)
			}
			slot := c.Guns.Free()
			if slot < 0 {
				return cancel(ReasonNoRoom)
			}
			g := st.Ground[gi].Gun
			g.ID = c.Guns.NextID()
			g.Location = dest
			g.Cocked = !g.Jammed // a jammed gun cannot be cocked until completely reloaded (13.31)
			c.Guns[slot] = g
			st.Ground = append(st.Ground[:gi:gi], st.Ground[gi+1:]...)
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDraw, Action: a.Code, From: "ground", To: dest.String(), Gun: g.Type, GunID: g.ID, N: a.Ground, Result: jammedResult(g)})
			return 0, true
		}
		// Move the chosen gun from its box (a holster, or a hand) to the
		// one named and cock it (11.1).
		slot := c.Guns.Find(a.Gun)
		if slot < 0 || c.Guns[slot].Location == dest {
			return cancel(ReasonNoGun)
		}
		if c.Guns.Blocked(dest, slot) {
			return cancel(ReasonHandFull)
		}
		g := &c.Guns[slot]
		from := g.Location
		g.Location = dest
		g.Cocked = !g.Jammed // a jammed gun cannot be cocked until completely reloaded (13.31)
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvDraw, Action: a.Code, From: from.String(), To: dest.String(), Gun: g.Type, GunID: g.ID, Result: jammedResult(*g)})
		return 0, true
	case cards.Load:
		// One shell into the gun in BOTH HANDS (11.2, 27.2), which uncocks
		// it; a jammed gun fires again once completely reloaded (13.31).
		slot := c.Guns.At(BothHands)
		if slot < 0 {
			return cancel(ReasonNoGun)
		}
		g := &c.Guns[slot]
		if g.Exploded {
			return cancel(ReasonBroken)
		}
		capacity := g.Type.Spec().Capacity
		if g.Shells >= capacity {
			return cancel(ReasonFull)
		}
		g.Shells++
		g.Cocked = false
		ev := Event{Seg: seg, Player: p, Kind: EvLoad, Action: a.Code, N: g.Shells, Gun: g.Type, GunID: g.ID}
		if g.Jammed && g.Shells == capacity {
			g.Jammed = false
			ev.Result = LoadUnjammed
		}
		*evs = append(*evs, ev)
		return 0, true
	case cards.Throw: // a throw resolves with the shots; this one does nothing (17.1)
		*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code})
		return 0, true
	case cards.CockAimShoot, cards.Shoot:
		if a.Opt == OptNothing {
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvNothing, Action: a.Code})
			return 0, true
		}
		slot := c.Guns.Firing() // a gun in the proper box (11.3)
		if slot < 0 {
			return cancel(ReasonNoGun)
		}
		g := &c.Guns[slot]
		if g.Exploded { // useless for the rest of the game (13.31)
			return cancel(ReasonBroken)
		}
		switch a.Opt {
		case OptCock:
			if g.Jammed { // not before it is completely reloaded (13.31)
				return cancel(ReasonJammed)
			}
			g.Cocked = true
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvCock, Action: a.Code, Gun: g.Type, GunID: g.ID})
		case OptUncock:
			g.Cocked = false
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvUncock, Action: a.Code, Gun: g.Type, GunID: g.ID})
		case OptAim:
			// Two AIM points (12.1, 12.2) on the target named: a character,
			// wherever it is, or a hex; either must be in the aim zone.
			hexAt := a.Hex
			var at *Character
			if a.Target >= 0 {
				at = st.char(a.Target)
				if at == nil || a.Target == p || at.Status != Alive {
					return cancel(ReasonNoTarget)
				}
				hexAt = at.Hex
			} else if !board.Has(a.Hex) {
				return cancel(ReasonNoHex)
			}
			if !board.InAimZone(c.Hex, c.Facing, hexAt) {
				return cancel(ReasonOutOfZone)
			}
			// ...and in sight (31.1): a target behind the trough cannot be aimed at.
			if clear, blocker := canSee(board, c, hexAt, at); !clear {
				return cancelAt(ReasonNoLOS, blocker)
			}
			c.Aim += 2
			if c.Aim > MaxAim {
				c.Aim = MaxAim
			}
			c.AimHex = a.Hex // "" for a character: the markers follow it
			c.AimAt = a.Target
			*evs = append(*evs, Event{Seg: seg, Player: p, Kind: EvAim, Action: a.Code, To: hexAt, Target: a.Target, N: c.Aim})
		}
		return 0, true
	}
	// Not implemented yet (loading, throwing, brawling): Validate rejects these upfront.
	return cancel("unsupported")
}

setup.gno

package engine

import "gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"

// The showdown's SET UP (rules 3.4 and 29.2; [H3]): each character has its
// own hexes to set up in, as a showdown's SET UP assigns them (showdown 1,
// Gunfight, lines its two sides up inside the corral; this one puts up to
// four around its middle). The seats take the characters in order: the creator is
// the first, each player joining the next. Nobody is alerted (29.21): all
// start upright with the Colt holstered, facing any direction.

// CharSetup is where a character of the showdown sets up: the hexes it may
// stand in, and the way it faces unless its player turns it.
type CharSetup struct {
	Char   string
	Hexes  []string
	Facing hex.Dir
}

// Setups is the showdown played, one character per seat in seat order,
// each a side of its own, around the middle of the corral: the Marshal on
// the west side in D5-D7, E6 and E7, the Kid on the east side in H5-H7, G6
// and G7, Reb to the south in E8, F7, F8 and G8, Yankee to the north in
// E5, F5, F4 and G5. They face
// the middle: a flat-top grid has no west or east, so the Marshal looks
// south-east and the Kid north-west; Reb looks north, Yankee south. A
// character with no entry is not in the showdown; a game of n seats uses
// the first n.
var Setups = []CharSetup{
	{Char: "marshal", Hexes: []string{"A-D5", "A-D6", "A-D7", "A-E6", "A-E7"}, Facing: hex.SE},
	{Char: "the_kid", Hexes: []string{"A-H5", "A-H6", "A-H7", "A-G6", "A-G7"}, Facing: hex.NW},
	{Char: "reb", Hexes: []string{"A-E8", "A-F7", "A-F8", "A-G8"}, Facing: hex.N},
	{Char: "yankee", Hexes: []string{"A-E5", "A-F5", "A-F4", "A-G5"}, Facing: hex.S},
}

// SeatChar is the character of a seat, "" for a seat the showdown does not have.
func SeatChar(seat int) string {
	if seat < 0 || seat >= len(Setups) {
		return ""
	}
	return Setups[seat].Char
}

// SetupOf returns the set up of a character, nil when it is not in the showdown.
func SetupOf(charKey string) *CharSetup {
	for i := range Setups {
		if Setups[i].Char == charKey {
			return &Setups[i]
		}
	}
	return nil
}

// ShowdownChars lists the characters of the showdown, seats in order.
func ShowdownChars() []string {
	out := make([]string, len(Setups))
	for i, s := range Setups {
		out[i] = s.Char
	}
	return out
}

// CanSetUp reports whether charKey may set up in hex id: one of its hexes.
func CanSetUp(charKey, id string) bool {
	s := SetupOf(charKey)
	if s == nil {
		return false
	}
	for _, h := range s.Hexes {
		if h == id {
			return true
		}
	}
	return false
}

// SetUp stands seat p's character upright in hex id facing f; the rest of
// its sheet is left as it is.
func (s *State) SetUp(p int, id string, f hex.Dir) {
	s.Chars[p].Hex = id
	s.Chars[p].Facing = f
	s.Chars[p].Down = false
}

sight.gno

package engine

import "gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"

// sightHeight is a character's height for the line of sight (30.32):
// upright, or DOWN unless it lies on an obstacle, where it counts as
// upright.
func sightHeight(board *hex.Board, c *Character) hex.Height {
	if c.Down && !board.Obstacle(c.Hex) {
		return hex.HeightDown
	}
	return hex.HeightUpright
}

// canSee reports whether c has a clear line of sight (rule 31) to its
// target: the character t when t is not nil, wherever it stands and at its
// height, else the hex at, which counts as upright (31.3). blocker names
// the obstacle in the way. The aim zone is checked apart (31.21).
func canSee(board *hex.Board, c *Character, at string, t *Character) (clear bool, blocker string) {
	h := hex.HeightUpright
	if t != nil {
		at, h = t.Hex, sightHeight(board, t)
	}
	return board.LineOfSight(c.Hex, at, sightHeight(board, c), h)
}

state.gno

// Package engine is the pure, deterministic rules engine of a gunfight of
// two to four characters: plan parsing and validation, and the 5-segment
// resolution of a turn. It has no chain dependency so it can be unit-tested
// with gno test.
package engine

import "gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"

const (
	// MaxActionPoints is the time points a plan may spend in a turn (rule 7.3).
	MaxActionPoints = 5
	// Segments is the number of segments in a turn (rule 4.1).
	Segments = 5
	// EndOfTurn is the Seg of events recorded after segment 5 (cancelled
	// actions, passing out, the end-of-showdown check); turn-start events
	// (SERIOUS fatigue, aim lost on the first reveal) have Seg 0.
	EndOfTurn = Segments + 1
	// MinPlayers and MaxPlayers bound the seats of a game: the showdown's
	// characters (Setups) fill the seats in order, each a side of its own.
	MinPlayers = 2
	MaxPlayers = 4
)

// Status is the participation state of a character.
type Status int

const (
	// Alive characters plan and act.
	Alive Status = iota
	// Out characters (surrendered, or out of time) are skipped by Resolve.
	Out
	// Killed characters are out of the game (14.6).
	Killed
	// PassedOut characters carried more delay than endurance for two turns (14.2).
	PassedOut
	// RanAway characters moved off the map (15.5): out of the showdown,
	// their hex the edge hex they left from.
	RanAway
)

// String returns the status name used in JSON views.
func (s Status) String() string {
	switch s {
	case Alive:
		return "alive"
	case Out:
		return "out"
	case Killed:
		return "killed"
	case PassedOut:
		return "passed_out"
	case RanAway:
		return "ran_away"
	}
	return "?"
}

// StartEndurance is the endurance boxes a character starts with (14.2).
const StartEndurance = 20

// MaxAim is the most AIM points a character can hold on a target (12.3).
const MaxAim = 8

// NoSeat is the seat value for "nobody": AIM markers on a hex, a wound or a
// death nobody inflicted.
const NoSeat = -1

// Character is the mutable state of one gunslinger.
type Character struct {
	Hex    string
	Facing hex.Dir
	Down   bool
	Delay  int // delay points on the sheet (rule 6)
	Status Status
	// PlayedFoot and PlayedRun record whether the current turn's plan holds
	// a foot action / a Run, whether or not it executes ([H12], rules 13.61-62).
	PlayedFoot bool
	PlayedRun  bool
	// RanLastTurn is PlayedRun carried over from the previous turn: Sprint
	// needs a Run on the previous turn as well (rule 9.23, "build up speed").
	RanLastTurn bool
	// Dropped records a DROP penalty this turn ("Move" target status, 13.61).
	Dropped bool
	// Guns carried (section 10).
	Guns Guns
	// Aim is the AIM points on the target (12.2). AimAt is the seat of the
	// character the markers follow, wherever it goes (12.3), NoSeat when
	// they sit on the hex AimHex. Both are meaningless while Aim is 0.
	Aim    int
	AimAt  int
	AimHex string
	// Endurance is the boxes left on the sheet (14.2); wound and fatigue
	// cards cross them off.
	Endurance int
	// Exhausted counts the consecutive turn ends with more delay than
	// endurance; two in a row pass the character out (14.2).
	Exhausted int
	// Permanent wounds (14.12): fatigue cards per turn, aim time penalties
	// per hand, fatigue cards per hex moved upright.
	Serious  int
	GunArm   int
	OtherArm int
	Leg      int
	// Who did it, for the victory points (15.2, 15.21, 15.3), by seat: the
	// seats credited with the kill (several when their KILLs landed in the
	// same segment, or tied for the most SERIOUS points), the SERIOUS and
	// LEG points each seat's wounds gave (the fatigue those wounds cost
	// later is put down to it), and the endurance boxes each seat's hits
	// crossed off.
	Killers     [MaxPlayers]bool
	SeriousFrom [MaxPlayers]int
	LegFrom     [MaxPlayers]int
	Hurt        [MaxPlayers]int
}

// GroundGun is a weapon lying in a hex (10.21). ID identifies it on the
// ground for the whole game (plans refer to it as "g<ID>"); the gun's own
// ID was its previous owner's and is reassigned when picked up.
type GroundGun struct {
	ID  int
	Hex string
	Gun Gun
}

// State is the whole game state the engine acts on: one character per
// seat, in seat order.
type State struct {
	Chars     []Character
	Ground    []GroundGun
	GroundSeq int // last ground id handed out
}

// NewState is a showdown of n characters before anyone set up: each
// upright with its starting guns and endurance, standing nowhere yet (Hex
// "") until SetUp gives it its hex and facing ([H3], setup.gno).
func NewState(n int) State {
	chars := make([]Character, n)
	for i := range chars {
		chars[i] = newCharacter()
	}
	return State{Chars: chars}
}

// newCharacter is a character's sheet at the start of a showdown.
func newCharacter() Character {
	return Character{Guns: startingGuns(), Endurance: StartEndurance, AimAt: NoSeat}
}

// char is the character of a seat, nil for a seat the state does not have.
func (s *State) char(seat int) *Character {
	if seat < 0 || seat >= len(s.Chars) {
		return nil
	}
	return &s.Chars[seat]
}

// CloneChars copies the characters field by field. A plain copy of the
// slice is not enough on a node: a character written earlier in the same
// transaction stays shared with the live state, so a turn's stored start
// would show its end position.
func CloneChars(cs []Character) []Character {
	out := make([]Character, len(cs))
	for i, c := range cs {
		out[i] = Character{
			Hex:         c.Hex,
			Facing:      c.Facing,
			Down:        c.Down,
			Delay:       c.Delay,
			Status:      c.Status,
			PlayedFoot:  c.PlayedFoot,
			PlayedRun:   c.PlayedRun,
			RanLastTurn: c.RanLastTurn,
			Dropped:     c.Dropped,
			Aim:         c.Aim,
			AimAt:       c.AimAt,
			AimHex:      c.AimHex,
			Endurance:   c.Endurance,
			Exhausted:   c.Exhausted,
			Serious:     c.Serious,
			GunArm:      c.GunArm,
			OtherArm:    c.OtherArm,
			Leg:         c.Leg,
			Killers:     c.Killers,
			SeriousFrom: c.SeriousFrom,
			LegFrom:     c.LegFrom,
			Hurt:        c.Hurt,
		}
		for j, g := range c.Guns {
			out[i].Guns[j] = Gun{ID: g.ID, Type: g.Type, Location: g.Location, Cocked: g.Cocked, Shells: g.Shells, Jammed: g.Jammed, Exploded: g.Exploded}
		}
	}
	return out
}

// Budget is the time points seat p may plan this turn: the carried delay
// counts against the 5 points ([H5], rule 7.3).
func (s State) Budget(p int) int {
	b := MaxActionPoints - s.Chars[p].Delay
	if b < 0 {
		return 0
	}
	return b
}

// AliveCount counts the characters still in the fight.
func AliveCount(s State) int {
	n := 0
	for _, c := range s.Chars {
		if c.Status == Alive {
			n++
		}
	}
	return n
}

// EndTurn is the end-of-turn upkeep (rule 5.6): half of the delay points
// are removed, rounded up, the per-turn flags are cleared, and a character
// left with more delay than endurance for the second turn in a row passes
// out (14.2; checked after the halving). The state given is left as it is.
func EndTurn(s State) (State, []Event) {
	s.Chars = CloneChars(s.Chars)
	var evs []Event
	for p := range s.Chars {
		c := &s.Chars[p]
		c.Delay -= (c.Delay + 1) / 2
		c.RanLastTurn = c.PlayedRun
		c.PlayedFoot = false
		c.PlayedRun = false
		c.Dropped = false
		if c.Status != Alive {
			continue
		}
		if c.Delay > c.Endurance {
			c.Exhausted++
		} else {
			c.Exhausted = 0
		}
		if c.Exhausted >= 2 {
			c.Status = PassedOut
			c.Down = true
			clearAim(c)
			evs = append(evs, Event{Seg: EndOfTurn, Player: p, Kind: EvPassOut, Down: true})
			dropAllGuns(p, c, EndOfTurn, &s, &evs)
		}
	}
	return s, evs
}

// EndShowdown is the end-of-game check (14.5): every character with SERIOUS
// wounds draws a result card and is killed when its DELAY number plus the
// wound points reaches four; the enemy who gave the most SERIOUS points
// gets the kill, enemies tied for the most share it (15.21). The state
// given is left as it is.
func EndShowdown(s State, d Drawer) (State, []Event) {
	s.Chars = CloneChars(s.Chars)
	var evs []Event
	for p := range s.Chars {
		c := &s.Chars[p]
		if c.Status != Alive || c.Serious == 0 {
			continue
		}
		card := d.Draw()
		n := 0
		if card.Delay.IsPoints() {
			n = int(card.Delay)
		}
		evs = append(evs, Event{Seg: EndOfTurn, Player: p, Kind: EvSeriousCheck, Card: card.N, N: n + c.Serious})
		if n+c.Serious >= 4 {
			kill(c, mostSeats(c.SeriousFrom))
			evs = append(evs, Event{Seg: EndOfTurn, Player: p, Kind: EvWound, Result: string(Kill)})
			dropAllGuns(p, c, EndOfTurn, &s, &evs)
		}
	}
	return s, evs
}

// kill takes a character out of the game (14.6), killed by the seats
// marked in by (none when nobody's hit did it): down, no delay marker, no
// endurance left.
func kill(c *Character, by [MaxPlayers]bool) {
	c.Status = Killed
	c.Down = true
	clearAim(c)
	c.Delay = 0
	c.Endurance = 0
	c.Killers = by
}

// seat marks one seat, none for NoSeat.
func seat(p int) (out [MaxPlayers]bool) {
	if p >= 0 && p < MaxPlayers {
		out[p] = true
	}
	return out
}

// mostSeats marks the seats with the most points, every one of them on a
// tie; none when nobody has any.
func mostSeats(pts [MaxPlayers]int) (out [MaxPlayers]bool) {
	most := 0
	for _, n := range pts {
		if n > most {
			most = n
		}
	}
	if most == 0 {
		return out
	}
	for q, n := range pts {
		out[q] = n == most
	}
	return out
}

// clearAim takes the AIM markers off the sheet.
func clearAim(c *Character) {
	c.Aim = 0
	c.AimAt = NoSeat
	c.AimHex = ""
}

victory.gno

package engine

// Victory point awards (rule 15), for showdowns where each character is a
// side of its own: there are no allies (no "Ally killed"), and no special
// rule captures or kills anyone.
const (
	VPSurvive   = "survive"         // +2: conscious and unsurrendered at the end (15.62)
	VPHoldField = "hold_field"      // +2: the only side with survivors (15.63)
	VPSurrender = "surrender"       // -2 (15.41)
	VPCaptured  = "captured"        // -4: passed out or surrendered when the enemy holds the field (15.63, 15.7)
	VPKilled    = "killed"          // -8 (15.2)
	VPKill      = "kill_enemy"      // +2: the enemy who killed him (15.2)
	VPKnockOut  = "knock_out_enemy" // +1: the enemy who crossed off most of his endurance boxes (15.3, 15.41)
	VPRunAway   = "run_away"        // -2: moved off the map (15.5); no end-of-showdown points (15.6)
)

// VPPoints is what each award is worth (the VICTORY POINTS schedule, 15.11).
// Passing out is worth 0 and makes no award.
var VPPoints = map[string]int{
	VPSurvive:   2,
	VPHoldField: 2,
	VPSurrender: -2,
	VPCaptured:  -4,
	VPKilled:    -8,
	VPKill:      2,
	VPKnockOut:  1,
	VPRunAway:   -2,
}

// VPSharedKill is what each enemy gets when several KILLs land in the same
// segment: 15.2 shares the "Kill enemy" points, kept whole here.
const VPSharedKill = 1

// Award is victory points a character earns (Points > 0) or loses.
type Award struct {
	Player int
	Reason string // one of the VP* names
	Points int
}

// TurnVictoryPoints scores what a turn did, from the characters before and
// after it: a character killed loses the "Killed" points and the enemy
// whose hit killed it gets "Kill enemy" (15.2, Character.Killers), or,
// when several enemies share the kill, 1 point each (kept whole); one
// who passed out gets nothing and the enemy who crossed off most of its
// endurance boxes "Knock out enemy" (15.3, Character.Hurt). A character
// who is not up cannot be hit, so a knocked-out one is never killed
// afterwards.
func TurnVictoryPoints(before, after State) []Award {
	var out []Award
	for p, c := range after.Chars {
		if p >= len(before.Chars) || before.Chars[p].Status != Alive {
			continue
		}
		switch c.Status {
		case Killed:
			out = append(out, award(p, VPKilled))
			var killers []int
			for q, k := range c.Killers {
				if k && q != p && q < len(after.Chars) {
					killers = append(killers, q)
				}
			}
			for _, q := range killers {
				if len(killers) == 1 {
					out = append(out, award(q, VPKill))
				} else {
					out = append(out, Award{Player: q, Reason: VPKill, Points: VPSharedKill})
				}
			}
		case PassedOut:
			if k := knockedOutBy(c); k >= 0 {
				out = append(out, award(k, VPKnockOut))
			}
		case RanAway:
			out = append(out, award(p, VPRunAway))
		}
	}
	return out
}

// knockedOutBy is the enemy who crossed off most of the character's
// endurance boxes (15.3): the first in seat order when two did as much,
// NoSeat when nobody did.
func knockedOutBy(c Character) int {
	best, most := NoSeat, 0
	for q, n := range c.Hurt {
		if n > most {
			best, most = q, n
		}
	}
	return best
}

// EndVictoryPoints scores the end of the showdown (15.6): a character still
// up survives, and holds the field when it is the only one (15.62, 15.63);
// Out stands for a surrendered character, who loses the "Surrender" points
// and, like passing out, gives "Knock out enemy" to the enemy who crossed
// off most of its endurance boxes (15.41); passed out or surrendered, a
// character is captured when an enemy holds the field (15.63, 15.7).
func EndVictoryPoints(s State) []Award {
	var out []Award
	survivors := AliveCount(s)
	for p, c := range s.Chars {
		holds := survivors == 1 && c.Status != Alive // someone else holds the field
		switch c.Status {
		case Alive:
			out = append(out, award(p, VPSurvive))
			if survivors == 1 {
				out = append(out, award(p, VPHoldField))
			}
		case Out:
			out = append(out, award(p, VPSurrender))
			if k := knockedOutBy(c); k >= 0 {
				out = append(out, award(k, VPKnockOut))
			}
			if holds {
				out = append(out, award(p, VPCaptured))
			}
		case PassedOut:
			if holds {
				out = append(out, award(p, VPCaptured))
			}
		}
	}
	return out
}

func award(p int, reason string) Award {
	return Award{Player: p, Reason: reason, Points: VPPoints[reason]}
}

// VPEvents are the awards as end-of-turn events of the turn's log.
func VPEvents(awards []Award) []Event {
	evs := make([]Event, 0, len(awards))
	for _, a := range awards {
		evs = append(evs, Event{Seg: EndOfTurn, Player: a.Player, Kind: EvVP, N: a.Points, Reason: a.Reason})
	}
	return evs
}

// VPTotals adds the awards up per seat, for n seats.
func VPTotals(awards []Award, n int) []int {
	t := make([]int, n)
	for _, a := range awards {
		if a.Player >= 0 && a.Player < n {
			t[a.Player] += a.Points
		}
	}
	return t
}