Playground
events.gno
package gnoslinger
import "chain"
// Events emitted by the realm (type, attribute keys):
//
// GameCreated id creator char seats maxTurns timeoutMinutes hex facing stake
// PlayerJoined id player seat char hex facing
// PlanCommitted id turn player seat
// AllCommitted id turn (every character in the fight committed: the reveals start)
// PlanRevealed id turn seat by (by: who sent the reveal, the player or the opener of its timelocked plan)
// PlanUnopened id turn seat reason (a RevealMany skips a seat whose salt and plan do not match its commit or whose plan is not valid)
// PlanPassed id turn seat (a player with no time points to play is passed automatically)
// PlanMissed id turn seat missed (a claimed timeout passes the turn of a player whose plan is not in, no commit or never revealed; Out at the MaxMissed-th in a row)
// PlayerSurrendered id turn player seat
// TurnResolved id turn rev seed
// VictoryPoints id seat player reason points (one per award at the end of a turn or of the showdown, rule 15; points < 0 for a loss)
// GameEnded id reason winner
// PotPaid id seat player amount (ugnot; one per winner, a draw splitting the pot, stakes.gno)
// StakeRefunded id seat player amount (a showdown cancelled, or ended with everyone out of time, gives the stakes back)
// HouseWithdrawn to amount
// AdminChanged admin
// PlanDue id turn turns to char vs left (a turn started: one per player with a plan to send; char its character, vs the others', left the time the turn gives; notify.gno)
// RevealDue id turn turns to char vs (the reveals started: one per player whose committed plan is not revealed)
// ShowdownOver id to char vs outcome (the game ended: one per player, "you won", "you lost", "a draw"; a cancelled game, to the players who had joined)
//
// They land in transaction results; clients still poll Game.Rev to sync.
// PlanDue, RevealDue and ShowdownOver name their recipient, for the
// browser notifications (notify.gno).
func emit(typ string, attrs ...string) {
chain.Emit(typ, attrs...)
}
gnomod.toml
module = "gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/v0" gno = "0.9" [addpkg] creator = "g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2" height = 758904 max_deposit = "150000000ugnot"
gnoslinger.gno
// Package gnoslinger is the on-chain lobby and referee of Gunslinger
// showdowns (the 1982 Avalon Hill gunfight game) of two to four players.
// Players create and join games and play their turn plans hidden: each
// commits the hash of its plan, then reveals it once every plan is
// committed (DESIGN_HIDDEN_PLANS.md); the realm resolves each turn with the
// pure engine package and keeps the result for the web client to animate.
package gnoslinger
import (
"crypto/sha256"
enchex "encoding/hex"
"strconv"
"time"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/seqid/v0"
profiles "gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/profiles/v0"
)
const (
realmPath = "gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/v0"
// DefaultTimeout is how long a turn may sit without progress before
// anyone can call ClaimTimeout on it, when CreateGame gets 0.
DefaultTimeout = 48 * time.Hour
// MinTimeout and MaxTimeout bound the timeout a creator may pick.
MinTimeout = 5 * time.Minute
MaxTimeout = 30 * 24 * time.Hour
// MinMaxTurns and MaxMaxTurns bound the game length.
MinMaxTurns = 10
MaxMaxTurns = 30
// MaxMissed is the turns in a row a player may let time out: each is
// passed for it, the last puts its character out of the fight.
MaxMissed = 3
// RevealGrace is how long after the commit deadline a claim waits
// before it may pass the turn of a seat whose plan is not revealed: the
// timelocked plans open LockDelay after the deadline, and their opener
// needs time for its transaction.
RevealGrace = 5 * time.Minute
// LockDelay puts the drand round the plans are timelocked to after the
// deadline, past any drift between the block time and drand's clock.
LockDelay = 2 * time.Minute
// MaxLocked bounds the size of a timelocked plan.
MaxLocked = 1024
// MaxSalt bounds the size of a salt (hex).
MaxSalt = 64
// The drand quicknet chain the plans are timelocked to: its genesis
// (unix seconds) and the seconds between two rounds.
DrandGenesis = 1692803367
DrandPeriod = 3
)
// Phase is where a game stands.
type Phase int
const (
// PhaseWaiting: the seats are filling up.
PhaseWaiting Phase = iota
// PhasePlanning: every seat taken; collecting the commits of the
// current turn.
PhasePlanning
// PhaseFinished: over, see Game.EndReason.
PhaseFinished
// PhaseRevealing: every seat in the fight committed; collecting the
// reveals.
PhaseRevealing
)
// String returns the phase name used in JSON views.
func (p Phase) String() string {
switch p {
case PhaseWaiting:
return "waiting"
case PhasePlanning:
return "planning"
case PhaseFinished:
return "finished"
case PhaseRevealing:
return "revealing"
}
return "?"
}
// Player is a seat: the address that controls it (empty while nobody took
// it) and its character token.
type Player struct {
Addr address
Char string
}
// TurnResult is the outcome of one resolved turn, kept so the client can
// replay it: the state the turn started from, the plans (one per seat),
// and what happened. Seed lets anyone re-run the resolution; Cards is the
// trace of the result cards drawn from the deck it shuffles, in order. The
// start snapshot, the weapons on the ground at the start, the cards and the
// events are kept in the engine's compact text encodings: as structs they
// cost a hundred times more storage (see engine/encode.gno). With the
// ground, a turn is shown from its own record, without the turns before it.
type TurnResult struct {
Turn int
Plans []string
Seed string
StartEnc string // engine.EncodeChars
GroundEnc string // engine.EncodeGround
CardsEnc string // engine.EncodeInts
EventsEnc string // engine.EncodeEvents
}
func newTurnResult(turn int, start []engine.Character, ground string, plans []string, seed string, cards []int, evs []engine.Event) *TurnResult {
return &TurnResult{
Turn: turn, Plans: plans, Seed: seed, StartEnc: engine.EncodeChars(start), GroundEnc: ground,
CardsEnc: engine.EncodeInts(cards), EventsEnc: engine.EncodeEvents(evs),
}
}
// Start is the state of every seat when the turn began.
func (r *TurnResult) Start() []engine.Character { return engine.DecodeChars(r.StartEnc) }
// Ground is the weapons lying on the board when the turn began.
func (r *TurnResult) Ground() []engine.GroundGun { return engine.DecodeGround(r.GroundEnc) }
// Cards is the result cards drawn during the turn, in order.
func (r *TurnResult) Cards() []int { return engine.DecodeInts(r.CardsEnc) }
// Events is what happened during the turn, in order.
func (r *TurnResult) Events() []engine.Event { return engine.DecodeEvents(r.EventsEnc) }
// Sealed is a seat's sealed plan for the turn in progress, cleared by its
// reveal.
type Sealed struct {
Hash string // PlanHash of the seat's salt and plan; "" until committed
Locked string // the salt and plan timelocked to LockRound
}
// Game is one showdown. Players, Commits, Plans, Salts, Revealed, Missed and
// VP have one entry per seat, the seats filling up in the order the players
// join.
type Game struct {
ID string
Players []Player
State engine.State
Turn int // 1-based
MaxTurns int
Timeout time.Duration // the time a turn gives, from TurnStart, after which ClaimTimeout succeeds
Phase Phase
Commits []Sealed // the turn in progress, each cleared by its seat's reveal
Plans []string // the turn in progress, revealed, canonical form
Salts []string // the turn in progress, revealed; part of the deck's seed
Revealed []bool // the turn in progress: the seat's plan is in (revealed, or passed)
Missed []int // turns in a row each seat let time out, reset by a revealed plan
TurnStart time.Time // when the turn in progress started: its clock, left alone by the saves within the turn
Turns []*TurnResult // resolved turns, in order (at most MaxTurns)
Winner int // seat index, -1 for none: the most victory points, -1 on a tie
EndReason string
// Awards are the victory points earned and lost so far (rule 15), at
// the end of each turn and of the showdown; VP adds them up per seat.
Awards []engine.Award
VP []int
// Stake is what each player puts in, in ugnot (0: a free showdown);
// Pot what the realm holds for the showdown, the stakes paid so far.
// Payouts is what each seat got once the showdown is over (nil before,
// and for a free one), HouseCut what the house kept (stakes.gno).
Stake int64
Pot int64
Payouts []int64
HouseCut int64
Rev int // bumped on every change; clients poll it
CreatedAt time.Time
UpdatedAt time.Time
}
var (
games = avl.NewTree() // id -> *Game
gameSeq seqid.ID
byPlayer = avl.NewTree() // address -> []string game ids, newest first
openGames = avl.NewTree() // id -> *Game while a seat is free
)
func getGame(id string) *Game {
if _, err := seqid.FromString(id); err != nil {
panic("gnoslinger: invalid game id")
}
v := games.Get(id)
if v == nil {
panic("gnoslinger: game not found")
}
return v.(*Game)
}
// seats is the number of seats of the game, taken or not.
func (g *Game) seats() int { return len(g.Players) }
// seat returns the seat of addr in g, or -1.
func (g *Game) seat(addr address) int {
for i, p := range g.Players {
if p.Addr == addr && p.Addr != "" {
return i
}
}
return -1
}
func (g *Game) mustSeat(addr address) int {
p := g.seat(addr)
if p < 0 {
panic("gnoslinger: you are not a player of this game")
}
return p
}
// freeSeat is the first seat nobody took, -1 once every seat is taken.
func (g *Game) freeSeat() int {
for i, p := range g.Players {
if p.Addr == "" {
return i
}
}
return -1
}
// seated counts the seats taken.
func (g *Game) seated() int {
n := 0
for _, p := range g.Players {
if p.Addr != "" {
n++
}
}
return n
}
// committed reports whether seat p committed its plan this turn (revealed
// or not).
func (g *Game) committed(p int) bool { return g.Commits[p].Hash != "" || g.Revealed[p] }
// allCommitted reports whether every character still in the fight
// committed its plan.
func (g *Game) allCommitted() bool {
for p := range g.Players {
if g.State.Chars[p].Status == engine.Alive && !g.committed(p) {
return false
}
}
return true
}
// allRevealed reports whether the turn has every plan it waits for: one
// from each character still in the fight.
func (g *Game) allRevealed() bool {
for p := range g.Players {
if g.State.Chars[p].Status == engine.Alive && !g.Revealed[p] {
return false
}
}
return true
}
// clearTurn forgets the commits and plans of the turn.
func (g *Game) clearTurn() {
n := g.seats()
g.Commits = make([]Sealed, n)
g.Plans = make([]string, n)
g.Salts = make([]string, n)
g.Revealed = make([]bool, n)
}
// PlanHash is what a seat commits: the sha256, in hex, of its salt and plan
// for that game, turn and seat ("gnoslinger|id|turn|seat|salt|plan").
func PlanHash(id string, turn, seat int, salt, plan string) string {
h := sha256.Sum256([]byte("gnoslinger|" + id + "|" + strconv.Itoa(turn) + "|" + strconv.Itoa(seat) + "|" + salt + "|" + plan))
return enchex.EncodeToString(h[:])
}
// lastTurn is the most recently resolved turn, or nil.
func (g *Game) lastTurn() *TurnResult {
if len(g.Turns) == 0 {
return nil
}
return g.Turns[len(g.Turns)-1]
}
// commitUntil is the turn's deadline: commits are refused from then, and
// the turn can be claimed if commits are missing. Timeout after the turn's
// start whatever happened since (a commit does not restart it); a game
// waiting for players has none.
func (g *Game) commitUntil() time.Time { return g.TurnStart.Add(g.Timeout) }
// revealUntil is when a claim may put the seats that did not reveal out of
// the fight: RevealGrace after the deadline.
func (g *Game) revealUntil() time.Time { return g.commitUntil().Add(RevealGrace) }
// timeoutAt is when the turn in progress becomes claimable through
// ClaimTimeout: the deadline while planning, revealUntil while revealing.
func (g *Game) timeoutAt() time.Time {
if g.Phase == PhaseRevealing {
return g.revealUntil()
}
return g.commitUntil()
}
// LockRound is the drand quicknet round the turn's plans are timelocked
// to: the first round after the deadline plus LockDelay. The realm never
// checks anything about drand: the round only tells every client the same.
func (g *Game) lockRound() int64 {
return (g.commitUntil().Add(LockDelay).Unix()-DrandGenesis)/DrandPeriod + 2
}
// startTurn starts the turn's clock.
func (g *Game) startTurn() { g.TurnStart = time.Now() }
// assertInTime refuses a commit once the turn's deadline passed: from
// then it can only be claimed (ClaimTimeout), so playing late cannot turn
// a lost game around, nor win it by claiming right after.
func (g *Game) assertInTime() {
if !time.Now().Before(g.commitUntil()) {
panic("gnoslinger: out of time: the game can only be claimed now")
}
}
// award records victory points (rule 15): each award is a VictoryPoints
// event, adds to the seat's total and to the player's profile (in the
// profiles realm, which cur, the crossing call's, gets to write).
func (g *Game) award(cur realm, awards []engine.Award) {
for _, a := range awards {
g.Awards = append(g.Awards, a)
g.VP[a.Player] += a.Points
emit("VictoryPoints", "id", g.ID, "seat", strconv.Itoa(a.Player), "player", g.Players[a.Player].Addr.String(),
"reason", a.Reason, "points", strconv.Itoa(a.Points))
profiles.AddVictoryPoints(cross(cur), g.Players[a.Player].Addr, a.Points)
}
}
// finish ends the game: the most victory points win, a tie for the most (a
// game nobody played included) being a draw; the pot is paid out (cur,
// the crossing call's, pays from the realm).
func (g *Game) finish(cur realm, reason string) {
g.Phase = PhaseFinished
g.EndReason = reason
g.Winner = -1
best, tie := 0, false
for p, v := range g.VP {
switch {
case g.Winner < 0 || v > best:
g.Winner, best, tie = p, v, false
case v == best:
tie = true
}
}
if tie {
g.Winner = -1
}
w := ""
if g.Winner >= 0 {
w = g.Players[g.Winner].Addr.String()
}
emit("GameEnded", "id", g.ID, "reason", reason, "winner", w)
g.notifyOver()
g.payPot(cur)
}
// save records a change: bumps the revision and the activity clock.
func save(g *Game) {
g.Rev++
g.UpdatedAt = time.Now()
games.Set(g.ID, g)
}
func index(addr address, id string) {
var ids []string
if v := byPlayer.Get(addr.String()); v != nil {
ids = v.([]string)
}
byPlayer.Set(addr.String(), append([]string{id}, ids...))
}
// unindex removes id from addr's games, and addr from byPlayer once it has
// none left.
func unindex(addr address, id string) {
v := byPlayer.Get(addr.String())
if v == nil {
return
}
var ids []string
for _, x := range v.([]string) {
if x != id {
ids = append(ids, x)
}
}
if len(ids) == 0 {
byPlayer.Remove(addr.String())
return
}
byPlayer.Set(addr.String(), ids)
}
json.gno
package gnoslinger
import (
"strconv"
"strings"
"time"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
profiles "gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/profiles/v0"
)
// JSON views for the web client, read through Render("json/...") so the
// string comes back raw from vm/qrender. Built by hand: the shapes are fixed
// and small, and the chain has no encoding/json.
const listLimit = 50
// liveScan is how many of the newest games GamesJSON looks through for the
// ones being played: what the view costs stays bounded however many games
// there are.
const liveScan = 200
// endedLimit is how many of the last finished games GamesJSON lists.
const endedLimit = 10
// GameJSON is the full view of a game:
//
// {"id","rev","phase","turn","maxTurns","timeout" (seconds),"board",
// "players":[{"addr" ("" for a seat nobody took yet),"name","char","hex" ("" until the seat set up),"facing","down","delay","status","committed","revealed","locked" (its timelocked plan, "" once revealed),"missed" (turns in a row it let time out),"playedFoot","playedRun","ranLastTurn",
// "aim","aimAt" (the seat the AIM markers follow, -1 when they sit on a hex or there is no aim),"aimHex" (the hex they sit on, "" when they follow a seat),"endurance","serious","gunArm","otherArm","leg",
// "guns":[{"id","type","name","location","cocked","shells","capacity","jammed","exploded"}]}] (one entry per seat, 2 to 4),
// "ground":[{"id" (ground id, "g<id>" in a plan),"hex","guns":[{..}]}],
// "winner","vp":[victory points per seat],"awards":[{"p","reason","points"}] (rule 15, once a played game ends),
// "stake" (ugnot each player puts in, 0 for a free showdown),"pot" (the stakes paid so far),"payouts":[ugnot each seat got, [] until paid],"houseCut" (stakes.gno),"endReason",
// "createdAt","updatedAt","timeoutAt" (when the turn in progress can be claimed, 0 unless planning or revealing),
// "commitUntil" (the turn's deadline),"revealUntil" (when unrevealed seats can be claimed out),"lockRound" (the drand round the plans are timelocked to) (0 unless planning or revealing),
// "lastTurn":null|{"turn","seed","cards":[result card numbers drawn, in order],"plans":[..],
// "events":[{"seg","p","kind","action","from","to","facing","down","n","delay","reason","card","result","endurance","target","hit","range","gun","gunId","step","chart","status"}],
// "start":[{"hex","facing","down","delay","status","aim","aimAt","aimHex","endurance","serious","gunArm","otherArm","leg","guns":[..]},..],
// "ground":[the weapons on the ground at the turn's start, as "ground" above]}}
//
// Times are unix seconds; winner, events[].p and events[].target are seat indexes, -1 for none.
// The plans of the turn in progress are hidden until revealed: only their
// commits show, as flags and timelocked plans.
func GameJSON(id string) string {
g := getGame(id)
var b strings.Builder
b.WriteString(`{"id":` + quote(g.ID))
b.WriteString(`,"rev":` + strconv.Itoa(g.Rev))
b.WriteString(`,"phase":` + quote(g.Phase.String()))
b.WriteString(`,"turn":` + strconv.Itoa(g.Turn))
b.WriteString(`,"maxTurns":` + strconv.Itoa(g.MaxTurns))
b.WriteString(`,"timeout":` + strconv.FormatInt(int64(g.Timeout/time.Second), 10))
b.WriteString(`,"board":"A"`)
b.WriteString(`,"players":[`)
for i := range g.Players {
if i > 0 {
b.WriteByte(',')
}
writePlayer(&b, g, i)
}
b.WriteByte(']')
writeGround(&b, g.State.Ground)
b.WriteString(`,"winner":` + strconv.Itoa(g.Winner))
writeVP(&b, g)
b.WriteString(`,"awards":[`)
for i, a := range g.Awards {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(`{"p":` + strconv.Itoa(a.Player) + `,"reason":` + quote(a.Reason) + `,"points":` + strconv.Itoa(a.Points) + `}`)
}
b.WriteByte(']')
writeStakes(&b, g)
b.WriteString(`,"endReason":` + quote(g.EndReason))
b.WriteString(`,"createdAt":` + strconv.FormatInt(g.CreatedAt.Unix(), 10))
b.WriteString(`,"updatedAt":` + strconv.FormatInt(g.UpdatedAt.Unix(), 10))
writeTimeoutAt(&b, g)
commitUntil, revealUntil, lockRound := int64(0), int64(0), int64(0)
if g.Phase == PhasePlanning || g.Phase == PhaseRevealing {
commitUntil, revealUntil, lockRound = g.commitUntil().Unix(), g.revealUntil().Unix(), g.lockRound()
}
b.WriteString(`,"commitUntil":` + strconv.FormatInt(commitUntil, 10))
b.WriteString(`,"revealUntil":` + strconv.FormatInt(revealUntil, 10))
b.WriteString(`,"lockRound":` + strconv.FormatInt(lockRound, 10))
b.WriteString(`,"lastTurn":`)
writeTurnResult(&b, g.lastTurn())
b.WriteByte('}')
return b.String()
}
// PlanJSON is where an address's plan for the turn in progress stands; the
// plan itself shows once revealed:
//
// {"id","turn","seat" (-1 when addr is not a player),"committed","revealed","plan" ("" until revealed)}
func PlanJSON(id, addr string) string {
g := getGame(id)
seat := g.seat(address(addr))
var b strings.Builder
b.WriteString(`{"id":` + quote(g.ID))
b.WriteString(`,"turn":` + strconv.Itoa(g.Turn))
b.WriteString(`,"seat":` + strconv.Itoa(seat))
committed, revealed, plan := false, false, ""
if seat >= 0 {
committed, revealed, plan = g.committed(seat), g.Revealed[seat], g.Plans[seat]
}
b.WriteString(`,"committed":` + strconv.FormatBool(committed))
b.WriteString(`,"revealed":` + strconv.FormatBool(revealed))
b.WriteString(`,"plan":` + quote(plan))
b.WriteByte('}')
return b.String()
}
// TurnJSON is one resolved turn of a game (from 1), the turn result as
// json/game writes its last one: what replays read, a turn per query (the
// "json/history/{id}/{turn}" view), so that what a query costs does not
// grow with the game. Each turn is self-contained (its start and ground).
func TurnJSON(id string, turn int) string {
g := getGame(id)
if turn < 1 || turn > len(g.Turns) {
panic("gnoslinger: turn " + strconv.Itoa(turn) + " is not resolved")
}
var b strings.Builder
writeTurnResult(&b, g.Turns[turn-1])
return b.String()
}
// HistoryJSON is every resolved turn of a game, oldest first, for tests and
// tools (the tutorial's showdown, make gen-tutorial); no view serves it: a
// long game's history may cost more than a query can.
//
// {"id","turn","phase","players":[{"addr","char"}],"turns":[turn result...]}
func HistoryJSON(id string) string {
g := getGame(id)
var b strings.Builder
b.WriteString(`{"id":` + quote(g.ID))
b.WriteString(`,"turn":` + strconv.Itoa(g.Turn))
b.WriteString(`,"phase":` + quote(g.Phase.String()))
b.WriteString(`,"players":[`)
for i, p := range g.Players {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(`{"addr":` + quote(p.Addr.String()) + `,"name":` + quote(profiles.Name(p.Addr)) + `,"char":` + quote(p.Char) + `}`)
}
b.WriteString(`],"turns":[`)
for i, r := range g.Turns {
if i > 0 {
b.WriteByte(',')
}
writeTurnResult(&b, r)
}
b.WriteString("]}")
return b.String()
}
func writePlayer(b *strings.Builder, g *Game, i int) {
p, c := g.Players[i], g.State.Chars[i]
b.WriteString(`{"addr":` + quote(p.Addr.String()))
b.WriteString(`,"name":` + quote(profiles.Name(p.Addr)))
b.WriteString(`,"char":` + quote(p.Char))
b.WriteString(`,"hex":` + quote(c.Hex))
b.WriteString(`,"facing":` + strconv.Itoa(int(c.Facing)))
b.WriteString(`,"down":` + strconv.FormatBool(c.Down))
b.WriteString(`,"delay":` + strconv.Itoa(c.Delay))
b.WriteString(`,"status":` + quote(c.Status.String()))
b.WriteString(`,"committed":` + strconv.FormatBool(g.committed(i)))
b.WriteString(`,"revealed":` + strconv.FormatBool(g.Revealed[i]))
b.WriteString(`,"locked":` + quote(g.Commits[i].Locked))
b.WriteString(`,"missed":` + strconv.Itoa(g.Missed[i]))
b.WriteString(`,"playedFoot":` + strconv.FormatBool(c.PlayedFoot))
b.WriteString(`,"playedRun":` + strconv.FormatBool(c.PlayedRun))
b.WriteString(`,"ranLastTurn":` + strconv.FormatBool(c.RanLastTurn))
writeWounds(b, c)
writeGuns(b, c.Guns)
b.WriteByte('}')
}
// writeWounds writes the aim and wound members of a character.
func writeWounds(b *strings.Builder, c engine.Character) {
b.WriteString(`,"aim":` + strconv.Itoa(c.Aim))
aimAt := engine.NoSeat
if c.Aim > 0 {
aimAt = c.AimAt
}
b.WriteString(`,"aimAt":` + strconv.Itoa(aimAt))
b.WriteString(`,"aimHex":` + quote(c.AimHex))
b.WriteString(`,"endurance":` + strconv.Itoa(c.Endurance))
b.WriteString(`,"serious":` + strconv.Itoa(c.Serious))
b.WriteString(`,"gunArm":` + strconv.Itoa(c.GunArm))
b.WriteString(`,"otherArm":` + strconv.Itoa(c.OtherArm))
b.WriteString(`,"leg":` + strconv.Itoa(c.Leg))
}
// writeTimeoutAt writes the ,"timeoutAt" member: when the turn in progress
// can be claimed, 0 unless the game is planning or revealing.
func writeTimeoutAt(b *strings.Builder, g *Game) {
timeoutAt := int64(0)
if g.Phase == PhasePlanning || g.Phase == PhaseRevealing {
timeoutAt = g.timeoutAt().Unix()
}
b.WriteString(`,"timeoutAt":` + strconv.FormatInt(timeoutAt, 10))
}
// writeGround writes the ,"ground":[...] member: the weapons lying in hexes.
func writeGround(b *strings.Builder, ground []engine.GroundGun) {
b.WriteString(`,"ground":[`)
for i, gg := range ground {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(`{"id":` + strconv.Itoa(gg.ID))
b.WriteString(`,"hex":` + quote(gg.Hex))
writeGuns(b, engine.Guns{gg.Gun})
b.WriteByte('}')
}
b.WriteByte(']')
}
// writeGuns writes the ,"guns":[...] member of a character.
func writeGuns(b *strings.Builder, guns engine.Guns) {
b.WriteString(`,"guns":[`)
n := 0
for _, g := range guns {
if g.Type == engine.NoGun {
continue
}
if n > 0 {
b.WriteByte(',')
}
n++
spec := g.Type.Spec()
b.WriteString(`{"id":` + strconv.Itoa(g.ID))
b.WriteString(`,"type":` + quote(string(g.Type)))
b.WriteString(`,"name":` + quote(spec.Name))
b.WriteString(`,"location":` + quote(g.Location.String()))
b.WriteString(`,"cocked":` + strconv.FormatBool(g.Cocked))
b.WriteString(`,"shells":` + strconv.Itoa(g.Shells))
b.WriteString(`,"capacity":` + strconv.Itoa(spec.Capacity))
b.WriteString(`,"jammed":` + strconv.FormatBool(g.Jammed))
b.WriteString(`,"exploded":` + strconv.FormatBool(g.Exploded))
b.WriteByte('}')
}
b.WriteByte(']')
}
func writeTurnResult(b *strings.Builder, r *TurnResult) {
if r == nil {
b.WriteString("null")
return
}
b.WriteString(`{"turn":` + strconv.Itoa(r.Turn))
b.WriteString(`,"seed":` + quote(r.Seed))
b.WriteString(`,"cards":[`)
for i, n := range r.Cards() {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(strconv.Itoa(n))
}
b.WriteString(`],"plans":[`)
for i, p := range r.Plans {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(quote(p))
}
b.WriteString(`],"events":[`)
for i, e := range r.Events() {
if i > 0 {
b.WriteByte(',')
}
writeEvent(b, e)
}
b.WriteString(`],"start":[`)
for i, c := range r.Start() {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(`{"hex":` + quote(c.Hex))
b.WriteString(`,"facing":` + strconv.Itoa(int(c.Facing)))
b.WriteString(`,"down":` + strconv.FormatBool(c.Down))
b.WriteString(`,"delay":` + strconv.Itoa(c.Delay))
b.WriteString(`,"status":` + quote(c.Status.String()))
writeWounds(b, c)
writeGuns(b, c.Guns)
b.WriteByte('}')
}
b.WriteByte(']')
writeGround(b, r.Ground())
b.WriteByte('}')
}
func writeEvent(b *strings.Builder, e engine.Event) {
b.WriteString(`{"seg":` + strconv.Itoa(e.Seg))
b.WriteString(`,"p":` + strconv.Itoa(e.Player))
b.WriteString(`,"kind":` + quote(e.Kind))
b.WriteString(`,"action":` + quote(string(e.Action)))
b.WriteString(`,"from":` + quote(e.From))
b.WriteString(`,"to":` + quote(e.To))
b.WriteString(`,"facing":` + strconv.Itoa(int(e.Facing)))
b.WriteString(`,"down":` + strconv.FormatBool(e.Down))
b.WriteString(`,"n":` + strconv.Itoa(e.N))
b.WriteString(`,"delay":` + strconv.Itoa(e.Delay))
b.WriteString(`,"reason":` + quote(e.Reason))
b.WriteString(`,"card":` + strconv.Itoa(e.Card))
b.WriteString(`,"result":` + quote(e.Result))
b.WriteString(`,"endurance":` + strconv.Itoa(e.Endurance))
b.WriteString(`,"target":` + strconv.Itoa(e.Target))
b.WriteString(`,"hit":` + quote(e.Hit))
b.WriteString(`,"range":` + strconv.Itoa(e.Range))
b.WriteString(`,"gun":` + quote(string(e.Gun)))
b.WriteString(`,"gunId":` + strconv.Itoa(e.GunID))
b.WriteString(`,"step":` + strconv.Itoa(e.Step))
b.WriteString(`,"chart":` + quote(e.Chart))
b.WriteString(`,"status":` + quote(e.Status))
b.WriteByte('}')
}
// GamesJSON lists, for an address, the games with a free seat, the games
// being played (live: planning or revealing, for anyone to watch), the
// last endedLimit games finished (ended, for anyone to replay) and the
// games it plays or played, newest first (at most 50 each), with the
// address's registered name ("" if none). live and ended are found among
// the liveScan newest games, a running game being recent: a turn times
// out within days.
//
// {"name","open":[summary...],"live":[summary...],"ended":[summary...],"mine":[summary...]}
// summary = {"id","rev","phase","turn","maxTurns","timeout","winner","endReason","vp","stake","pot","payouts","houseCut","createdAt","updatedAt","timeoutAt","lockRound","players":[{"addr","name","char","status","committed","revealed"}]}
//
// lockRound (0 unless planning or revealing) tells the lobby when the
// timelocked plans of a seat committed and not revealed can be opened.
//
// players has one entry per seat, "addr" "" for a seat nobody took yet.
func GamesJSON(addr string) string {
var b strings.Builder
b.WriteString(`{"name":` + quote(profiles.Name(address(addr))))
b.WriteString(`,"open":[`)
n := 0
openGames.ReverseIterate("", "", func(_ string, v any) bool {
if n > 0 {
b.WriteByte(',')
}
writeSummary(&b, v.(*Game))
n++
return n >= listLimit
})
var live, ended strings.Builder
nLive, nEnded, scanned := 0, 0, 0
games.ReverseIterate("", "", func(_ string, v any) bool {
scanned++
g := v.(*Game)
switch {
case (g.Phase == PhasePlanning || g.Phase == PhaseRevealing) && nLive < listLimit:
if nLive > 0 {
live.WriteByte(',')
}
writeSummary(&live, g)
nLive++
case g.Phase == PhaseFinished && nEnded < endedLimit:
if nEnded > 0 {
ended.WriteByte(',')
}
writeSummary(&ended, g)
nEnded++
}
return (nLive >= listLimit && nEnded >= endedLimit) || scanned >= liveScan
})
b.WriteString(`],"live":[` + live.String() + `],"ended":[` + ended.String() + `],"mine":[`)
if v := byPlayer.Get(addr); v != nil {
for i, id := range v.([]string) {
if i >= listLimit {
break
}
if i > 0 {
b.WriteByte(',')
}
writeSummary(&b, games.Get(id).(*Game))
}
}
b.WriteString("]}")
return b.String()
}
func writeSummary(b *strings.Builder, g *Game) {
b.WriteString(`{"id":` + quote(g.ID))
b.WriteString(`,"rev":` + strconv.Itoa(g.Rev))
b.WriteString(`,"phase":` + quote(g.Phase.String()))
b.WriteString(`,"turn":` + strconv.Itoa(g.Turn))
b.WriteString(`,"maxTurns":` + strconv.Itoa(g.MaxTurns))
b.WriteString(`,"timeout":` + strconv.FormatInt(int64(g.Timeout/time.Second), 10))
b.WriteString(`,"winner":` + strconv.Itoa(g.Winner))
writeVP(b, g)
writeStakes(b, g)
b.WriteString(`,"endReason":` + quote(g.EndReason))
b.WriteString(`,"createdAt":` + strconv.FormatInt(g.CreatedAt.Unix(), 10))
b.WriteString(`,"updatedAt":` + strconv.FormatInt(g.UpdatedAt.Unix(), 10))
writeTimeoutAt(b, g)
lockRound := int64(0)
if g.Phase == PhasePlanning || g.Phase == PhaseRevealing {
lockRound = g.lockRound()
}
b.WriteString(`,"lockRound":` + strconv.FormatInt(lockRound, 10))
b.WriteString(`,"players":[`)
for i, p := range g.Players {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(`{"addr":` + quote(p.Addr.String()) + `,"name":` + quote(profiles.Name(p.Addr)) + `,"char":` + quote(p.Char) +
`,"status":` + quote(g.State.Chars[i].Status.String()) + `,"committed":` + strconv.FormatBool(g.committed(i)) + `,"revealed":` + strconv.FormatBool(g.Revealed[i]) + `}`)
}
b.WriteString("]}")
}
// writeVP writes the victory points of each seat.
func writeVP(b *strings.Builder, g *Game) {
b.WriteString(`,"vp":[`)
for i, v := range g.VP {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(strconv.Itoa(v))
}
b.WriteByte(']')
}
// writeStakes writes the stake, the pot and, once paid, what each seat got.
func writeStakes(b *strings.Builder, g *Game) {
b.WriteString(`,"stake":` + strconv.FormatInt(g.Stake, 10))
b.WriteString(`,"pot":` + strconv.FormatInt(g.Pot, 10))
b.WriteString(`,"payouts":[`)
for i, v := range g.Payouts {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(strconv.FormatInt(v, 10))
}
b.WriteString(`],"houseCut":` + strconv.FormatInt(g.HouseCut, 10))
}
// quote encodes s as a JSON string.
func quote(s string) string {
var b strings.Builder
b.WriteByte('"')
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '"' || c == '\\':
b.WriteByte('\\')
b.WriteByte(c)
case c == '\n':
b.WriteString(`\n`)
case c == '\r':
b.WriteString(`\r`)
case c == '\t':
b.WriteString(`\t`)
case c < 0x20:
b.WriteString(`\u00`)
b.WriteByte("0123456789abcdef"[c>>4])
b.WriteByte("0123456789abcdef"[c&0xf])
default:
b.WriteByte(c)
}
}
b.WriteByte('"')
return b.String()
}
// GameRev is the cheapest way to poll a game for changes.
func GameRev(id string) int { return getGame(id).Rev }
lobby.gno
package gnoslinger
import (
"strconv"
"strings"
"time"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
profiles "gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/profiles/v0"
)
// CreateGame opens a showdown of seats players (engine.MinPlayers to
// engine.MaxPlayers) with the caller in seat 0, playing the showdown's
// first character (engine.Setups: the marshal), standing in startHex, one
// of the hexes assigned to that character, facing f (0=N 1=NE 2=SE 3=S
// 4=SW 5=NW); it returns the game id. The other seats take the next
// characters in the order the players join. maxTurns is the game length,
// from MinMaxTurns to MaxMaxTurns; timeoutMinutes is the time each turn
// gives the players, past which anyone may claim it with ClaimTimeout, 0
// meaning DefaultTimeout (2 days). The game stays open until its seats fill
// up or its creator cancels it: the turn clock starts with the last join.
// The ugnot sent with the call are the showdown's stake, which every
// joiner must send too; none, a free showdown (stakes.gno).
func CreateGame(cur realm, seats int, maxTurns int, timeoutMinutes int, startHex string, facing int) string {
caller := cur.Previous().Address()
stake := sentStake(cur)
if seats < engine.MinPlayers || seats > engine.MaxPlayers {
panic("gnoslinger: seats must be between " + strconv.Itoa(engine.MinPlayers) + " and " + strconv.Itoa(engine.MaxPlayers))
}
if maxTurns < MinMaxTurns || maxTurns > MaxMaxTurns {
panic("gnoslinger: maxTurns must be between " + strconv.Itoa(MinMaxTurns) + " and " + strconv.Itoa(MaxMaxTurns))
}
timeout := DefaultTimeout
if timeoutMinutes != 0 {
timeout = time.Duration(timeoutMinutes) * time.Minute
}
if timeout < MinTimeout || timeout > MaxTimeout {
panic("gnoslinger: timeoutMinutes must be between " + strconv.Itoa(int(MinTimeout/time.Minute)) + " and " + strconv.Itoa(int(MaxTimeout/time.Minute)))
}
charKey := engine.SeatChar(0)
assertSetUp(charKey, startHex, facing)
id := gameSeq.Next().String()
g := &Game{
ID: id,
Players: make([]Player, seats),
State: engine.NewState(seats),
Turn: 1,
MaxTurns: maxTurns,
Timeout: timeout,
Phase: PhaseWaiting,
Missed: make([]int, seats),
Winner: -1,
VP: make([]int, seats),
Stake: stake,
Pot: stake,
CreatedAt: time.Now(),
}
g.clearTurn()
g.Players[0] = Player{Addr: caller, Char: charKey}
g.State.SetUp(0, startHex, hex.Dir(facing))
openGames.Set(id, g)
index(caller, id)
profiles.Ensure(cross(cur), caller)
save(g)
emit("GameCreated", "id", id, "creator", caller.String(), "char", charKey, "seats", strconv.Itoa(seats),
"maxTurns", strconv.Itoa(maxTurns), "timeoutMinutes", strconv.Itoa(int(timeout/time.Minute)), "hex", startHex, "facing", strconv.Itoa(facing),
"stake", strconv.FormatInt(stake, 10))
return id
}
// JoinGame seats the caller in the first free seat of a waiting game,
// playing that seat's character (the kid, then the reb, then the yankee),
// standing in startHex, one of that character's hexes, facing f; the game
// starts collecting the commits of turn 1 once its last seat is taken.
// The call must send the showdown's stake, no more, no less.
func JoinGame(cur realm, id string, startHex string, facing int) {
caller := cur.Previous().Address()
stake := sentStake(cur)
g := getGame(id)
if g.Phase != PhaseWaiting {
panic("gnoslinger: game is not open")
}
switch g.seat(caller) {
case 0:
panic("gnoslinger: you cannot join your own game")
case -1:
default:
panic("gnoslinger: you are already in this game")
}
seat := g.freeSeat()
if seat < 0 {
panic("gnoslinger: every seat is taken")
}
charKey := engine.SeatChar(seat)
assertSetUp(charKey, startHex, facing)
if stake != g.Stake {
panic("gnoslinger: this showdown's stake is " + strconv.FormatInt(g.Stake, 10) + Denom + ", sent " + strconv.FormatInt(stake, 10) + Denom)
}
g.Pot += stake
g.Players[seat] = Player{Addr: caller, Char: charKey}
g.State.SetUp(seat, startHex, hex.Dir(facing))
index(caller, id)
if g.freeSeat() < 0 {
// The game starts: it counts as played for every seat.
g.Phase = PhasePlanning
g.startTurn()
g.notifyPlanDue()
openGames.Remove(id)
for _, p := range g.Players {
profiles.AddGamePlayed(cross(cur), p.Addr)
}
} else {
profiles.Ensure(cross(cur), caller)
}
save(g)
emit("PlayerJoined", "id", id, "player", caller.String(), "seat", strconv.Itoa(seat), "char", charKey, "hex", startHex, "facing", strconv.Itoa(facing))
}
// assertSetUp refuses a character that is not in the showdown, a hex it
// may not set up in, or no such facing.
func assertSetUp(charKey, startHex string, facing int) {
setup := engine.SetupOf(charKey)
if setup == nil {
panic("gnoslinger: " + charKey + " is not in this showdown: play " + strings.Join(engine.ShowdownChars(), " or "))
}
if !engine.CanSetUp(charKey, startHex) {
panic("gnoslinger: " + charKey + " sets up in " + strings.Join(setup.Hexes, ", ") + ", not in " + startHex)
}
if !hex.Dir(facing).Valid() {
panic("gnoslinger: facing must be between 0 (N) and 5 (NW)")
}
}
// CancelGame withdraws a game whose seats are not all taken yet. Creator
// only. The game is deleted, not kept as finished, so the creator gets back
// the storage deposit CreateGame paid; the players who had joined are
// unindexed with it, and every stake paid goes back.
func CancelGame(cur realm, id string) {
assertNoSend()
caller := cur.Previous().Address()
g := getGame(id)
if g.Phase != PhaseWaiting {
panic("gnoslinger: only a game waiting for players can be cancelled")
}
if g.Players[0].Addr != caller {
panic("gnoslinger: only the creator can cancel the game")
}
g.refundStakes(cur)
openGames.Remove(id)
games.Remove(id)
for _, p := range g.Players {
if p.Addr != "" {
unindex(p.Addr, id)
}
}
emit("GameEnded", "id", id, "reason", "cancelled", "winner", "")
g.notifyCancelled(caller)
}
notify.gno
package gnoslinger
import (
"strconv"
"strings"
"time"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
gnotif "gno.land/r/nym-gfanton001/gnotif/v1"
)
// Browser notifications, through gnotif (https://gnotif.xyz). At the
// moments a player may have the game closed, the realm emits one event per
// player concerned, naming it in the "to" attribute (PlanDue, RevealDue,
// ShowdownOver), and declares in the gnotif registry one trigger per
// event, which gives the notification its title, body and link. A gnotif
// server (gnotif.xyz on Onyx; make notif runs one on gnodev) reads the
// chain's events and pushes the notification to every browser opted in
// with that address; the client opts in from the lobby
// (game/notifications.ts). A deadline passing emits nothing, so a timeout
// is never notified.
// notifTriggers are the realm's triggers, by name. Title and body are
// templates, {key} standing for the event's attribute: every event names
// the player's character (char) and the others' (vs), and the game; the
// link opens the game in the client (game/route.ts).
var notifTriggers = []struct {
name string
t gnotif.Trigger
}{
{"move", gnotif.Trigger{Event: "PlanDue", Param: "to", Title: "Gnoslinger · Your move", Body: "{char} vs {vs}, game {id}, turn {turn} of {turns}: {left} to send your plan.", Link: "/#game/{id}"}},
{"reveal", gnotif.Trigger{Event: "RevealDue", Param: "to", Title: "Gnoslinger · Reveal your plan", Body: "{char} vs {vs}, game {id}, turn {turn} of {turns}: every plan is in, yours waits to be revealed.", Link: "/#game/{id}"}},
{"over", gnotif.Trigger{Event: "ShowdownOver", Param: "to", Title: "Gnoslinger · Showdown over", Body: "{char} vs {vs}, game {id}: {outcome}.", Link: "/#game/{id}"}},
}
// notif is the realm's handle on its triggers in the registry, kept so that
// DeclareTriggers can set them again: a changed title, body or link keeps
// the trigger's id, and so the browsers opted in.
var notif *gnotif.Handle
// DeclareTriggers sets the realm's triggers in the gnotif registry. Admin
// only, and the first call has what the registry's Open requires: the
// namespace owner's own key (not a session), in a call sent straight to
// the realm; so the deployer sends it once the realm is deployed (on
// gnodev, the make notif script sends it as test1). The triggers keep
// their ids from one call to the next. Every call makes the registry emit
// each trigger again (TriggerDeclared), which is what a gnotif server
// reads them from: the registry emits nothing for a trigger set as it
// already is, so each is first set with a nudged body, then as it should
// be. That is for gnodev, whose reload puts the earlier call in the
// genesis, where no indexer serves its events: the script calls again
// after each reload and the triggers reach gnotifd anew.
func DeclareTriggers(cur realm) {
assertNoSend()
assertAdmin(cur)
me := cur.Sub(gnotif.Subpath)
if notif == nil {
notif = gnotif.Open(cross(me))
}
for _, nt := range notifTriggers {
nudged := nt.t
nudged.Body += " "
notif.Set(cross(me), nt.name, nudged)
notif.Set(cross(me), nt.name, nt.t)
}
}
// notifyPlanDue tells every player with a plan to send that the turn
// started: its character in the fight, not committed, with time points to
// play (one passed automatically has nothing to send).
func (g *Game) notifyPlanDue() {
if g.Phase != PhasePlanning {
return
}
left := formatTimeout(g.Timeout)
for p, pl := range g.Players {
if g.State.Chars[p].Status == engine.Alive && !g.committed(p) && g.State.Budget(p) > 0 {
emit("PlanDue", "id", g.ID, "turn", strconv.Itoa(g.Turn), "turns", strconv.Itoa(g.MaxTurns), "to", pl.Addr.String(), "char", charName(pl.Char), "vs", g.others(p), "left", left)
}
}
}
// notifyRevealDue tells every player whose committed plan is not revealed
// yet that the reveals started.
func (g *Game) notifyRevealDue() {
for p, pl := range g.Players {
if g.State.Chars[p].Status == engine.Alive && !g.Revealed[p] {
emit("RevealDue", "id", g.ID, "turn", strconv.Itoa(g.Turn), "turns", strconv.Itoa(g.MaxTurns), "to", pl.Addr.String(), "char", charName(pl.Char), "vs", g.others(p))
}
}
}
// notifyOver tells every player how the finished showdown ended for it.
func (g *Game) notifyOver() {
for p, pl := range g.Players {
outcome := "a draw"
switch {
case g.Winner == p:
outcome = "you won"
case g.Winner >= 0:
outcome = "you lost"
}
emit("ShowdownOver", "id", g.ID, "to", pl.Addr.String(), "char", charName(pl.Char), "vs", g.others(p), "outcome", outcome)
}
}
// notifyCancelled tells the players who had joined a showdown that its
// creator cancelled it (the creator knows).
func (g *Game) notifyCancelled(creator address) {
for p, pl := range g.Players {
if pl.Addr != "" && pl.Addr != creator {
emit("ShowdownOver", "id", g.ID, "to", pl.Addr.String(), "char", charName(pl.Char), "vs", g.others(p), "outcome", "cancelled by its creator, every stake given back")
}
}
}
// others names the characters of the other seated players, in seat
// order, comma-separated: "The Kid, Reb".
func (g *Game) others(seat int) string {
var names []string
for p, pl := range g.Players {
if p != seat && pl.Addr != "" {
names = append(names, charName(pl.Char))
}
}
return strings.Join(names, ", ")
}
// charName spells a character key as the client does: "the_kid" is "The
// Kid".
func charName(key string) string {
words := strings.Split(key, "_")
for i, w := range words {
if w != "" {
words[i] = strings.ToUpper(w[:1]) + w[1:]
}
}
return strings.Join(words, " ")
}
// formatTimeout spells the time a turn gives: whole days, else whole hours,
// else minutes.
func formatTimeout(d time.Duration) string {
n, unit := int64(d/time.Minute), "minute"
switch {
case d%(24*time.Hour) == 0:
n, unit = int64(d/(24*time.Hour)), "day"
case d%time.Hour == 0:
n, unit = int64(d/time.Hour), "hour"
}
if n != 1 {
unit += "s"
}
return strconv.FormatInt(n, 10) + " " + unit
}
play.gno
package gnoslinger
import (
"chain/runtime"
enchex "encoding/hex"
"strconv"
"strings"
"time"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/cards/v0"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
)
// Commit seals the caller's plan for the given turn, the one in progress,
// and returns the game revision (a commit meant for another turn, say one
// still on its way when time was called, is refused: its hash, which covers
// the turn, could never be revealed in this one, and it would take the
// seat's commit). hash is PlanHash of a salt and the plan, which a Reveal shows
// once every character still in the fight committed; locked is the salt
// and plan timelocked to the turn's LockRound (at most MaxLocked bytes,
// required: encrypting needs no drand node), which anyone can open and
// reveal from then if the player does not. When this commit is the last one the turn waits for, the game
// moves on to the reveals.
func Commit(cur realm, id string, turn int, hash string, locked string) int {
assertNoSend()
caller := cur.Previous().Address()
g := getGame(id)
if turn != g.Turn {
panic("gnoslinger: turn " + strconv.Itoa(turn) + " is not the turn in progress")
}
if g.Phase != PhasePlanning {
panic("gnoslinger: game is not accepting plans")
}
g.assertInTime()
p := g.mustSeat(caller)
if g.State.Chars[p].Status != engine.Alive {
panic("gnoslinger: your character is out of the fight")
}
if g.committed(p) {
panic("gnoslinger: plan already submitted for this turn")
}
if !isHex(hash, 64, 64) {
panic("gnoslinger: the hash must be 64 hex characters")
}
if locked == "" {
panic("gnoslinger: a commit needs its timelocked plan")
}
if len(locked) > MaxLocked {
panic("gnoslinger: the timelocked plan is over " + strconv.Itoa(MaxLocked) + " bytes")
}
g.Commits[p] = Sealed{Hash: hash, Locked: locked}
emit("PlanCommitted", "id", id, "turn", strconv.Itoa(g.Turn), "player", caller.String(), "seat", strconv.Itoa(p))
progress(cur, g)
save(g)
return g.Rev
}
// Reveal puts a seat's salt and plan for the given turn on chain and
// returns the game revision. Anyone may send it while the game collects the
// reveals: the salt and plan must match the seat's commit (PlanHash). The
// last seat to commit may also reveal straight away, without committing:
// the others' plans are already fixed by their hashes, so its plan in clear
// helps nobody; that is only accepted from the seat itself, before the
// deadline, once every other character still in the fight committed (a
// refused transaction still shows its plan). The plan is a comma-separated
// list of "<card><f|b>[:<choice>]" entries, e.g. "1f:ahead_left,2f:ahead,3f";
// an empty string passes. The reveal that completes the turn resolves it in
// this same transaction and the next turn starts.
func Reveal(cur realm, id string, turn int, seat int, salt string, plan string) int {
assertNoSend()
caller := cur.Previous().Address()
g := getGame(id)
if turn != g.Turn {
panic("gnoslinger: turn " + strconv.Itoa(turn) + " is not the turn in progress")
}
if seat < 0 || seat >= g.seats() {
panic("gnoslinger: there is no seat " + strconv.Itoa(seat) + " in this game")
}
switch g.Phase {
case PhaseRevealing:
if g.Revealed[seat] {
panic("gnoslinger: that plan is already revealed")
}
revealSeat(g, seat, salt, plan, caller)
case PhasePlanning:
// The last commit, in clear.
g.assertInTime()
if g.mustSeat(caller) != seat {
panic("gnoslinger: only its player may reveal a plan before every plan is committed")
}
if g.State.Chars[seat].Status != engine.Alive {
panic("gnoslinger: your character is out of the fight")
}
if g.committed(seat) {
panic("gnoslinger: plan already submitted for this turn")
}
for p := range g.Players {
if p != seat && g.State.Chars[p].Status == engine.Alive && !g.committed(p) {
panic("gnoslinger: only the last plan to commit may be revealed at once")
}
}
storePlan(g, seat, salt, plan, caller)
default:
panic("gnoslinger: game is not accepting plans")
}
progress(cur, g)
save(g)
return g.Rev
}
// RevealMany reveals several seats of the given turn in one transaction,
// as Reveal does each, in the order given: what an opener of the
// timelocked plans sends. seats, salts and plans are lists separated by
// ";", of the same length (a plan string never holds a ";", an empty plan
// is an empty field). A seat already revealed is skipped (its player's own
// reveal landed first), and so is one whose salt and plan do not match its
// commit or whose plan is not valid (event PlanUnopened): the opener
// cannot check that before opening, and one bad timelocked plan must not
// keep the others back; that seat stays unrevealed, for the claim.
func RevealMany(cur realm, id string, turn int, seats string, salts string, plans string) int {
assertNoSend()
caller := cur.Previous().Address()
g := getGame(id)
if turn != g.Turn {
panic("gnoslinger: turn " + strconv.Itoa(turn) + " is not the turn in progress")
}
if g.Phase != PhaseRevealing {
panic("gnoslinger: game is not collecting the reveals")
}
ss, sa, pl := strings.Split(seats, ";"), strings.Split(salts, ";"), strings.Split(plans, ";")
if len(sa) != len(ss) || len(pl) != len(ss) {
panic("gnoslinger: seats, salts and plans must list as many entries")
}
for i, s := range ss {
seat, err := strconv.Atoi(s)
if err != nil || seat < 0 || seat >= g.seats() {
panic("gnoslinger: there is no seat " + s + " in this game")
}
if g.Revealed[seat] {
continue
}
if why := checkReveal(g, seat, sa[i], pl[i]); why != "" {
emit("PlanUnopened", "id", g.ID, "turn", strconv.Itoa(g.Turn), "seat", s, "reason", why)
continue
}
revealSeat(g, seat, sa[i], pl[i], caller)
}
progress(cur, g)
save(g)
return g.Rev
}
// revealSeat checks a committed seat's salt and plan against its hash and
// stores them, clearing the commit.
func revealSeat(g *Game, seat int, salt, plan string, by address) {
if why := checkReveal(g, seat, salt, plan); why != "" {
panic("gnoslinger: " + why)
}
storePlan(g, seat, salt, plan, by)
}
// checkReveal tells why a committed seat's salt and plan cannot be
// revealed, "" if they can.
func checkReveal(g *Game, seat int, salt, plan string) string {
if g.Commits[seat].Hash == "" {
return "seat " + strconv.Itoa(seat) + " has no plan committed"
}
if PlanHash(g.ID, g.Turn, seat, salt, plan) != g.Commits[seat].Hash {
return "the salt and plan do not match seat " + strconv.Itoa(seat) + "'s commit"
}
if _, why := checkPlan(g, seat, salt, plan); why != "" {
return why
}
return ""
}
// checkPlan parses and validates a seat's salt and plan; why is "" when
// they are fine.
func checkPlan(g *Game, seat int, salt, plan string) (pl engine.Plan, why string) {
if !isHex(salt, 1, MaxSalt) {
return nil, "the salt must be 1 to " + strconv.Itoa(MaxSalt) + " hex characters"
}
pl, err := engine.ParsePlan(plan)
if err != nil {
return nil, err.Error()
}
if err := pl.Validate(g.State.Chars[seat]); err != nil {
return nil, err.Error()
}
for _, a := range pl {
if a.Ground > 0 && !groundExists(g.State, a.Ground) {
return nil, "there is no such weapon on the ground"
}
if a.Target >= g.seats() {
return nil, "there is no character @" + strconv.Itoa(a.Target) + " in this game"
}
if a.Target == seat {
return nil, "you cannot " + a.Opt + " at your own character"
}
}
return pl, ""
}
// storePlan validates a seat's plan and records it as revealed, clearing
// its commit (whose storage deposit goes back to the caller).
func storePlan(g *Game, seat int, salt, plan string, by address) {
pl, why := checkPlan(g, seat, salt, plan)
if why != "" {
panic("gnoslinger: " + why)
}
// Target-status flags for this turn, set whether or not the actions
// end up executing ([H12]).
g.State.Chars[seat].PlayedFoot = pl.PlayedFoot()
g.State.Chars[seat].PlayedRun = pl.Has(cards.Run)
g.Plans[seat] = pl.String()
g.Salts[seat] = salt
g.Revealed[seat] = true
g.Missed[seat] = 0
g.Commits[seat] = Sealed{}
emit("PlanRevealed", "id", g.ID, "turn", strconv.Itoa(g.Turn), "seat", strconv.Itoa(seat), "by", by.String())
}
// isHex reports whether s is min to max lowercase hex characters.
func isHex(s string, min, max int) bool {
if len(s) < min || len(s) > max {
return false
}
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}
// progress moves the turn on as far as it can: it passes the players who
// cannot play anything (a carried delay of 5 or more leaves no time
// points, rule 7.3: there is nothing to wait for from them), goes on to
// the reveals once every character in the fight committed, and resolves
// the turn once every plan is in; when nobody is left to wait for in the
// next turn either, that turn resolves at once, and so on.
func progress(cur realm, g *Game) {
for {
if g.Phase == PhasePlanning {
for p := range g.Players {
c := &g.State.Chars[p]
if c.Status != engine.Alive || g.committed(p) || g.State.Budget(p) > 0 {
continue
}
c.PlayedFoot = false
c.PlayedRun = false
g.Plans[p] = ""
g.Revealed[p] = true
emit("PlanPassed", "id", g.ID, "turn", strconv.Itoa(g.Turn), "seat", strconv.Itoa(p))
}
if !g.allCommitted() {
return
}
g.Phase = PhaseRevealing
emit("AllCommitted", "id", g.ID, "turn", strconv.Itoa(g.Turn))
g.notifyRevealDue()
}
if g.Phase != PhaseRevealing || !g.allRevealed() {
return
}
turn := g.Turn
seed := resolveTurn(cur, g)
emit("TurnResolved", "id", g.ID, "turn", strconv.Itoa(turn), "rev", strconv.Itoa(g.Rev+1), "seed", seed)
g.notifyPlanDue()
}
}
// resolveTurn plays the seats' plans with the result deck shuffled from
// this turn's seed, stores the result and advances the game. It returns the
// seed in hex.
func resolveTurn(cur realm, g *Game) string {
n := g.seats()
// The salts make the seed unknown to every player when it commits, the
// block keeps the outcome unknown to the last one to reveal.
parts := append([]string{realmPath, g.ID, strconv.Itoa(g.Turn)}, g.Salts...)
parts = append(parts, g.Plans...)
parts = append(parts, strconv.FormatInt(runtime.ChainHeight(), 10), strconv.FormatInt(time.Now().UnixNano(), 10))
seed := engine.Seed(parts...)
plans := make([]engine.Plan, n)
for i, s := range g.Plans {
pl, err := engine.ParsePlan(s)
if err != nil {
panic("gnoslinger: stored plan is invalid: " + err.Error())
}
plans[i] = pl
}
// From a copy: the live state may share the characters with what the
// engine returns (see engine.CloneChars).
start := engine.CloneChars(g.State.Chars)
ground := engine.EncodeGround(g.State.Ground)
deck := engine.NewDeck(seed)
st, evs := engine.Resolve(hex.A, g.State, plans, deck)
st, endEvs := engine.EndTurn(st)
evs = append(evs, endEvs...)
if g.Turn >= g.MaxTurns && engine.AliveCount(st) > 1 { // the end-of-showdown SERIOUS wound check (14.5)
st, endEvs = engine.EndShowdown(st, deck)
evs = append(evs, endEvs...)
}
// Victory points close the turn: what it did, then, when the showdown
// ends with it, the end of the showdown (rule 15).
over := engine.AliveCount(st) <= 1 || g.Turn >= g.MaxTurns
awards := engine.TurnVictoryPoints(engine.State{Chars: start}, st)
if over {
awards = append(awards, engine.EndVictoryPoints(st)...)
}
evs = append(evs, engine.VPEvents(awards)...)
seedHex := enchex.EncodeToString(seed[:])
g.Turns = append(g.Turns, newTurnResult(g.Turn, start, ground, g.Plans, seedHex, deck.Drawn(), evs))
g.State = st
g.award(cur, awards)
g.clearTurn()
switch {
case engine.AliveCount(g.State) == 0:
g.finish(cur, "all_down")
case engine.AliveCount(g.State) == 1:
g.finish(cur, "last_standing")
case g.Turn >= g.MaxTurns:
g.finish(cur, "max_turns")
default:
g.Turn++
g.Phase = PhasePlanning
g.startTurn()
}
return seedHex
}
// groundExists reports whether a gun with that ground id lies somewhere on
// the board; whether it is in the character's hex is checked when the
// action executes, since the character may walk to it first.
func groundExists(st engine.State, id int) bool {
for _, gg := range st.Ground {
if gg.ID == id {
return true
}
}
return false
}
// Surrender gives up the showdown (rule 15.4: at the start of a turn, that
// is while the plans are committed; once they are revealed, surrendering
// after reading the others' would be the abort the hidden plans remove).
// The character is Out: nobody can shoot it and it plays no more. With one
// character left in the fight the game ends and is scored, the surrendered
// losing the "Surrender" points and, an enemy holding the field, being
// captured; with more, the showdown goes on without it (its commit is
// dropped), and goes on to the reveals if the others' plans are committed.
func Surrender(cur realm, id string) {
assertNoSend()
caller := cur.Previous().Address()
g := getGame(id)
switch g.Phase {
case PhasePlanning:
case PhaseRevealing:
panic("gnoslinger: the plans are being revealed: surrender at the start of a turn")
default:
panic("gnoslinger: game is not in progress")
}
p := g.mustSeat(caller)
if g.State.Chars[p].Status != engine.Alive {
panic("gnoslinger: your character is out of the fight")
}
g.State.Chars[p].Status = engine.Out
emit("PlayerSurrendered", "id", id, "turn", strconv.Itoa(g.Turn), "player", caller.String(), "seat", strconv.Itoa(p))
if engine.AliveCount(g.State) <= 1 {
g.award(cur, engine.EndVictoryPoints(g.State))
g.finish(cur, "surrender")
} else {
g.Commits[p] = Sealed{}
g.Plans[p] = ""
g.Salts[p] = ""
g.Revealed[p] = false
progress(cur, g)
}
save(g)
}
// ClaimTimeout ends the wait of a turn past its deadline. Anyone may call
// it. A game waiting for players has no timeout (its creator may cancel
// it). While the plans are committed, past the deadline: each player who
// did not commit misses the turn: it is passed for them, unless that makes
// MaxMissed in a row, which puts the character out of the fight (out of
// time counts as surrendering); the game then goes on to the reveals, and
// with nobody's plan in, the turn resolves empty. A showdown nobody plays
// any more so ends after MaxMissed claims, everyone out of the fight (its
// stakes given back, stakes.gno). While they are
// revealed, RevealGrace past the deadline (the timelocked plans had time
// to be opened, which is how a vanished player's plan normally comes in):
// every character whose plan is still not in misses the turn the same way.
// The realm cannot tell a copy nobody could open from one nobody tried to
// open, so it does not punish more than a missed turn. With one character
// left the game ends and is scored, with more the turn resolves with the
// plans in and the showdown goes on.
func ClaimTimeout(cur realm, id string) {
assertNoSend()
g := getGame(id)
switch g.Phase {
case PhaseFinished:
panic("gnoslinger: game is finished")
case PhaseWaiting:
panic("gnoslinger: the game is waiting for players: it has no timeout")
}
if time.Now().Before(g.timeoutAt()) {
if g.Phase == PhaseRevealing {
panic("gnoslinger: the plans can still be revealed")
}
panic("gnoslinger: the game has not timed out yet")
}
for p := range g.Players {
late := !g.committed(p) // planning: no commit
if g.Phase == PhaseRevealing {
late = !g.Revealed[p] // revealing: no plan in
}
if g.State.Chars[p].Status == engine.Alive && late {
missTurn(g, p)
}
}
if engine.AliveCount(g.State) <= 1 {
g.award(cur, engine.EndVictoryPoints(g.State))
g.finish(cur, "timeout")
} else {
progress(cur, g)
}
save(g)
}
// missTurn passes the turn for a seat whose plan is not in at the claim
// (its commit, if any, dropped), or puts the character out of the fight
// at its MaxMissed-th miss in a row; only a revealed plan resets the count.
func missTurn(g *Game, p int) {
c := &g.State.Chars[p]
g.Missed[p]++
g.Commits[p] = Sealed{}
emit("PlanMissed", "id", g.ID, "turn", strconv.Itoa(g.Turn), "seat", strconv.Itoa(p), "missed", strconv.Itoa(g.Missed[p]))
if g.Missed[p] >= MaxMissed {
c.Status = engine.Out
return
}
c.PlayedFoot = false
c.PlayedRun = false
g.Plans[p] = ""
g.Revealed[p] = true
}
render.gno
package gnoslinger
import (
"strconv"
"strings"
"time"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/cards/v0"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/hex/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/moul/txlink/v0"
"gno.land/p/nt/markdown/sanitize/v0"
"gno.land/p/nt/mux/v0"
profiles "gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/profiles/v0"
)
const recentLimit = 20
var router = mux.NewRouter()
func init() {
router.HandleFunc("", renderHome)
router.HandleFunc("help", renderHelp)
router.HandleFunc("game/{id}", renderGame)
router.HandleFunc("json/game/{id}", func(res *mux.ResponseWriter, req *mux.Request) {
res.Write(GameJSON(req.GetVar("id")))
})
router.HandleFunc("json/games/{addr}", func(res *mux.ResponseWriter, req *mux.Request) {
res.Write(GamesJSON(req.GetVar("addr")))
})
router.HandleFunc("json/history/{id}/{turn}", func(res *mux.ResponseWriter, req *mux.Request) {
turn, err := strconv.Atoi(req.GetVar("turn"))
if err != nil {
panic("gnoslinger: invalid turn")
}
res.Write(TurnJSON(req.GetVar("id"), turn))
})
router.HandleFunc("json/plan/{id}/{addr}", func(res *mux.ResponseWriter, req *mux.Request) {
res.Write(PlanJSON(req.GetVar("id"), req.GetVar("addr")))
})
}
// Render serves the gnoweb pages ("", "help", "game/{id}") and the raw JSON
// views the web client reads ("json/game/{id}", "json/games/{addr}",
// "json/history/{id}/{turn}", "json/plan/{id}/{addr}"); the players' profiles and
// ranking are the profiles realm's (gno.land/r/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/profiles/v0).
func Render(path string) string {
return router.Render(path)
}
// link is a gnoweb link to a sub-path of this realm.
func link(text, path string) string {
return md.Link(text, strings.TrimPrefix(realmPath, "gno.land")+":"+path)
}
func renderHome(res *mux.ResponseWriter, _ *mux.Request) {
res.Write(md.H1("Gnoslinger"))
res.Write(md.Paragraph("Showdowns of two to four gunfighters on board A, the Corral, each on their own. " +
"Create a game, wait for the seats to fill up, then submit a plan every turn. " +
link("How to play", "help") + "."))
res.Write(md.Paragraph(createLink("Create a game of two as the marshal", 2) + " · " + createLink("of three", 3) + " · " + createLink("of four", 4)))
res.Write(md.H2("Open games"))
n := 0
var b strings.Builder
b.WriteString("| Game | Creator | Seats | Stake | Created | |\n|---|---|---|---|---|---|\n")
openGames.ReverseIterate("", "", func(_ string, v any) bool {
g := v.(*Game)
b.WriteString("| " + link(g.ID, "game/"+g.ID) +
" | " + addr(g.Players[0].Addr) +
" | " + strconv.Itoa(g.seated()) + "/" + strconv.Itoa(g.seats()) +
" | " + stakeLabel(g) +
" | " + when(g.CreatedAt) +
" | " + joinLink(g) + " |\n")
n++
return n >= recentLimit
})
if n == 0 {
res.Write(md.Paragraph("No game is waiting for players."))
} else {
res.Write(b.String() + "\n")
}
res.Write(md.H2("Recent games"))
n = 0
b.Reset()
b.WriteString("| Game | Players | Turn | Phase |\n|---|---|---|---|\n")
games.ReverseIterate("", "", func(_ string, v any) bool {
g := v.(*Game)
b.WriteString("| " + link(g.ID, "game/"+g.ID) +
" | " + seatLabels(g) +
" | " + strconv.Itoa(g.Turn) + "/" + strconv.Itoa(g.MaxTurns) +
" | " + phaseLabel(g) + " |\n")
n++
return n >= recentLimit
})
if n == 0 {
res.Write(md.Paragraph("No game yet."))
} else {
res.Write(b.String() + "\n")
}
if house > 0 {
res.Write(md.Paragraph("The house holds " + gnot(house) + " for events."))
}
}
func renderGame(res *mux.ResponseWriter, req *mux.Request) {
g := getGame(req.GetVar("id"))
res.Write(md.H1("Game " + g.ID))
res.Write(md.Paragraph("Turn " + strconv.Itoa(g.Turn) + " of " + strconv.Itoa(g.MaxTurns) + " · " + phaseLabel(g)))
if g.Stake > 0 {
line := "Stake " + stakeLabel(g) + " · pot " + gnot(g.Pot)
for i, v := range g.Payouts {
if v > 0 {
line += " · " + addr(g.Players[i].Addr) + " got " + gnot(v)
}
}
if g.HouseCut > 0 {
line += " · the house kept " + gnot(g.HouseCut)
}
res.Write(md.Paragraph(line))
}
var b strings.Builder
b.WriteString("| Seat | Player | Character | Hex | Facing | Down | Delay | Status | Plan |\n")
b.WriteString("|---|---|---|---|---|---|---|---|---|\n")
for i, p := range g.Players {
c := g.State.Chars[i]
plan := "-"
if g.Phase == PhasePlanning || g.Phase == PhaseRevealing {
switch {
case g.Revealed[i]:
plan = "revealed"
case g.committed(i):
plan = "committed"
default:
plan = "pending"
}
}
b.WriteString("| " + strconv.Itoa(i) +
" | " + addr(p.Addr) +
" | " + sanitize.InlineText(p.Char) +
" | " + c.Hex +
" | " + c.Facing.String() +
" | " + yesNo(c.Down) +
" | " + strconv.Itoa(c.Delay) +
" | " + c.Status.String() +
" | " + plan + " |\n")
}
res.Write(b.String() + "\n")
for _, r := range g.Turns {
res.Write(md.H3("Turn " + strconv.Itoa(r.Turn)))
plans := make([]string, len(r.Plans))
for i, p := range r.Plans {
plans[i] = md.InlineCode(orPass(p))
}
res.Write(md.Paragraph("Plans: " + strings.Join(plans, " vs ")))
if drawn := r.Cards(); len(drawn) > 0 {
cards := make([]string, len(drawn))
for i, n := range drawn {
cards[i] = strconv.Itoa(n)
}
res.Write(md.Paragraph("Result cards drawn: " + strings.Join(cards, ", ")))
}
evs := r.Events()
items := make([]string, 0, len(evs))
for _, e := range evs {
items = append(items, describeEvent(g, e))
}
if len(items) == 0 {
items = append(items, "Nothing happened.")
}
res.Write(md.BulletList(items) + "\n")
}
switch g.Phase {
case PhaseWaiting:
res.Write(md.Paragraph(joinLink(g) + " · " + md.Link("Cancel", txlink.Call("CancelGame", "id", g.ID))))
case PhasePlanning:
res.Write(md.Paragraph("Plans are hidden: commit " + md.InlineCode("PlanHash(id, turn, seat, salt, plan)") +
", reveal once every plan is committed. " +
md.Link("Commit a plan", txlink.Call("Commit", "id", g.ID, "turn", strconv.Itoa(g.Turn), "hash", "", "locked", "")) +
" · " + md.Link("Surrender", txlink.Call("Surrender", "id", g.ID)) +
" · " + md.Link("Claim timeout", txlink.Call("ClaimTimeout", "id", g.ID)) +
" (after " + when(g.timeoutAt()) + ")"))
case PhaseRevealing:
res.Write(md.Paragraph(md.Link("Reveal a plan", txlink.Call("Reveal", "id", g.ID, "turn", strconv.Itoa(g.Turn), "seat", "", "salt", "", "plan", "")) +
" · " + md.Link("Claim timeout", txlink.Call("ClaimTimeout", "id", g.ID)) +
" (after " + when(g.timeoutAt()) + ")"))
}
res.Write(md.Paragraph(link("Back to the lobby", "")))
}
func renderHelp(res *mux.ResponseWriter, _ *mux.Request) {
res.Write(md.H1("How to play"))
res.Write(md.Paragraph("Two to four gunfighters, each on their own. Each turn has five segments. Every player secretly picks up to five time points " +
"of action cards, in the order they will do them, then the turn resolves: an action executes on the " +
"segment equal to the time points used so far plus its own cost plus the delay points on your sheet. " +
"Delay you gain during a segment counts from the next one; actions left after segment 5 are cancelled. " +
"At the end of the turn half of your delay (rounded up) goes away."))
res.Write(md.H2("Setting up"))
res.Write(md.Paragraph("The creator picks how many play, two to four, and is the marshal; the others take the next characters " +
"in the order they join: the kid, then the reb, then the yankee. Each player picks where to stand when calling or joining a showdown, " +
"among the hexes assigned to its character, inside the corral: " + setupList() + "; each faces any direction (" +
md.InlineCode("0") + " N, " + md.InlineCode("1") + " NE, " + md.InlineCode("2") + " SE, " + md.InlineCode("3") + " S, " +
md.InlineCode("4") + " SW, " + md.InlineCode("5") + " NW; the marshal looks south-east, the kid north-west, the reb north and the yankee south unless told otherwise). " +
"All start upright with a loaded Colt 45 in the holster. Aims and shots name a character by seat (" + md.InlineCode("@1") +
") or a hex. A character killed or passed out is out of the fight; one may surrender while the plans are collected, and the others fight on."))
res.Write(md.H2("Plan string"))
res.Write(md.Paragraph("A plan is a comma-separated list of card sides in play order, each " +
md.InlineCode("<card><f|b>[:<direction>]") + ". Directions are relative to your facing: " +
md.InlineCode("ahead_left") + ", " + md.InlineCode("ahead") + ", " + md.InlineCode("ahead_right") + " for forward moves and turns, " +
md.InlineCode("back_left") + ", " + md.InlineCode("back") + ", " + md.InlineCode("back_right") + " for backward ones. " +
"An empty plan passes."))
res.Write(md.Paragraph("Example: " + md.InlineCode("1f:ahead_left,2f:ahead,3f") + " advances ahead-left, runs ahead, then sprints straight."))
res.Write(md.Paragraph("Rules: one side per card per turn; the total cost must fit in 5 minus your delay; " +
"Run needs Advance in the same plan; Sprint needs Run."))
res.Write(md.Paragraph("Aiming and shooting need the target in your aim zone and in sight (rule 31). " +
"On board A only the horse trough (" + md.InlineCode("A-I11*") + ") gets in the way: it hides two characters " +
"lying DOWN from each other, and a DOWN character next to it from anyone across it; standing characters see " +
"over it. An aim at a target out of sight is cancelled and AIM points on it are lost at the end of the " +
"segment; a shot at it is held, nothing spent, like a shot at a hex nobody stands in when it comes up."))
res.Write(md.H2("Cards"))
var b strings.Builder
b.WriteString("| Card | Front | Back |\n|---|---|---|\n")
for _, c := range cards.Cards {
b.WriteString("| " + strconv.Itoa(c.Number) + " | " + sideLabel(c.Front) + " | " + sideLabel(c.Back) + " |\n")
}
res.Write(b.String() + "\n")
res.Write(md.Paragraph("Only foot actions are available for now; the others come with guns and brawling."))
}
// cancelReason is the reason of a cancel event as the log shows it: the
// reason code, except a target out of sight, spelled out with the obstacle
// in the way.
func cancelReason(e engine.Event) string {
switch e.Reason {
case engine.ReasonNoLOS:
return noSight(e)
case engine.ReasonNotInHand:
return "the gun is not in hand"
case engine.ReasonNotBoth:
return "the gun is not in both hands"
}
return e.Reason
}
// noSight words a no_los reason: the event's To names the obstacle in the way.
func noSight(e engine.Event) string {
if e.To == "" {
return "no line of sight"
}
return "no line of sight, " + e.To + " in the way"
}
func sideLabel(s cards.Side) string {
l := s.Name + " (" + strconv.Itoa(s.Cost) + ")"
if !cards.Enabled(s.Code) {
l += " *"
}
return l
}
func describeEvent(g *Game, e engine.Event) string {
who := sanitize.InlineText(g.Players[e.Player].Char)
seg := "turn start"
switch {
case e.Seg > engine.Segments:
seg = "end of turn"
case e.Seg > 0:
seg = "seg " + strconv.Itoa(e.Seg)
}
action := strings.ReplaceAll(string(e.Action), "_", " ")
var what string
switch e.Kind {
case engine.EvMove:
what = who + " " + action + ": " + e.From + " → " + e.To
if e.Down {
what += " (crawling)"
}
case engine.EvTurn:
what = who + " " + action + ": now facing " + hex.Dir(e.Facing).String()
case engine.EvFlip:
if e.Down {
what = who + " goes down"
} else {
what = who + " gets up"
}
case engine.EvDelay:
what = who + " gains " + strconv.Itoa(e.N) + " delay (" + e.Reason + "), now " + strconv.Itoa(e.Delay)
if e.Card > 0 {
// Every card drawn reads the same: who draws which card and why, then what it does.
drawn := who + " draws card " + strconv.Itoa(e.Card) + " (" + e.Reason + "): "
if e.Result != "" {
what = drawn + strings.ToUpper(strings.ReplaceAll(e.Result, "_", " "))
} else {
gain := "no delay"
if e.N > 0 {
gain = "gains " + strconv.Itoa(e.N) + " delay"
}
what = drawn + gain + ", now " + strconv.Itoa(e.Delay)
if e.Endurance > 0 {
what += ", loses " + strconv.Itoa(e.Endurance) + " endurance"
}
}
}
case engine.EvWildShot:
what = who + "'s " + e.Gun.Spec().Name + " goes off (wild shot)"
case engine.EvCock:
what = who + " cocks the " + e.Gun.Spec().Name
case engine.EvUncock:
what = who + " uncocks the " + e.Gun.Spec().Name
case engine.EvAim:
what = who + " aims at " + e.To
if e.Target >= 0 {
what += " (" + seatLabel(g, e.Target) + ")"
}
what += ": " + strconv.Itoa(e.N) + " AIM points"
case engine.EvLoseAim:
if e.Reason == engine.ReasonNoLOS {
what = who + " loses the aim (" + noSight(e) + ")"
} else if e.Reason == engine.ReasonOwnHex {
what = who + " loses the aim (the markers cannot move into or out of its own hex)"
} else {
what = who + " loses the aim (" + strings.ReplaceAll(e.Reason, "_", " ") + ")"
}
case engine.EvNothing:
hold := " holds fire: "
if e.Action == cards.Throw {
hold = " holds the throw: "
}
switch e.Reason {
case engine.ReasonEmptyHex:
what = who + hold + "nobody in " + e.To
case engine.ReasonNoLOS:
what = who + hold + seatLabel(g, e.Target) + " in " + e.To + " is out of sight"
case engine.ReasonOutOfFight:
what = who + hold + seatLabel(g, e.Target) + " is out of the fight"
default:
what = who + " does nothing (" + action + ")"
}
case engine.EvShot:
at := "at " + e.To
if e.Target >= 0 {
at = seatLabel(g, e.Target) + " in " + e.To
}
what = who + " shoots " + at + " (card " + strconv.Itoa(e.Card) + ", aim time " + strconv.Itoa(e.N) + ", range " + strconv.Itoa(e.Range) + "): "
switch {
case e.Reason == engine.ReasonMisfire:
what += "misfire"
case e.Hit == string(engine.Miss):
what += "miss"
if e.Reason != "" {
what += " (" + strings.ReplaceAll(e.Reason, "_", " ") + ")"
}
default:
what += e.Hit + " hit"
}
case engine.EvThrow:
at := "at " + e.To
if e.Target >= 0 {
at = "at " + seatLabel(g, e.Target) + " in " + e.To
}
what = who + " throws the " + e.Gun.Spec().Name + " " + at + " (card " + strconv.Itoa(e.Card) + ", aim time " + strconv.Itoa(e.N) + ", range " + strconv.Itoa(e.Range) + "): "
if e.Hit == string(engine.Miss) {
what += "miss"
if e.Reason != "" {
what += " (" + strings.ReplaceAll(e.Reason, "_", " ") + ")"
}
} else {
what += e.Hit + " hit"
}
case engine.EvMalfunction:
what = who + " draws card " + strconv.Itoa(e.Card) + ": MALFUNCTION, " + strings.ReplaceAll(e.Result, "_", " ")
case engine.EvWound:
what = who + " suffers " + strings.ToUpper(strings.ReplaceAll(e.Result, "_", " "))
if e.N > 0 {
what += " " + strconv.Itoa(e.N)
}
case engine.EvDirection:
what = who + " draws card " + strconv.Itoa(e.Card) + " as a direction: " + strings.ReplaceAll(e.To, "_", " ")
case engine.EvDropGun:
what = who + " drops the " + e.Gun.Spec().Name + " in " + e.To
if e.Reason == engine.ReasonThrow {
what = who + "'s " + e.Gun.Spec().Name + " lands in " + e.To
}
case engine.EvMoveGun:
what = who + " moves the " + e.Gun.Spec().Name + " from " + strings.ReplaceAll(e.From, "_", " ") + " to the " + strings.ReplaceAll(e.To, "_", " ")
case engine.EvPassOut:
what = who + " passes out"
case engine.EvRunAway:
what = who + " runs away off the map from " + e.From
case engine.EvSeriousCheck:
what = who + " draws card " + strconv.Itoa(e.Card) + " for the SERIOUS wounds: " + strconv.Itoa(e.N) + " points"
case engine.EvVP:
pts := strconv.Itoa(e.N)
if e.N > 0 {
pts = "+" + pts
}
what = who + ": " + pts + " VP, " + strings.ReplaceAll(e.Reason, "_", " ")
case engine.EvDraw:
to := "to the " + strings.ReplaceAll(e.To, "_", " ")
if e.To == engine.BothHands.String() {
to = "into both hands"
}
cocks := " and cocks it"
if e.Result == engine.DrawJammed {
cocks = " (jammed: not cocked)"
}
switch e.From {
case "ground":
what = who + " picks up the " + e.Gun.Spec().Name + " from the ground " + to + cocks
case engine.Holstered.String():
what = who + " draws the " + e.Gun.Spec().Name + " " + to + cocks
default:
what = who + " moves the " + e.Gun.Spec().Name + " " + to + cocks
}
case engine.EvLoad:
what = who + " loads a shell in the " + e.Gun.Spec().Name + " (" + strconv.Itoa(e.N) + " now)"
if e.Result == engine.LoadUnjammed {
what += ": no longer jammed"
}
case engine.EvCancel:
what = who + ": " + action + " is cancelled (" + cancelReason(e) + ")"
default:
what = who + " " + e.Kind
}
return seg + ": " + what
}
func seatLabel(g *Game, i int) string {
if i < 0 || i >= g.seats() || g.Players[i].Addr == "" {
return "?"
}
return sanitize.InlineText(g.Players[i].Char)
}
// seatLabels names every seat, "marshal vs the_kid vs ?".
func seatLabels(g *Game) string {
labels := make([]string, g.seats())
for i := range g.Players {
labels[i] = seatLabel(g, i)
}
return strings.Join(labels, " vs ")
}
// createLink is a transaction link to call a showdown of seats players,
// standing in the middle of the marshal's hexes, facing its way.
func createLink(text string, seats int) string {
setup := engine.Setups[0]
return md.Link(text, txlink.Call("CreateGame", "seats", strconv.Itoa(seats), "maxTurns", "20", "timeoutMinutes", "0",
"startHex", setup.Hexes[len(setup.Hexes)/2], "facing", strconv.Itoa(int(setup.Facing))))
}
// joinLink is a transaction link to take the next free seat of a waiting
// game, standing in the middle of its character's hexes.
func joinLink(g *Game) string {
seat := g.freeSeat()
if seat < 0 {
return ""
}
setup := engine.SetupOf(engine.SeatChar(seat))
tx := txlink.NewLink("JoinGame").AddArgs("id", g.ID, "startHex", setup.Hexes[len(setup.Hexes)/2], "facing", strconv.Itoa(int(setup.Facing)))
if g.Stake > 0 {
tx = tx.SetSend(strconv.FormatInt(g.Stake, 10) + Denom)
}
return md.Link("Join as "+strings.ReplaceAll(setup.Char, "_", " "), tx.URL())
}
// gnot words an amount of ugnot in GNOT: "5 GNOT", "9.5 GNOT".
func gnot(ugnot int64) string {
s := strconv.FormatInt(ugnot/1_000_000, 10)
if frac := ugnot % 1_000_000; frac != 0 {
f := strconv.FormatInt(1_000_000+frac, 10)[1:]
s += "." + strings.TrimRight(f, "0")
}
return s + " GNOT"
}
// stakeLabel words a showdown's stake: "free", or "5 GNOT each".
func stakeLabel(g *Game) string {
if g.Stake == 0 {
return "free"
}
return gnot(g.Stake) + " each"
}
// setupList words where each character sets up: "the marshal in A-G5 to A-G9, ...".
func setupList() string {
parts := make([]string, len(engine.Setups))
for i, s := range engine.Setups {
parts[i] = strings.ReplaceAll(s.Char, "_", " ") + " in " + md.InlineCode(s.Hexes[0]) + " to " + md.InlineCode(s.Hexes[len(s.Hexes)-1])
}
return strings.Join(parts, ", ")
}
func phaseLabel(g *Game) string {
if g.Phase != PhaseFinished {
return g.Phase.String()
}
l := "finished (" + g.EndReason + ")"
if len(g.Awards) > 0 {
vp := make([]string, len(g.VP))
for i, v := range g.VP {
vp[i] = strconv.Itoa(v)
}
l += ", " + strings.Join(vp, " to ") + " VP"
}
if g.Winner >= 0 {
l += ", winner: " + seatLabel(g, g.Winner)
}
return l
}
// addr shows an address by its registered name when it has one.
func addr(a address) string {
if name := profiles.Name(a); name != "" {
return md.Bold(sanitize.InlineText(name))
}
return md.InlineCode(sanitize.InlineText(a.String()))
}
func when(t time.Time) string {
return t.UTC().Format("2006-01-02 15:04") + " UTC"
}
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}
func orPass(plan string) string {
if plan == "" {
return "(pass)"
}
return plan
}
stakes.gno
package gnoslinger
import (
"chain"
"chain/banker"
"chain/runtime/unsafe"
"strconv"
"gno.land/p/g1th0masp67zfs9lg6d34qhghldhg6kjcqjuv7c2/gnoslinger/engine/v0"
)
// Stakes (this project's, not the board game's): a showdown may be played
// for GNOT. The creator sends the stake with CreateGame, and every joiner
// sends the same with JoinGame; the realm holds them, the pot. When the
// showdown ends the house keeps HouseCutPercent of the pot for events, and
// the winner takes the rest; a draw splits it between the seats tied for
// the most victory points (what does not divide evenly goes to the house).
// A showdown that ends with nobody left in the fight, everyone out of time,
// or cancelled before it starts, gives every stake back in full. The admin, the deployer at
// first, may send the house's funds out (WithdrawHouse): a later version of
// the realm cannot reach this one's balance.
const (
// Denom is the only coin a stake is paid in.
Denom = "ugnot"
// HouseCutPercent is the share of a pot the house keeps, for events.
HouseCutPercent = 5
)
var (
// house is what the realm holds for events: the house's cuts, less
// what the admin withdrew. The rest of the realm's balance is the pots
// of the showdowns not over yet.
house int64
// admin may withdraw the house's funds; the deployer at first.
admin = unsafe.OriginCaller()
)
// sentStake returns the ugnot sent with the call, 0 for none. Coins can
// only come straight from a user's call: a realm in between could have
// spent the send it reports (unsafe.OriginSend is the whole message's).
func sentStake(cur realm) int64 {
sent := unsafe.OriginSend()
if len(sent) == 0 {
return 0
}
if !cur.Previous().IsUserCall() {
panic("gnoslinger: a stake can only be sent by a direct call")
}
if len(sent) != 1 || sent[0].Denom != Denom || sent[0].Amount <= 0 {
panic("gnoslinger: a stake is paid in " + Denom + " only")
}
return sent[0].Amount
}
// assertNoSend refuses coins sent with a call that takes none: they would
// sit in the realm's balance with no showdown to pay them out.
func assertNoSend() {
if len(unsafe.OriginSend()) > 0 {
panic("gnoslinger: this call takes no coins")
}
}
// pay sends amount ugnot from the realm to addr.
func pay(cur realm, to address, amount int64) {
if amount <= 0 {
return
}
banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), to, chain.Coins{chain.NewCoin(Denom, amount)})
}
// refundStakes gives every seated player its stake back: the showdown
// was cancelled, or nobody was left to win it. Payouts records it, so a finished game says
// what each seat got.
func (g *Game) refundStakes(cur realm) {
if g.Pot == 0 {
return
}
g.Payouts = make([]int64, g.seats())
for i, p := range g.Players {
if p.Addr == "" {
continue
}
pay(cur, p.Addr, g.Stake)
g.Payouts[i] = g.Stake
emit("StakeRefunded", "id", g.ID, "seat", strconv.Itoa(i), "player", p.Addr.String(), "amount", strconv.FormatInt(g.Stake, 10))
}
}
// payPot pays the pot of a finished showdown: the house's cut, then the
// winner, or the seats tied for the most victory points in equal shares.
func (g *Game) payPot(cur realm) {
if g.Pot == 0 || g.Payouts != nil {
return
}
if g.nobodyWon() {
g.refundStakes(cur)
return
}
best := g.VP[0]
for _, v := range g.VP {
if v > best {
best = v
}
}
var winners []int
for i, v := range g.VP {
if v == best {
winners = append(winners, i)
}
}
cut := g.Pot * HouseCutPercent / 100
share := (g.Pot - cut) / int64(len(winners))
cut = g.Pot - share*int64(len(winners))
g.Payouts = make([]int64, g.seats())
for _, w := range winners {
pay(cur, g.Players[w].Addr, share)
g.Payouts[w] = share
emit("PotPaid", "id", g.ID, "seat", strconv.Itoa(w), "player", g.Players[w].Addr.String(), "amount", strconv.FormatInt(share, 10))
}
g.HouseCut = cut
house += cut
}
// nobodyWon tells a showdown that ended with nobody left in the fight
// because everyone ran out of time: nobody played it to the end, nothing
// was won.
func (g *Game) nobodyWon() bool {
return g.EndReason == "timeout" && engine.AliveCount(g.State) == 0
}
// WithdrawHouse sends amount ugnot of the house's funds to an address.
// Admin only.
func WithdrawHouse(cur realm, to address, amount int64) {
assertNoSend()
assertAdmin(cur)
if !to.IsValid() {
panic("gnoslinger: invalid address")
}
if amount <= 0 || amount > house {
panic("gnoslinger: the house holds " + strconv.FormatInt(house, 10) + Denom)
}
house -= amount
pay(cur, to, amount)
emit("HouseWithdrawn", "to", to.String(), "amount", strconv.FormatInt(amount, 10))
}
// SetAdmin hands the house's funds over to another admin. Admin only.
func SetAdmin(cur realm, addr address) {
assertNoSend()
assertAdmin(cur)
if !addr.IsValid() {
panic("gnoslinger: invalid address")
}
admin = addr
emit("AdminChanged", "admin", addr.String())
}
func assertAdmin(cur realm) {
if prev := cur.Previous(); !prev.IsUser() || prev.Address() != admin {
panic("gnoslinger: admin only")
}
}
// House is the ugnot the house holds for events.
func House() int64 { return house }
// Admin is who may withdraw the house's funds.
func Admin() address { return admin }