Playground
bot.gno
package brawl
// House bots: the opponents you fight in the browser, at three levels. They
// react to the match every tick, so they are fair rivals, and they are
// deterministic, so the chain can replay a match against them exactly.
// Bot levels.
const (
Easy = iota
Normal
Hard
)
type botLevel struct {
think int // ticks between decisions
idle int // per mille chance to stand still for a decision
fight int // per mille chance to go after the rival and use buttons
reach int // how far it looks for gold first, in squares
guard int // per mille chance, each tick, to block a rival in reach who can swing
}
var botLevels = [3]botLevel{
{think: 4, idle: 30, fight: 600, reach: 8, guard: 0},
{think: 3, idle: 80, fight: 900, reach: 8, guard: 150},
{think: 2, idle: 0, fight: 200, reach: 8, guard: 250},
}
// BotClass is the class each level plays on each arena.
var BotClass = [3][3]int{
{Coward, Trickster, Reader},
{Hunter, Brawler, Reader},
{Brawler, Hunter, Trickster},
}
// A Bot plays one side of a match.
type Bot struct {
Level int
rng uint32
wait int
dir int
target int // square it is heading for, -1 for none
rescan int // decisions left before it looks for a better coin
stuck int
lastX int
lastY int
turn int
}
func NewBot(level int, seed uint32) *Bot {
return &Bot{Level: level, rng: seed*2654435761 + 1, dir: Still, target: -1}
}
func (b *Bot) rand(n int) int {
b.rng = b.rng*1103515245 + 12345
return int(b.rng>>8) % n
}
// toward picks one of the 16 directions for (dx, dy) with a few comparisons
// (tan 11.25, 33.75, 56.25 and 78.75 degrees); Still if both are 0.
func toward(dx, dy int) int {
if dx == 0 && dy == 0 {
return Still
}
ax, ay := abs(dx), abs(dy)
j := 4
if ay*1000 < ax*199 {
j = 0
} else if ay*1000 < ax*668 {
j = 1
} else if ay*1000 < ax*1497 {
j = 2
} else if ay*1000 < ax*5027 {
j = 3
}
if dx >= 0 && dy >= 0 {
return j
}
if dx < 0 && dy >= 0 {
return 8 - j
}
if dx < 0 {
return 8 + j
}
return (16 - j) % 16
}
// ringCoin looks for gold ring by ring outward from the fighter's square,
// up to r squares away, and stops one ring after the first find. -1 if none.
func (g *Game) ringCoin(me *Fighter, r int) int {
cx, cy := me.X/U, me.Y/U
best, bd, found := -1, 0, -1
for k := 0; k <= r; k++ {
if found >= 0 && k > found+1 {
break
}
for y := cy - k; y <= cy+k; y++ {
if y < 0 || y >= Size {
continue
}
step := 2 * k
if y == cy-k || y == cy+k || k == 0 {
step = 1
}
for x := cx - k; x <= cx+k; x += step {
if x < 0 || x >= Size || g.Coin[y*Size+x] == 0 {
continue
}
dx, dy := x*U+U/2-me.X, y*U+U/2-me.Y
if d := dx*dx + dy*dy; best < 0 || d < bd {
best, bd = y*Size+x, d
if found < 0 {
found = k
}
}
}
}
}
return best
}
// looseCoin finds gold on the fighter's square or one of the 8 round it (the
// first in ringX order), or -1.
func (g *Game) looseCoin(me *Fighter) int {
cx, cy := me.X/U, me.Y/U
if c := cy*Size + cx; g.Coin[c] != 0 {
return c
}
for k := 0; k < 8; k++ {
x, y := cx+ringX[k], cy+ringY[k]
if x >= 0 && y >= 0 && x < Size && y < Size && g.Coin[y*Size+x] != 0 {
return y*Size + x
}
}
return -1
}
// Act decides the bot's move and button for this tick, as side s.
func (b *Bot) Act(g *Game, s int) (int, int) {
lv := botLevels[b.Level]
me, o := &g.F[s], &g.F[1-s]
think := b.wait == 0
if !think {
b.wait--
} else {
b.wait = lv.think - 1
if b.rand(1000) < lv.idle {
b.dir = Still
} else {
tx, ty := o.X, o.Y
ex, ey := o.X-me.X, o.Y-me.Y
od := ex*ex + ey*ey
loose := g.looseCoin(me) // gold right next to it (knocked loose, say) comes first
chase := loose < 0 && o.Gold > 0 && od < 2500*2500 && (o.Gold >= me.Gold || od < 1600*1600) && b.rand(1000) < lv.fight
if !chase {
if loose >= 0 {
b.target = loose
} else if g.Coin[Mid*Size+Mid] == 3 {
b.target = Mid*Size + Mid // the jackpot is worth the trip
} else if b.target < 0 || g.Coin[b.target] == 0 || b.rescan <= 0 {
b.target = g.ringCoin(me, lv.reach)
b.rescan = 10
}
b.rescan--
if b.target >= 0 {
tx, ty = b.target%Size*U+U/2, b.target/Size*U+U/2
}
}
b.dir = toward(tx-me.X, ty-me.Y)
if b.stuck > 2 { // walking into a wall: slide round it for a moment
if b.turn == 0 {
b.dir = (b.dir + 4) % 16
} else {
b.dir = (b.dir + 12) % 16
}
b.turn = 1 - b.turn
b.stuck = 0
b.wait = 3
}
}
}
if b.dir != Still && abs(me.X-b.lastX)+abs(me.Y-b.lastY) < 60 {
b.stuck++
} else {
b.stuck = 0
}
b.lastX, b.lastY = me.X, me.Y
act := None
if lv.fight > 0 {
t := g.T
ex, ey := me.X-o.X, me.Y-o.Y
dd := ex*ex + ey*ey
if think && t >= me.CD && b.pays(g, me, o, dd) {
act = Special
} else if dd <= Melee*Melee && o.Gold > 0 && t >= me.AtkCD {
act = Attack
} else if lv.guard > 0 && dd <= Melee*Melee && t >= o.AtkCD && t >= me.BlockCD && me.Gold > 0 && b.rand(1000) < lv.guard {
act = Block
}
}
return b.dir, act
}
func (b *Bot) pays(g *Game, me, o *Fighter, dd int) bool {
return specialPays(g, me, o, dd, b.dir, b.target)
}
// specialPays says whether the class special is worth firing now: dir is where the
// bot is heading and target the coin square it wants (-1 for none).
func specialPays(g *Game, me, o *Fighter, dd, dir, target int) bool {
switch me.Class {
case Hunter:
return dd <= Long*Long && o.Gold > 0 && g.clear(me, o)
case Brawler, Trickster:
return dd <= Melee*Melee && o.Gold > 0
case Coward:
return dd < 2000*2000 && me.Gold > 0 && dir != Still
case Reader:
return target >= 0 && g.Coin[target] != 0 &&
abs(target%Size*U+U/2-me.X) <= Magnet*U && abs(target/Size*U+U/2-me.Y) <= Magnet*U
}
return false
}
// Versus replays a run (side A's inputs) against a house bot on side B.
func Versus(seed uint32, classA, level int, inA string) (int, int) {
if level < Easy || level > Hard {
panic("brawl: no such bot level")
}
if len(inA) > Ticks {
panic("brawl: inputs longer than a match")
}
g := New(seed, classA, BotClass[level][seed%3])
b := NewBot(level, seed)
for t := 0; t < Ticks; t++ {
m0, a0 := Still, None
if t < len(inA) {
c := inA[t]
if c >= 128 || decMove[c] < 0 {
panic("brawl: bad input character")
}
m0, a0 = decMove[c], decAct[c]
}
m1, a1 := b.Act(g, 1)
g.Step(m0, a0, m1, a1)
}
return g.F[0].Gold, g.F[1].Gold
}
brawl.gno
// Package brawl is the free-movement arena: two fighters run around a 15x15
// floor for one minute grabbing gold and robbing each other. It is written
// for the chain, so it uses whole numbers only and runs at 10 ticks a second.
// The browser runs an exact copy, so a match played there gives the same
// result when the chain replays the inputs.
//
// Units: 1000 = one square. x grows right, y grows down. Fighter A starts
// near (1,1), fighter B near the far corner.
//
// It is built to be cheap to replay on chain:
// - coins and power-ups sit in the middle of a square, and you grab one by
// standing on its square, so a tick needs one lookup instead of a loop;
// - timers hold the tick they run out on, so nothing counts down;
// - wall checks only run next to walls.
package brawl
const (
U = 1000
Size = 15
SizeU = Size * U
Cells = Size * Size
Mid = Size / 2 // middle square
TPS = 10
Ticks = 60 * TPS // match length
RushTicks = 10 * TPS // last 10 s are a gold rush
Speed = 420 // per tick
Rad = 380 // fighter radius
Melee = 1450
Long = 5000
Magnet = 4 // squares
StartCoins = 15
MaxCoins = 22
CoinEvery = 30
RushEvery = 9
PowerEvery = 120
FirstPower = 80
AttackCD = 8
BlockCD = 9
BlockT = 5
FeintT = 6
DodgeCD = 13
ComboGap = 20 // a combo's hits land within this many ticks of each other
ComboHits = 3 // the hit that makes a combo stuns
ComboStun = 6
Bounty = 15 // a lead this big doubles what hits knock out of the leader
Decay = 500 // knockback kept per tick, per mille
KnockMul = 66 // knockback per point of power, per tick
SubStep = 400 // longest move between wall checks
)
// Classes.
const (
Hunter = iota
Brawler
Coward
Trickster
Reader
)
// Actions.
const (
None = iota
Attack
Block
Special
Dodge
)
// Still means no movement this tick; 0..15 are directions.
const Still = 16
var SpecialCD = [5]int{40, 80, 40, 56, 30}
// Arenas are drawn by hand. Each list holds one square of every mirrored
// pair as x, y; its twin sits at (14-x, 14-y).
var arenaNames = [3]string{"Tavern", "Rooftop", "Scrapyard"}
var layouts = [3][3][]int{
{ // Tavern: tables everywhere, two kegs that kick you forward
{7, 2, 4, 3, 10, 3, 2, 6, 5, 6, 9, 5, 12, 2},
{1, 9, 7, 4},
{},
},
{ // Rooftop: open, full of speed pads
{7, 3, 3, 7, 4, 10},
{2, 5, 5, 2, 12, 3, 5, 5, 9, 1},
{},
},
{ // Scrapyard: crates and traps that knock gold out of you
{7, 2, 2, 7, 10, 5, 5, 4},
{7, 4},
{5, 1, 1, 5, 9, 7, 12, 3},
},
}
// ArenaName names the arena a seed plays on.
func ArenaName(seed uint32) string { return arenaNames[seed%3] }
// 16 directions, per mille, starting east and turning towards +y; 16 is still.
var dirX = [17]int{1000, 924, 707, 383, 0, -383, -707, -924, -1000, -924, -707, -383, 0, 383, 707, 924, 0}
var dirY = [17]int{0, 383, 707, 924, 1000, 924, 707, 383, 0, -383, -707, -924, -1000, -924, -707, -383, 0}
// running speed per direction (dir * Speed / 1000), precomputed
var runX, runY [17]int
func init() {
for i := 0; i < 17; i++ {
runX[i], runY[i] = dirX[i]*Speed/1000, dirY[i]*Speed/1000
}
}
// Square kinds.
const (
Empty = iota
Wall
Pad
Trap
)
// Power-up kinds, stored as kind+1 in Game.Power.
const (
Shield = iota
Double
Recharge
)
// Fighter timers (CD .. DodgeCD) hold the tick they run out on.
type Fighter struct {
Class int
X, Y, VX, VY int
Gold int
Shield bool
Double bool
CD int // special
AtkCD int
BlockCD int
BlockT int
FeintT int
InvT int
DashT int
DashX, DashY int
StunT int
TrapT int
BoostT int
PadT int
SwingT int
DodgeCD int
Face int
Cell int // square it stands on; things on a square happen when you step onto it
Combo int // hits landed on the rival in a row
ComboT int // the combo is lost if the next hit doesn't land before this tick
}
type Game struct {
Seed uint32
Arena int
T int // ticks played
End int // match length in ticks (Ticks unless set with NewLength)
F [2]Fighter
Move [2]*Recipe // a recipe used in place of the class special, or nil
Floor [Cells]byte // Empty, Wall, Pad, Trap
Coin [Cells]byte // gold on each square: 0, 1, or 3 for the jackpot
Power [Cells]byte // power-up on each square: 0, or kind+1
NCoins int
NPower int
nearWall [Cells]bool
nextCoin int // tick of the next coin drop
nextPower int
powerKind int
jackpot bool
rushOn bool
rng uint32
}
func (g *Game) rand() int {
g.rng = g.rng*1103515245 + 12345
return int(g.rng >> 8) // 0 .. 2^24-1
}
func abs(v int) int {
if v < 0 {
return -v
}
return v
}
func imax(a, b int) int {
if a > b {
return a
}
return b
}
// isqrt is the whole-number square root, rounded down.
func isqrt(n int) int {
if n <= 0 {
return 0
}
r, b := 0, 1<<30
for b > n {
b >>= 2
}
for b != 0 {
if n >= r+b {
n -= r + b
r = (r >> 1) + b
} else {
r >>= 1
}
b >>= 2
}
return r
}
func (g *Game) floor(x, y int) byte {
if x < 0 || y < 0 || x >= Size || y >= Size {
return Empty
}
return g.Floor[y*Size+x]
}
// New sets up a match. The seed picks the arena and lays out terrain and coins.
func New(seed uint32, classA, classB int) *Game {
g := &Game{Seed: seed, Arena: int(seed % 3), End: Ticks}
g.rng = seed*7919 + 17
for k, list := range layouts[g.Arena] {
for i := 0; i+1 < len(list); i += 2 {
c := list[i+1]*Size + list[i]
g.Floor[c] = byte(k + 1)
g.Floor[Cells-1-c] = byte(k + 1)
}
}
for c := 0; c < Cells; c++ {
if g.Floor[c] != Wall {
continue
}
x, y := c%Size, c/Size
for dy := -1; dy <= 1; dy++ {
for dx := -1; dx <= 1; dx++ {
if x+dx >= 0 && y+dy >= 0 && x+dx < Size && y+dy < Size {
g.nearWall[(y+dy)*Size+x+dx] = true
}
}
}
}
g.F[0] = Fighter{Class: classA, X: 1200, Y: 1200, Face: 1}
g.F[1] = Fighter{Class: classB, X: SizeU - 1200, Y: SizeU - 1200, Face: -1}
g.Coin[Mid*Size+Mid] = 1
g.NCoins = 1
for i := 0; i < 200 && g.NCoins < StartCoins; i++ {
c := g.rand() * Cells >> 24
x, y := c%Size, c/Size
if abs(x-Mid) <= 1 && abs(y-Mid) <= 1 {
continue
}
g.spawnAt(c, false, 1)
}
g.F[0].Cell, g.F[1].Cell = -1, -1
g.nextCoin = CoinEvery
g.nextPower = FirstPower
g.powerKind = int(seed % 3)
return g
}
// free reports whether a square can take a new coin or power-up.
func (g *Game) free(c int) bool {
if g.Floor[c] != Empty || g.Coin[c] != 0 || g.Power[c] != 0 {
return false
}
x, y := c%Size, c/Size
if x == 0 || y == 0 || x == Size-1 || y == Size-1 {
return false
}
for i := 0; i < 2; i++ {
if g.F[i].X/U == x && g.F[i].Y/U == y {
return false
}
}
return true
}
// spawnAt puts a mirrored pair on square c and its opposite, if both are free.
func (g *Game) spawnAt(c int, power bool, val int) bool {
return g.place(c, Cells-1-c, power, val)
}
// place puts a pair on squares c and m, if both are free.
func (g *Game) place(c, m int, power bool, val int) bool {
if c == m || !g.free(c) || !g.free(m) {
return false
}
if power {
g.Power[c], g.Power[m] = byte(val+1), byte(val+1)
g.NPower += 2
} else {
g.Coin[c], g.Coin[m] = byte(val), byte(val)
g.NCoins += 2
}
return true
}
// spawnPair drops a pair of coins or power-ups. Usually the pair is mirrored
// through the middle, one in each half of the floor. While a fighter trails by
// Bounty or more, new coins favour the trailing fighter's half instead: the
// pair is mirrored across the other diagonal, so both land in that half.
func (g *Game) spawnPair(power bool, val int) {
half := -1
if !power {
half = g.trailingHalf()
}
for i := 0; i < 40; i++ {
c := g.rand() * Cells >> 24
if half < 0 {
if g.spawnAt(c, power, val) {
return
}
continue
}
x, y := c%Size, c/Size
if x+y != Size-1 && (x+y < Size-1) != (half == 0) {
x, y = Size-1-x, Size-1-y
}
if g.place(y*Size+x, x*Size+y, power, val) {
return
}
}
}
// trailingHalf is the half of the floor the trailing fighter stands in while
// the lead is Bounty or more: 0 for A's corner (x+y < 14), 1 for B's; -1
// while the match is close.
func (g *Game) trailingHalf() int {
a, b := &g.F[0], &g.F[1]
tr := a
if a.Gold-b.Gold >= Bounty {
tr = b
} else if b.Gold-a.Gold < Bounty {
return -1
}
if tr.X/U+tr.Y/U < Size-1 {
return 0
}
return 1
}
func (g *Game) Over() bool { return g.T >= g.End }
// NewLength is New for a longer or shorter match (rooms use it); the jackpot
// still drops at half time and the gold rush fills the last 10 seconds.
func NewLength(seed uint32, classA, classB, ticks int) *Game {
if ticks < 2*RushTicks {
panic("brawl: match too short")
}
g := New(seed, classA, classB)
g.End = ticks
return g
}
// Winner is 0 or 1, or -1 for a draw.
func (g *Game) Winner() int {
a, b := g.F[0].Gold, g.F[1].Gold
if a > b {
return 0
}
if b > a {
return 1
}
return -1
}
// Step runs one tick. move is a direction 0..15 or Still; act is an action.
func (g *Game) Step(move0, act0, move1, act1 int) {
t := g.T
if t >= g.End {
return
}
// actions first; the side that goes first swaps every tick
if act0 != None || act1 != None {
if t%2 == 0 {
g.act(0, move0, act0)
g.act(1, move1, act1)
} else {
g.act(1, move1, act1)
g.act(0, move0, act0)
}
}
a, b := &g.F[0], &g.F[1]
g.move(a, move0, t)
g.move(b, move1, t)
dx, dy := b.X-a.X, b.Y-a.Y
if dx < 2*Rad && dx > -2*Rad && dy < 2*Rad && dy > -2*Rad {
if dd := dx*dx + dy*dy; dd < 4*Rad*Rad && dd > 0 {
d := isqrt(dd)
push := (2*Rad - d) / 2
nx, ny := dx*push/d, dy*push/d
a.X -= nx
a.Y -= ny
b.X += nx
b.Y += ny
g.collide(a)
g.collide(b)
}
}
t++
g.T = t
if c := a.Y/U*Size + a.X/U; c != a.Cell {
a.Cell = c
g.land(a, t)
}
if c := b.Y/U*Size + b.X/U; c != b.Cell {
b.Cell = c
g.land(b, t)
}
if t == g.End/2 && !g.jackpot {
g.jackpot = true
c := Mid*Size + Mid
if g.Coin[c] == 0 {
g.NCoins++
}
g.Coin[c] = 3
if a.Cell == c {
a.Cell = -1 // grab it next tick
}
if b.Cell == c {
b.Cell = -1
}
}
if t == g.End-RushTicks && !g.rushOn {
g.rushOn = true
g.nextCoin = t
}
if t >= g.nextCoin {
g.nextCoin = t + CoinEvery
limit := MaxCoins
if g.rushOn {
g.nextCoin = t + RushEvery
limit += 8
}
if g.NCoins+2 <= limit {
g.spawnPair(false, 1)
}
}
if t >= g.nextPower {
g.nextPower = t + PowerEvery
if g.NPower == 0 {
kind := g.powerKind
g.powerKind = (g.powerKind + 1) % 3
g.spawnPair(true, kind)
}
}
}
func (g *Game) move(me *Fighter, dir, t int) {
if dir == Still && me.VX == 0 && me.VY == 0 && t >= me.DashT {
return
}
var vx, vy int
if t < me.DashT {
vx, vy = me.DashX, me.DashY
} else {
if t < me.BoostT || t < me.StunT || t < me.BlockT {
sp := Speed
if t < me.BoostT {
sp = Speed * 18 / 10
}
if t < me.StunT {
sp /= 4
}
if t < me.BlockT {
sp /= 2
}
vx, vy = dirX[dir]*sp/1000, dirY[dir]*sp/1000
} else {
vx, vy = runX[dir], runY[dir]
}
if me.VX != 0 || me.VY != 0 {
vx += me.VX
vy += me.VY
me.VX = me.VX * Decay / 1000
me.VY = me.VY * Decay / 1000
}
}
if vx == 0 && vy == 0 {
return
}
if vx > -SubStep && vx < SubStep && vy > -SubStep && vy < SubStep {
me.X += vx
me.Y += vy
g.collide(me)
} else {
n := (imax(abs(vx), abs(vy)) + SubStep - 1) / SubStep
for i := 0; i < n; i++ {
me.X += vx*(i+1)/n - vx*i/n
me.Y += vy*(i+1)/n - vy*i/n
g.collide(me)
}
}
if vx > 30 {
me.Face = 1
} else if vx < -30 {
me.Face = -1
}
}
func (g *Game) collide(me *Fighter) {
if me.X < Rad {
me.X = Rad
} else if me.X > SizeU-Rad {
me.X = SizeU - Rad
}
if me.Y < Rad {
me.Y = Rad
} else if me.Y > SizeU-Rad {
me.Y = SizeU - Rad
}
if !g.nearWall[me.Y/U*Size+me.X/U] {
return
}
x0c, x1c, y0c, y1c := (me.X-Rad)/U, (me.X+Rad)/U, (me.Y-Rad)/U, (me.Y+Rad)/U
for wy := y0c; wy <= y1c; wy++ {
for wx := x0c; wx <= x1c; wx++ {
if wx >= Size || wy >= Size || g.Floor[wy*Size+wx] != Wall {
continue
}
x0, x1, y0, y1 := wx*U+80, wx*U+920, wy*U+80, wy*U+920
px, py := me.X, me.Y
if px < x0 {
px = x0
} else if px > x1 {
px = x1
}
if py < y0 {
py = y0
} else if py > y1 {
py = y1
}
dx, dy := me.X-px, me.Y-py
dd := dx*dx + dy*dy
if dd >= Rad*Rad {
continue
}
if d := isqrt(dd); d > 0 {
me.X = px + dx*Rad/d
me.Y = py + dy*Rad/d
} else {
me.X = x0 - Rad
}
}
}
}
// land handles whatever is on the square a fighter stands on.
func (g *Game) land(me *Fighter, t int) {
c := me.Y/U*Size + me.X/U
if v := g.Coin[c]; v != 0 {
g.Coin[c] = 0
g.NCoins--
g.collect(me, int(v))
}
if p := g.Power[c]; p != 0 {
g.Power[c] = 0
g.NPower--
switch int(p) - 1 {
case Shield:
me.Shield = true
case Double:
me.Double = true
default:
me.CD = 0
}
}
switch g.Floor[c] {
case Trap:
if t >= me.TrapT && t >= me.DashT {
me.TrapT = t + 12
me.StunT = imax(me.StunT, t+3)
if me.Gold > 0 {
me.Gold--
}
}
case Pad:
if t >= me.PadT {
me.BoostT = t + 9
me.PadT = t + 10
}
}
}
func (g *Game) collect(me *Fighter, val int) {
if me.Double {
val *= 2
me.Double = false
}
me.Gold += val
}
// hit is a blow from side s that lands: it knocks n gold out of the rival
// onto the floor round them (twice as much from a leader who is Bounty or
// more ahead), and counts towards a combo; the ComboHits-th hit in a row
// within ComboGap ticks of the last stuns the rival.
func (g *Game) hit(s, n int) {
t := g.T
me, o := &g.F[s], &g.F[1-s]
o.Combo = 0 // taking a hit breaks your own combo
if t < me.ComboT {
me.Combo++
} else {
me.Combo = 1
}
me.ComboT = t + ComboGap
if me.Combo >= ComboHits {
me.Combo = 0
o.StunT = imax(o.StunT, t+ComboStun)
}
if o.Gold-me.Gold >= Bounty {
n *= 2
}
if n > 0 && o.Shield {
n--
o.Shield = false
}
if n > o.Gold {
n = o.Gold
}
if n <= 0 {
return
}
o.Gold -= n
g.drop(o, me, n)
}
// The squares round a fighter, nearest first: the ring of 8, then the ring of 16.
var ringX = [24]int{1, 1, 0, -1, -1, -1, 0, 1, 2, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1}
var ringY = [24]int{0, 1, 1, 1, 0, -1, -1, -1, -2, -1, 0, 1, 2, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2}
// drop scatters n coins knocked out of victim onto free squares round it:
// each on the free square of the inner ring nearest the hitter (the outer
// ring if the inner one is full; ties go to the first in ringX order). If
// there is no room at all, the hitter pockets the rest.
func (g *Game) drop(victim, hitter *Fighter, n int) {
cx, cy := victim.X/U, victim.Y/U
for ; n > 0; n-- {
best, bd := -1, 0
for k := 0; k < 24; k++ {
if k == 8 && best >= 0 {
break
}
x, y := cx+ringX[k], cy+ringY[k]
if x < 1 || y < 1 || x >= Size-1 || y >= Size-1 || !g.free(y*Size+x) {
continue
}
dx, dy := x*U+U/2-hitter.X, y*U+U/2-hitter.Y
if d := dx*dx + dy*dy; best < 0 || d < bd {
best, bd = y*Size+x, d
}
}
if best < 0 {
hitter.Gold += n
return
}
g.Coin[best] = 1
g.NCoins++
}
}
// steal moves n gold straight from the rival to side s (a parry).
func (g *Game) steal(s, n int) {
thief, victim := &g.F[s], &g.F[1-s]
if n > 0 && victim.Shield {
n--
victim.Shield = false
}
if n > victim.Gold {
n = victim.Gold
}
if n <= 0 {
return
}
victim.Gold -= n
thief.Gold += n
}
func knock(t, from *Fighter, power int) {
dx, dy := t.X-from.X, t.Y-from.Y
l := isqrt(dx*dx + dy*dy)
if l == 0 {
l = 1
}
t.VX += dx * power * KnockMul / l
t.VY += dy * power * KnockMul / l
}
func dash(me *Fighter, dx, dy, length, ticks, t int) {
l := isqrt(dx*dx + dy*dy)
if l == 0 {
l = 1
}
me.DashT = t + ticks
me.DashX = dx * length / l / ticks
me.DashY = dy * length / l / ticks
}
func (g *Game) act(s, dir, action int) {
if action == None {
return
}
t := g.T
me, o := &g.F[s], &g.F[1-s]
mx, my := dirX[dir], dirY[dir]
if action == Dodge { // works while dazed: it's your escape
if t < me.DodgeCD {
return
}
me.DodgeCD = t + DodgeCD
me.StunT = 0
dx, dy := mx, my
if dx == 0 && dy == 0 {
dx, dy = me.X-o.X, me.Y-o.Y
}
dash(me, dx, dy, 2400, 2, t)
me.InvT = imax(me.InvT, t+4)
return
}
if t < me.StunT {
return
}
dx, dy := me.X-o.X, me.Y-o.Y
dd := dx*dx + dy*dy
oBlocks := t < o.BlockT || t < o.FeintT
oSafe := t < o.InvT
switch action {
case Attack:
if t < me.AtkCD {
return
}
me.AtkCD = t + AttackCD
me.SwingT = t + 3
if dd > Melee*Melee || oSafe {
return
}
if oBlocks { // parried: the blocker takes a coin straight from you
me.Combo = 0
g.steal(1-s, 1)
me.StunT = t + 5
me.AtkCD = t + 9
} else {
g.hit(s, 1)
knock(o, me, 3)
}
case Block:
if t < me.BlockCD {
return
}
me.BlockCD = t + BlockCD
me.BlockT = t + BlockT
case Special:
if t < me.CD {
return
}
if r := g.Move[s]; r != nil {
me.CD = t + r.CD
g.recipe(s, r, mx, my, dd, oBlocks, oSafe)
return
}
me.CD = t + SpecialCD[me.Class]
g.special(s, mx, my, dd, oBlocks, oSafe)
}
}
func (g *Game) special(s, mx, my, dd int, oBlocks, oSafe bool) {
t := g.T
me, o := &g.F[s], &g.F[1-s]
switch me.Class {
case Hunter:
if dd <= Long*Long && !oSafe && g.clear(me, o) {
g.hit(s, 1)
knock(o, me, 2)
o.StunT = imax(o.StunT, t+5) // dazed for half a second
}
case Brawler:
if dd <= (Melee+150)*(Melee+150) && !oSafe {
n := 2
if oBlocks {
n = 1
}
g.hit(s, n)
knock(o, me, 9)
o.StunT = imax(o.StunT, t+4)
} else {
dash(me, o.X-me.X, o.Y-me.Y, 1400, 2, t)
}
case Coward:
dx, dy := mx, my
if dx == 0 && dy == 0 {
if c := g.nearestCoin(me, Size); c >= 0 {
dx, dy = c%Size*U+U/2-me.X, c/Size*U+U/2-me.Y
} else {
dx, dy = me.X-o.X, me.Y-o.Y
}
}
dash(me, dx, dy, 4000, 3, t)
me.InvT = t + 7
me.Shield = true
case Trickster:
me.FeintT = t + FeintT
if dd <= Melee*Melee && t >= o.SwingT && !oSafe {
g.hit(s, 1)
}
case Reader:
for k := 0; k < 2; k++ {
c := g.nearestCoin(me, Magnet)
if c < 0 {
break
}
v := int(g.Coin[c])
g.Coin[c] = 0
g.NCoins--
g.collect(me, v)
}
}
}
// nearestCoin finds the closest square with gold, measured from the fighter
// to the middle of the square, within r squares. -1 if none.
func (g *Game) nearestCoin(me *Fighter, r int) int {
cx, cy := me.X/U, me.Y/U
best, bd := -1, 0
lim := (r*U + U/2) * (r*U + U/2)
for y := cy - r; y <= cy+r; y++ {
if y < 0 || y >= Size {
continue
}
for x := cx - r; x <= cx+r; x++ {
if x < 0 || x >= Size || g.Coin[y*Size+x] == 0 {
continue
}
dx, dy := x*U+U/2-me.X, y*U+U/2-me.Y
d := dx*dx + dy*dy
if d <= lim && (best < 0 || d < bd) {
best, bd = y*Size+x, d
}
}
}
return best
}
// clear reports whether the straight line between two fighters misses every wall.
func (g *Game) clear(a, b *Fighter) bool {
dx, dy := b.X-a.X, b.Y-a.Y
steps := (isqrt(dx*dx+dy*dy) + 199) / 200
for i := 1; i < steps; i++ {
x := a.X + dx*i/steps
y := a.Y + dy*i/steps
cx, cy := x/U, y/U
if g.Floor[cy*Size+cx] == Wall {
lx, ly := x-cx*U, y-cy*U
if lx > 100 && lx < 900 && ly > 100 && ly < 900 {
return false
}
}
}
return true
}
brawl_test.gno
package brawl
import "testing"
// noisy makes a full match of inputs: hold a direction for a few ticks,
// press a button now and then.
func noisy(seed uint32) string {
b := make([]byte, Ticks)
s := seed
dir, hold := 0, 0
for t := 0; t < Ticks; t++ {
s = s*1103515245 + 12345
r := int(s >> 8)
if hold == 0 {
dir = r % 17
hold = 3 + r%8
}
hold--
act := None
if r%7 == 0 {
act = 1 + (r>>4)%4
}
b[t] = Encode(dir, act)
}
return string(b)
}
func TestInputsOnly(t *testing.T) {
a, b := noisy(1), noisy(2)
if len(a) != Ticks || len(b) != Ticks {
t.Fatal("length")
}
}
func TestFullMatch(t *testing.T) {
a, b := noisy(1), noisy(2)
ga, gb := Play(42, Hunter, Brawler, a, b)
t.Logf("gold %d - %d", ga, gb)
if ga+gb == 0 {
t.Fatal("nobody scored")
}
}
func TestDeterministic(t *testing.T) {
a, b := noisy(5), noisy(6)
x1, y1 := Play(7, Coward, Reader, a, b)
x2, y2 := Play(7, Coward, Reader, a, b)
if x1 != x2 || y1 != y2 {
t.Fatal("replay differs")
}
}
func TestWallsHold(t *testing.T) {
for seed := uint32(0); seed < 6; seed++ {
g := New(seed, Coward, Brawler)
a, b := noisy(seed+10), noisy(seed+20)
for i := 0; i < Ticks; i++ {
m0, a0 := in(a, i)
m1, a1 := in(b, i)
g.Step(m0, a0, m1, a1)
for s := 0; s < 2; s++ {
f := g.F[s]
cx, cy := f.X/U, f.Y/U
if g.floor(cx, cy) == Wall {
lx, ly := f.X-cx*U, f.Y-cy*U
if lx > 100 && lx < 900 && ly > 100 && ly < 900 {
t.Fatalf("seed %d tick %d: fighter %d inside a wall", seed, i, s)
}
}
}
}
}
}
func TestLayouts(t *testing.T) {
for arena := uint32(0); arena < 3; arena++ {
g := New(arena, Hunter, Hunter)
n := 0
for c := 0; c < Cells; c++ {
k := g.Floor[c]
if k == Empty {
continue
}
n++
if g.Floor[Cells-1-c] != k {
t.Fatalf("%s: square %d not mirrored", ArenaName(arena), c)
}
x, y := c%Size, c/Size
if (x-1)*(x-1)+(y-1)*(y-1) <= 10 || (x-13)*(x-13)+(y-13)*(y-13) <= 10 {
t.Fatalf("%s: square %d,%d too close to a start", ArenaName(arena), x, y)
}
if abs(x-Mid) <= 1 && abs(y-Mid) <= 1 {
t.Fatalf("%s: square %d,%d in the middle", ArenaName(arena), x, y)
}
}
want := 0
for _, l := range layouts[arena] {
want += len(l)
}
if n != want {
t.Fatalf("%s: %d squares, want %d (overlap?)", ArenaName(arena), n, want)
}
}
}
// arena sets two fighters a square apart in the open middle of the Rooftop.
func arena() *Game {
g := New(1, Brawler, Reader)
g.Coin = [Cells]byte{}
g.NCoins = 0
g.F[0].X, g.F[0].Y = 6500, 8500
g.F[1].X, g.F[1].Y = 7500, 8500
g.F[1].Gold = 10
return g
}
// A hit knocks gold onto the floor next to the victim, on the side nearest
// the hitter, instead of into the hitter's purse.
func TestKnockOut(t *testing.T) {
g := arena()
g.Step(Still, Attack, Still, None)
if g.F[1].Gold != 9 || g.F[0].Gold != 0 || g.NCoins != 1 {
t.Fatalf("gold %d-%d, %d coins on the floor", g.F[0].Gold, g.F[1].Gold, g.NCoins)
}
// victim on square 7,8; the free squares next to it nearest the hitter
// (on 6,8) are 6,9 and 6,7, and 6,9 comes first
if g.Coin[9*Size+6] != 1 {
t.Fatal("coin not on 6,9")
}
}
func TestParryPaysDirect(t *testing.T) {
g := arena()
g.F[0].Gold = 4
g.Step(Still, None, Still, Block)
g.Step(Still, Attack, Still, None)
if g.F[0].Gold != 3 || g.F[1].Gold != 11 || g.T >= g.F[0].StunT {
t.Fatalf("parry: %d-%d, stun until %d", g.F[0].Gold, g.F[1].Gold, g.F[0].StunT)
}
}
func TestComboStuns(t *testing.T) {
g := arena()
g.hit(0, 1)
g.T = 10
g.hit(0, 1)
if g.F[1].StunT > g.T {
t.Fatal("two hits stunned")
}
g.T = 25
g.hit(0, 1)
if g.F[1].StunT != 25+ComboStun || g.F[0].Combo != 0 {
t.Fatalf("third hit: stun until %d", g.F[1].StunT)
}
// too slow: the combo starts again
g.T = 30
g.hit(0, 1)
g.T = 60
g.hit(0, 1)
if g.F[0].Combo != 1 {
t.Fatalf("combo %d after a gap", g.F[0].Combo)
}
// being hit breaks your own combo
g.T = 62
g.hit(1, 1)
if g.F[0].Combo != 0 {
t.Fatal("combo kept after taking a hit")
}
}
func TestBounty(t *testing.T) {
g := arena()
g.F[1].Gold = 20 // 20 ahead of a rival with 0
g.hit(0, 1)
if g.F[1].Gold != 18 || g.NCoins != 2 {
t.Fatalf("bounty hit left %d, %d coins", g.F[1].Gold, g.NCoins)
}
g.F[1].Shield = true
g.hit(0, 2) // 4, less 1 for the shield
if g.F[1].Gold != 15 {
t.Fatalf("shielded bounty hit left %d", g.F[1].Gold)
}
g.hit(0, 1) // 15 ahead still pays double
if g.F[1].Gold != 13 {
t.Fatalf("left %d", g.F[1].Gold)
}
g.hit(0, 1) // 13 ahead: back to 1
if g.F[1].Gold != 12 {
t.Fatalf("left %d", g.F[1].Gold)
}
}
// While one side leads by Bounty, new coins land in the trailing side's half.
func TestSpawnFavoursTrailing(t *testing.T) {
for s := 0; s < 2; s++ {
g := New(uint32(10+s), Hunter, Hunter)
g.Coin = [Cells]byte{}
g.NCoins = 0
g.F[1-s].Gold = Bounty
for i := 0; i < 6; i++ {
g.spawnPair(false, 1)
}
if g.NCoins != 12 {
t.Fatalf("%d coins", g.NCoins)
}
for c := 0; c < Cells; c++ {
if g.Coin[c] == 0 {
continue
}
h := c%Size + c/Size
if s == 0 && h > Size-1 || s == 1 && h < Size-1 {
t.Fatalf("side %d trails but a coin fell on %d,%d", s, c%Size, c/Size)
}
}
}
}
decode.gno
package brawl
// Decode reads one input character: the move (a direction 0..15 or Still)
// and the action. ok is false for a character that isn't an input.
func Decode(c byte) (move, act int, ok bool) {
if c >= 128 || decMove[c] < 0 {
return Still, None, false
}
return decMove[c], decAct[c], true
}
gnomod.toml
module = "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v3" gno = "0.9" [addpkg] creator = "g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28" height = 1559808 max_deposit = "50000000ugnot"
inputs.gno
package brawl
// A fighter's inputs for a whole match are one character per tick. Each
// character holds a move (a direction 0..15, or Still) and an action:
// value = move + 17*action, written with the alphabet below.
const alphabet = "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~!"
// per character: move and action, or -1 if the character isn't used
var decMove, decAct [128]int
func init() {
for i := range decMove {
decMove[i], decAct[i] = -1, -1
}
for i := 0; i < 17*5; i++ {
decMove[alphabet[i]], decAct[alphabet[i]] = i%17, i/17
}
}
// Encode writes one tick's input as a character.
func Encode(move, act int) byte { return alphabet[move+17*act] }
// Play replays a whole match from both fighters' inputs and returns the gold
// each one ended with. Short inputs mean standing still for the rest; a bad
// character panics.
func Play(seed uint32, classA, classB int, inA, inB string) (int, int) {
return play(seed, classA, classB, inA, inB, false, nil, nil)
}
// Duel is Play for a ghost: every run is recorded from A's corner, so B's
// inputs (an earlier run) are turned round to play from the far corner. The
// floor is mirrored through the middle, so the ghost sees the same arena.
func Duel(seed uint32, classA, classB int, inA, inB string) (int, int) {
return play(seed, classA, classB, inA, inB, true, nil, nil)
}
func play(seed uint32, classA, classB int, inA, inB string, mirrorB bool, moveA, moveB *Recipe) (int, int) {
g := New(seed, classA, classB)
g.Move[0], g.Move[1] = moveA, moveB
if len(inA) > Ticks || len(inB) > Ticks {
panic("brawl: inputs longer than a match")
}
for t := 0; t < Ticks; t++ {
m0, a0, m1, a1 := Still, None, Still, None
if t < len(inA) {
c := inA[t]
if c >= 128 || decMove[c] < 0 {
panic("brawl: bad input character")
}
m0, a0 = decMove[c], decAct[c]
}
if t < len(inB) {
c := inB[t]
if c >= 128 || decMove[c] < 0 {
panic("brawl: bad input character")
}
m1, a1 = decMove[c], decAct[c]
if mirrorB && m1 != Still {
m1 = (m1 + 8) % 16
}
}
g.Step(m0, a0, m1, a1)
}
return g.F[0].Gold, g.F[1].Gold
}
// Valid reports whether s is a well-formed set of inputs for one fighter.
func Valid(s string) bool {
if len(s) > Ticks {
return false
}
for i := 0; i < len(s); i++ {
if s[i] >= 128 || decMove[s[i]] < 0 {
return false
}
}
return true
}
func in(s string, t int) (int, int) {
if t >= len(s) {
return Still, None
}
c := s[t]
if c >= 128 || decMove[c] < 0 {
panic("brawl: bad input character")
}
return decMove[c], decAct[c]
}
parity_test.gno
package brawl
import (
"strconv"
"testing"
)
// gen makes a match of inputs the same way the browser's parity check does.
func gen(seed uint32) string {
b := make([]byte, Ticks)
s := seed
dir, hold := 0, 0
for t := 0; t < Ticks; t++ {
s = s*1103515245 + 12345
r := int(s >> 8)
if hold == 0 {
dir = r % 17
hold = 5 + r%12
}
hold--
act := 0
if r%7 == 0 {
act = 1 + (r>>4)%4
}
b[t] = Encode(dir, act)
}
return string(b)
}
// fingerprint plays a match and folds both fighters' state into a number
// every tick, so any difference between two copies of the rules shows up.
func fingerprint(seed uint32, ca, cb int, inA, inB string, mirror bool) string {
g := New(seed, ca, cb)
var h uint32
for t := 0; t < Ticks; t++ {
m0, a0 := in(inA, t)
m1, a1 := in(inB, t)
if mirror && m1 != Still {
m1 = (m1 + 8) % 16
}
g.Step(m0, a0, m1, a1)
for s := 0; s < 2; s++ {
f := g.F[s]
h = h*31 + uint32(f.X+7*f.Y+13*f.Gold)
}
h = h*31 + uint32(g.NCoins+5*g.NPower)
}
return strconv.Itoa(g.F[0].Gold) + "-" + strconv.Itoa(g.F[1].Gold) + ":" + strconv.FormatUint(uint64(h), 10)
}
func TestParity(t *testing.T) {
out := ""
for i := 0; i < 30; i++ {
seed := uint32(i * 7)
out += fingerprint(seed, i%5, (i*3+1)%5, gen(uint32(2*i+1)), gen(uint32(2*i+2)), i%2 == 1) + " "
}
t.Logf("PARITY %s", out)
}
func botFingerprint(seed uint32, ca, level int, inA string) string {
g := New(seed, ca, BotClass[level][seed%3])
b := NewBot(level, seed)
var h uint32
for t := 0; t < Ticks; t++ {
m0, a0 := in(inA, t)
m1, a1 := b.Act(g, 1)
g.Step(m0, a0, m1, a1)
for s := 0; s < 2; s++ {
f := g.F[s]
h = h*31 + uint32(f.X+7*f.Y+13*f.Gold)
}
}
return strconv.Itoa(g.F[0].Gold) + "-" + strconv.Itoa(g.F[1].Gold) + ":" + strconv.FormatUint(uint64(h), 10)
}
func TestBotParity(t *testing.T) {
out := ""
for i := 0; i < 18; i++ {
out += botFingerprint(uint32(i*5+1), i%5, i%3, gen(uint32(100+i))) + " "
}
t.Logf("BOTPARITY %s", out)
}
// Move recipes: the browser must accept and refuse the same recipes, cost
// them the same, and play matches with them the same.
var recipeChecks = []string{
"Blink Thief/84/D82S11", "Haymaker/150/S21K91T41", "Sniper/54/S15K25", "Magnet/40/P24",
"Turtle/147/H00I90", "Bully/90/D41T53K94", "Grab Dash/33/P11D62", "Flee/36/D83",
"A/32/S11", "Rush-in/50/D71I30", "O'Hare/150/S22P13T21", "Z/200/P35", "Pick/20/P11",
"A/20/S11", "A/31/S11", "Sniper/53/S15K25", "", "x", "A/20/", "A/020/S11", "A/19/H00", "A/201/H00", " A/20/H00", "A /20/H00", "A/20/H01",
"A/20/S11S11", "A/20/Q11", "A/20/S1", "A/99/S11H00I90K11", "A|B/20/H00", "A/30/S12H00",
"Thief Lord/200/S35", "ABCDEFGHIJKLMNOPQ/20/H00", "A/20/D80", "A/20/D90", "A/20/S01", "A/20/S16",
"A/20/I91", "A/20/T05", "A/20/K95", "A/2x/H00", "A/20/H00/", "A/20/h00",
}
func recipeLine() string {
out := ""
for _, s := range recipeChecks {
r, err := ParseRecipe(s)
if err != nil {
out += "x "
continue
}
out += r.String() + "=" + strconv.Itoa(r.Cost()) + " "
}
return out
}
func validRecipes() []*Recipe {
rs := []*Recipe{}
for _, s := range recipeChecks {
if r, err := ParseRecipe(s); err == nil {
rs = append(rs, r)
}
}
return rs
}
func moveFingerprint(seed uint32, ca, cb int, inA, inB string, mirror bool, ra, rb *Recipe) string {
g := New(seed, ca, cb)
g.Equip(0, ra)
g.Equip(1, rb)
var h uint32
for t := 0; t < Ticks; t++ {
m0, a0 := in(inA, t)
m1, a1 := in(inB, t)
if mirror && m1 != Still {
m1 = (m1 + 8) % 16
}
g.Step(m0, a0, m1, a1)
for s := 0; s < 2; s++ {
f := g.F[s]
h = h*31 + uint32(f.X+7*f.Y+13*f.Gold+17*f.StunT+19*f.InvT)
}
h = h*31 + uint32(g.NCoins+5*g.NPower)
}
return strconv.Itoa(g.F[0].Gold) + "-" + strconv.Itoa(g.F[1].Gold) + ":" + strconv.FormatUint(uint64(h), 10)
}
func TestParityMoves(t *testing.T) {
t.Logf("RECIPES %s", recipeLine())
rs := validRecipes()
n := len(rs)
out := ""
for i := 0; i < 22; i++ {
ra, rb := rs[i%n], rs[(i*3+1)%n]
if i%4 == 0 {
rb = nil
}
out += moveFingerprint(uint32(i*11+3), i%5, (i*2+3)%5, gen(uint32(300+2*i)), gen(uint32(301+2*i)), i%2 == 1, ra, rb) + " "
}
t.Logf("MOVES %s", out)
bo := ""
for i := 0; i < 11; i++ {
inA := gen(uint32(400 + i))
a, b := VersusMove(uint32(i*13+2), i%5, i%3, inA, rs[i%n].String())
bo += strconv.Itoa(a) + "-" + strconv.Itoa(b) + " "
}
t.Logf("MOVEBOT %s", bo)
}
// Bot profiles: the browser must accept and refuse the same profiles and
// play the same matches against them.
var profileChecks = []string{
"c1t3i1f6j8r6a7b2s5d4k0", "c0t3i0f9j9r8a9b9s9d9k5", "c4t9i9f0j0r1a0b0s0d0k0", "c2t4i2f1j5r4a3b6s9d8k3",
"c3t3i0f7j2r8a9b1s7d2k1", "c0t5i4f3j9r3a5b5s5d5k2", "c1t3i0f0j0r8a0b0s0d0k0",
"", "c5t3i1f6j8r6a7b2s5d4k0", "c1t1i1f6j8r6a7b2s5d4k0", "c1t2i1f6j8r6a7b2s5d4k0", "c1t3i1f6j8r9a7b2s5d4k0", "c1t3i1f6j8r0a7b2s5d4k0",
"c1t3i1f6j8r6a7b2s5d4k6", "c1t3i1f6j8r6a7b2s5d4k", "c1t3i1f6j8r6a7b2s5d4k00", "t3c1i1f6j8r6a7b2s5d4k0",
"C1t3i1f6j8r6a7b2s5d4k0", "c1t3i1f6j8r6a7b2s5d4kx", "c1t3i1f6j8r6a7b2s5d4k/", "c1t3 i1f6j8r6a7b2s5d4k0",
}
func profileFingerprint(seed uint32, ca int, p *Profile, inA string) string {
g := New(seed, ca, p.Class)
b := NewProfileBot(p, seed)
var h uint32
for t := 0; t < Ticks; t++ {
m0, a0 := in(inA, t)
m1, a1 := b.Act(g, 1)
g.Step(m0, a0, m1, a1)
for s := 0; s < 2; s++ {
f := g.F[s]
h = h*31 + uint32(f.X+7*f.Y+13*f.Gold+17*f.StunT+19*f.InvT)
}
}
return strconv.Itoa(g.F[0].Gold) + "-" + strconv.Itoa(g.F[1].Gold) + ":" + strconv.FormatUint(uint64(h), 10)
}
func TestParityProfiles(t *testing.T) {
out := ""
ps := []*Profile{}
for _, s := range profileChecks {
p, err := ParseProfile(s)
if err != nil {
out += "x "
continue
}
ps = append(ps, p)
out += p.String() + " "
}
n := len(ps)
for i := 0; i < 14; i++ {
out += profileFingerprint(uint32(i*17+4), i%5, ps[i%n], gen(uint32(500+i))) + " "
}
a, b := VersusProfile(9, 2, ps[0].String(), gen(600))
out += strconv.Itoa(a) + "-" + strconv.Itoa(b)
t.Logf("PROFILEBOT %s", out)
}
// Smart plans: the browser must accept and refuse the same plans, with the
// same errors, and play the same rounds with them.
var planChecks = []string{
"collect 120; chase 60; if near 1.4: attack; auto 60",
"run NE 20; goto 7,7; collect 100; if near 5: special; flee 30",
"chase 40; attack; block; special; dodge; wait 5; chase 40; if near 2 attack",
"auto 300",
"goto (12,2) 80; goto 2, 12; collect 300",
"RUN se 10\nWAIT 3\nCollect 50;if NEAR 3.5 : Special",
"flee 100; run 5 20; collect 120",
"",
"chase 30; if near 1.4: attack; chase 10; if near 1.4: attack; chase 10; if near 1.4: attack; collect 200",
"goto 0,14; goto 14,0; goto 7,3; dodge; collect 150",
"run N", "run X 5", "run 16 5", "wait 0", "wait 301", "attack 3", "goto 15,3", "goto 3", "if far 2: attack",
"if near 0: attack", "if near 1.45: attack", "if near 2: jump", "fly 3", "collect", "chase -3", "run N 5 ; ; dance",
"caf\u00e9 3", "if near 2:", "goto 3,4 0",
"guard on; auto 200; guard off; collect 40", "guard on; collect 240", "chase 60; guard on; if near 1.45: attack; chase 60; collect 100",
"guard", "guard maybe", "if near 1.456: attack", "if near 0.05: attack",
}
func planCheckList() []string {
l := append([]string{}, planChecks...)
long := ""
for i := 0; i < 72; i++ {
long += "wait 1;"
}
return append(l, long)
}
func planFingerprint(seed uint32, ca, cb int, pa, pb string, i int) string {
g := NewLength(seed, ca, cb, 240)
a, _ := ParsePlan(pa)
var b *Plan
var bot *Bot
if i%2 == 0 {
b, _ = ParsePlan(pb)
} else {
bot = NewBot(i%3, seed)
}
var h uint32
for !g.Over() {
m0, a0 := a.Next(g, 0)
var m1, a1 int
if b != nil {
m1, a1 = b.Next(g, 1)
} else {
m1, a1 = bot.Act(g, 1)
}
g.Step(m0, a0, m1, a1)
for s := 0; s < 2; s++ {
f := g.F[s]
h = h*31 + uint32(f.X+7*f.Y+13*f.Gold+17*f.StunT+19*m0+23*a0)
}
h = h*31 + uint32(g.NCoins)
}
done := 0
if a.Done() {
done = 1
}
return strconv.Itoa(g.F[0].Gold) + "-" + strconv.Itoa(g.F[1].Gold) + ":" + strconv.Itoa(done) + ":" + strconv.FormatUint(uint64(h), 10)
}
func TestParityPlans(t *testing.T) {
out := ""
ok := []string{}
for _, s := range planCheckList() {
if _, err := ParsePlan(s); err != "" {
out += "[" + err + "] "
continue
}
ok = append(ok, s)
out += "ok "
}
n := len(ok)
for i := 0; i < 16; i++ {
out += planFingerprint(uint32(i*19+5), i%5, (i*2+1)%5, ok[i%n], ok[(i+3)%n], i) + " "
}
t.Logf("PLANS %s", out)
}
plan.gno
package brawl
import "strconv"
// Smart plans: a side's moves written as plain text, run tick by tick
// against the live match. Rooms use them so an agent can say "go get that
// coin" or "chase and hit when close" instead of guessing keystrokes.
//
// Steps are separated by ";" or new lines (at most MaxPlan characters, plain
// ASCII). Words are case-blind. Ticks are 1 to 300 (10 ticks = 1 s).
//
// run <dir> <ticks> move that way
// wait <ticks> stand still
// attack | block | special | dodge
// press the button for one tick, still moving the
// way you were going
// goto <x>,<y> [ticks] walk to the middle of square (x,y), 0-14, sliding
// round walls; ends on arrival (next to it, for a
// table) or after ticks (60)
// collect <ticks> head for the nearest gold, picking a new coin when
// that one is gone
// chase <ticks> run at the rival
// flee <ticks> run from the rival
// if near <squares>: <button>
// one tick: press the button only if the rival is
// that close (centre to centre, like 1.4 or 3);
// otherwise just keep moving
// auto <ticks> let the Normal house bot play for you
// guard on | guard off from here on, block on its own whenever the
// rival is within 1.5 squares and can swing (and you
// have gold and your block is ready), unless the
// step is already pressing a button. Takes no time.
//
// Directions: N, NE, E, SE, S, SW, W, NW (y grows toward S, so A's corner is
// NW and B's is SE), or a number 0-15 counting clockwise from E in steps of
// 22.5 degrees. Melee reaches 1.45 squares, the Hunter's beam 5.
//
// Everything is whole-number, so the chain and the browser run a plan the
// same. A tick costs a few comparisons; collect looks for gold ring by ring
// only when its coin is gone, and at most every 5 ticks while there is none.
const (
MaxPlan = 500
PlanTicks = 300 // longest step
GotoTicks = 60 // goto's default limit
// GuardReach is how close the rival must be for guard to block: a little
// past melee (1.45), so the block is up before the swing lands.
GuardReach = 1500
)
const (
stepRun = iota
stepWait
stepButton
stepGoto
stepCollect
stepChase
stepFlee
stepIfNear
stepAuto
stepGuard
)
type planStep struct {
kind int
n int // ticks
dir int // run
act int // button, if near
x, y int // goto
near int // if near, in board units
}
// Plan is a parsed plain-text plan for one side, run tick by tick.
type Plan struct {
steps []planStep
i int // current step
on bool // the current step has started
left int // its ticks left
dir int // the last move, kept by buttons
target int // collect: the coin it heads for, -1 for none
look int // collect: no looking again before this tick
stuck int
lastX int
lastY int
turn int // which way it slides round walls
hold int // ticks left of a slide
slide int
bot *Bot // auto
guard bool // guard on
}
var planDirs = map[string]int{"E": 0, "SE": 2, "S": 4, "SW": 6, "W": 8, "NW": 10, "N": 12, "NE": 14}
var planButtons = map[string]int{"attack": Attack, "block": Block, "special": Special, "dodge": Dodge}
// ParsePlan reads a plan; on a bad step it returns nil and a short error naming the step.
func ParsePlan(text string) (*Plan, string) {
if len(text) > MaxPlan {
return nil, "plan: at most " + strconv.Itoa(MaxPlan) + " characters"
}
for i := 0; i < len(text); i++ {
if text[i] >= 128 {
return nil, "plan: plain ASCII only"
}
}
p := &Plan{dir: Still, target: -1}
start, num := 0, 0
for i := 0; i <= len(text); i++ {
if i < len(text) && text[i] != ';' && text[i] != '\n' {
continue
}
step := text[start:i]
start = i + 1
f := planFields(step)
if len(f) == 0 {
continue
}
num++
st, err := parseStep(f)
if err != "" {
return nil, "step " + strconv.Itoa(num) + " \"" + planTrim(step) + "\": " + err
}
p.steps = append(p.steps, st)
}
return p, ""
}
func planSpace(c byte) bool {
return c == ' ' || c == '\t' || c == '\r' || c == ',' || c == '(' || c == ')'
}
// planFields splits a step into words on spaces, commas and brackets; a
// colon is a word of its own.
func planFields(s string) []string {
var f []string
w := -1
for i := 0; i <= len(s); i++ {
if i < len(s) && !planSpace(s[i]) && s[i] != ':' {
if w < 0 {
w = i
}
continue
}
if w >= 0 {
f = append(f, s[w:i])
w = -1
}
if i < len(s) && s[i] == ':' {
f = append(f, ":")
}
}
return f
}
func planTrim(s string) string {
a, b := 0, len(s)
for a < b && (s[a] == ' ' || s[a] == '\t' || s[a] == '\r') {
a++
}
for b > a && (s[b-1] == ' ' || s[b-1] == '\t' || s[b-1] == '\r') {
b--
}
return s[a:b]
}
// planNum reads 1 to 3 digits; -1 if it isn't one.
func planNum(s string) int {
if len(s) == 0 || len(s) > 3 {
return -1
}
v := 0
for i := 0; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return -1
}
v = v*10 + int(s[i]-'0')
}
return v
}
func planLower(s string) string {
b := []byte(s)
for i := range b {
if b[i] >= 'A' && b[i] <= 'Z' {
b[i] += 'a' - 'A'
}
}
return string(b)
}
func planUpper(s string) string {
b := []byte(s)
for i := range b {
if b[i] >= 'a' && b[i] <= 'z' {
b[i] -= 'a' - 'A'
}
}
return string(b)
}
func planTicks(s string) (int, string) {
n := planNum(s)
if n < 1 || n > PlanTicks {
return 0, "ticks must be 1 to " + strconv.Itoa(PlanTicks)
}
return n, ""
}
// planNear reads a distance in squares with at most one decimal, like 1.4.
func planNear(s string) int {
dot := -1
for i := 0; i < len(s); i++ {
if s[i] == '.' {
dot = i
}
}
whole, tenth := s, ""
if dot >= 0 {
whole, tenth = s[:dot], s[dot+1:]
if len(tenth) != 1 && len(tenth) != 2 {
return -1
}
}
w := planNum(whole)
if w < 0 || len(whole) > 2 {
return -1
}
d := w * U
if tenth != "" {
v := planNum(tenth)
if v < 0 {
return -1
}
if len(tenth) == 1 {
v *= 10
}
d += v * 10
}
if d < 100 || d > Size*U {
return -1
}
return d
}
func parseStep(f []string) (planStep, string) {
word := planLower(f[0])
var st planStep
var err string
if act, ok := planButtons[word]; ok {
if len(f) != 1 {
return st, "a button takes no number"
}
return planStep{kind: stepButton, n: 1, act: act}, ""
}
switch word {
case "run":
if len(f) != 3 {
return st, "use run <dir> <ticks>"
}
d, ok := planDirs[planUpper(f[1])]
if !ok {
d = planNum(f[1])
if d < 0 || d > 15 {
return st, "direction is N, NE, E, SE, S, SW, W, NW or 0-15"
}
}
st = planStep{kind: stepRun, dir: d}
st.n, err = planTicks(f[2])
case "wait", "collect", "chase", "flee", "auto":
if len(f) != 2 {
return st, "use " + word + " <ticks>"
}
st.kind = map[string]int{"wait": stepWait, "collect": stepCollect, "chase": stepChase, "flee": stepFlee, "auto": stepAuto}[word]
st.n, err = planTicks(f[1])
case "goto":
if len(f) != 3 && len(f) != 4 {
return st, "use goto <x>,<y> [ticks]"
}
x, y := planNum(f[1]), planNum(f[2])
if x < 0 || x >= Size || y < 0 || y >= Size {
return st, "squares are 0 to 14"
}
st = planStep{kind: stepGoto, x: x, y: y, n: GotoTicks}
if len(f) == 4 {
st.n, err = planTicks(f[3])
}
case "guard":
if len(f) != 2 || (planLower(f[1]) != "on" && planLower(f[1]) != "off") {
return st, "use guard on or guard off"
}
st = planStep{kind: stepGuard}
if planLower(f[1]) == "on" {
st.n = 1
}
case "if":
// if near <squares> [:] <button>
if len(f) == 5 && f[3] == ":" {
f = []string{f[0], f[1], f[2], f[4]}
}
if len(f) != 4 || planLower(f[1]) != "near" {
return st, "use if near <squares>: <button>"
}
d := planNear(f[2])
if d < 0 {
return st, "distance is 0.1 to 15 squares"
}
act, ok := planButtons[planLower(f[3])]
if !ok {
return st, "button is attack, block, special or dodge"
}
st = planStep{kind: stepIfNear, n: 1, near: d, act: act}
default:
return st, "unknown word \"" + f[0] + "\""
}
return st, err
}
// Done reports whether the plan has run out.
func (p *Plan) Done() bool { return p.i >= len(p.steps) }
// Next returns this tick's move and action for side s, reacting to the live game.
// Once the plan runs out it returns Still, None. Call it once per tick.
func (p *Plan) Next(g *Game, s int) (move, act int) {
me, o := &g.F[s], &g.F[1-s]
move, act = Still, None
for p.i < len(p.steps) {
st := &p.steps[p.i]
if !p.on {
p.on, p.left, p.target, p.look, p.hold, p.stuck = true, st.n, -1, 0, 0, 0
}
if st.kind == stepGuard {
p.guard = st.n == 1
p.i++
p.on = false
continue
}
if st.kind == stepGoto && p.arrived(g, me, st) {
p.i++
p.on = false
continue
}
switch st.kind {
case stepRun:
p.dir = st.dir
case stepWait:
p.dir = Still
case stepButton:
act = st.act
case stepIfNear:
if dx, dy := o.X-me.X, o.Y-me.Y; dx*dx+dy*dy <= st.near*st.near {
act = st.act
}
case stepGoto:
p.steer(st.x*U+U/2-me.X, st.y*U+U/2-me.Y)
case stepChase:
p.steer(o.X-me.X, o.Y-me.Y)
case stepFlee:
p.steer(me.X-o.X, me.Y-o.Y)
case stepCollect:
if (p.target < 0 || g.Coin[p.target] == 0) && g.T >= p.look {
p.target = g.ringCoin(me, Size-1)
if p.target < 0 {
p.look = g.T + 5
}
}
if p.target >= 0 && g.Coin[p.target] != 0 {
p.steer(p.target%Size*U+U/2-me.X, p.target/Size*U+U/2-me.Y)
} else {
p.dir = Still
}
case stepAuto:
if p.bot == nil {
p.bot = NewBot(Normal, g.Seed*31+uint32(s)+3)
}
p.dir, act = p.bot.Act(g, s)
}
move = p.dir
p.left--
if p.left <= 0 {
p.i++
p.on = false
}
break
}
if p.guard && act == None && me.Gold > 0 && g.T >= o.AtkCD && g.T >= me.BlockCD {
if dx, dy := o.X-me.X, o.Y-me.Y; dx*dx+dy*dy <= GuardReach*GuardReach {
act = Block
}
}
if move != Still && abs(me.X-p.lastX)+abs(me.Y-p.lastY) < 60 {
p.stuck++
} else {
p.stuck = 0
}
p.lastX, p.lastY = me.X, me.Y
return move, act
}
// arrived reports whether a goto is over: the fighter is on the square, or
// next to it if the square is a wall.
func (p *Plan) arrived(g *Game, me *Fighter, st *planStep) bool {
x, y := me.X/U, me.Y/U
if x == st.x && y == st.y {
return true
}
return g.Floor[st.y*Size+st.x] == Wall && abs(x-st.x) <= 1 && abs(y-st.y) <= 1
}
// steer heads along (dx, dy), sliding round a wall like the house bot: once
// it has been stuck for 3 ticks it turns a quarter for 4 ticks, and if that
// way is blocked too it tries the other side.
func (p *Plan) steer(dx, dy int) {
if p.hold > 0 {
if p.stuck <= 2 {
p.hold--
p.dir = p.slide
return
}
p.turn = 1 - p.turn
p.hold = 0
}
d := toward(dx, dy)
if p.stuck > 2 && d != Still {
if p.turn == 0 {
d = (d + 4) % 16
} else {
d = (d + 12) % 16
}
p.slide, p.hold, p.stuck = d, 3, 0
}
p.dir = d
}
plan_test.gno
package brawl
import (
"strings"
"testing"
)
func TestPlanRefused(t *testing.T) {
bad := map[string]string{
"run N": "use run <dir> <ticks>",
"run N 5; fly 3": `step 2 "fly 3": unknown word "fly"`,
"goto 15,3": "squares are 0 to 14",
"if near 2: jump": "button is attack, block, special or dodge",
"if near 1.456: block": "distance is 0.1 to 15 squares",
"guard": "use guard on or guard off",
"guard up": "use guard on or guard off",
"wait 301": "ticks must be 1 to 300",
"café 3": "plan: plain ASCII only",
strings.Repeat("wait 1;", 72): "plan: at most 500 characters",
}
for text, want := range bad {
p, err := ParsePlan(text)
if p != nil || !strings.Contains(err, want) {
t.Errorf("%q: got %v %q, want an error with %q", text, p != nil, err, want)
}
}
}
func TestPlanWords(t *testing.T) {
for _, text := range []string{
"", "run N 5; wait 3; attack; block; special; dodge", "goto 3,4", "goto (3, 4) 20", "collect 50",
"chase 10\nflee 10", "if near 1.4: attack", "IF NEAR 3 Special", "auto 300", "run 15 2;; ;",
} {
if _, err := ParsePlan(text); err != "" {
t.Errorf("%q: %s", text, err)
}
}
}
// The plain keystroke words play exactly like the inputs rooms.Compile makes.
func TestPlanKeystrokes(t *testing.T) {
p, _ := ParsePlan("run E 3; attack; wait 2; run 14 1; dodge")
g := New(1, Hunter, Hunter)
want := []int{0, None, 0, None, 0, None, 0, Attack, Still, None, Still, None, 14, None, 14, Dodge, Still, None}
for i := 0; i < len(want); i += 2 {
m, a := p.Next(g, 0)
if m != want[i] || a != want[i+1] {
t.Fatalf("tick %d: %d,%d want %d,%d", i/2, m, a, want[i], want[i+1])
}
g.Step(m, a, Still, None)
}
if !p.Done() {
t.Fatal("plan should be done")
}
}
// goto reaches the square, sliding round tables on the way, then ends. On
// the Tavern 2,12 is a table: standing next to it is enough.
func TestPlanGoto(t *testing.T) {
for seed := uint32(0); seed < 3; seed++ {
g := New(seed, Hunter, Hunter)
p, _ := ParsePlan("goto 12,12 200; goto 2,12 200; goto 7,1 200")
for i := 0; i < 600 && !p.Done(); i++ {
m, a := p.Next(g, 0)
g.Step(m, a, Still, None)
}
f := g.F[0]
if !p.Done() || f.X/U != 7 || f.Y/U != 1 {
t.Fatalf("%s: ended on %d,%d at tick %d", ArenaName(seed), f.X/U, f.Y/U, g.T)
}
t.Logf("%s: three gotos in %d ticks", ArenaName(seed), g.T)
}
}
func TestPlanCollectChase(t *testing.T) {
for seed := uint32(0); seed < 3; seed++ {
g := New(seed, Reader, Hunter)
p, _ := ParsePlan("collect 200")
for i := 0; i < 200; i++ {
m, a := p.Next(g, 0)
g.Step(m, a, Still, None)
}
if g.F[0].Gold < 8 {
t.Errorf("%s: collect got %d gold in 20 s", ArenaName(seed), g.F[0].Gold)
}
g = New(seed, Brawler, Hunter)
g.F[1].Gold = 10
p, _ = ParsePlan("chase 80; if near 1.4: attack")
hits := 0
for i := 0; i < 81; i++ {
m, a := p.Next(g, 0)
if a == Attack {
hits++
}
g.Step(m, a, Still, None)
}
if hits != 1 || g.F[1].Gold != 9 {
t.Errorf("%s: chase then hit: %d swings, rival left with %d", ArenaName(seed), hits, g.F[1].Gold)
}
}
}
func TestPlanFleeAuto(t *testing.T) {
g := New(4, Coward, Brawler)
g.F[0].X, g.F[0].Y, g.F[1].X, g.F[1].Y = 7500, 6500, 7500, 8000
p, _ := ParsePlan("flee 30; auto 150")
for i := 0; i < 30; i++ {
m, a := p.Next(g, 0)
g.Step(m, a, Still, None)
}
dx, dy := g.F[0].X-g.F[1].X, g.F[0].Y-g.F[1].Y
if dx*dx+dy*dy < 5000*5000 {
t.Errorf("flee only got %d away", isqrt(dx*dx+dy*dy))
}
for i := 0; i < 150; i++ {
m, a := p.Next(g, 0)
g.Step(m, a, Still, None)
}
if !p.Done() || g.F[0].Gold == 0 {
t.Errorf("auto: done %v, gold %d", p.Done(), g.F[0].Gold)
}
if m, a := p.Next(g, 0); m != Still || a != None {
t.Error("a finished plan stands still")
}
}
// For gas: a 240-tick room round driven by a smart plan on each side.
func TestGasPlanRound(t *testing.T) {
g := NewLength(5, Brawler, Reader, 240)
a, _ := ParsePlan("collect 60; chase 30; if near 1.4: attack; chase 10; if near 1.4: attack; goto 7,7 40; collect 100")
b, _ := ParsePlan("auto 240")
for !g.Over() {
m0, x0 := a.Next(g, 0)
m1, x1 := b.Next(g, 1)
g.Step(m0, x0, m1, x1)
}
t.Logf("round: %d-%d", g.F[0].Gold, g.F[1].Gold)
}
func TestPlanGuard(t *testing.T) {
g := New(7, Reader, Brawler)
me, o := &g.F[0], &g.F[1]
me.X, me.Y, o.X, o.Y = 5000, 5000, 5000+GuardReach-10, 5000
me.Gold = 3
p, _ := ParsePlan("guard on; wait 5; guard off; wait 5")
if _, act := p.Next(g, 0); act != Block {
t.Errorf("rival in reach: want Block, got %d", act)
}
o.X = 5000 + GuardReach + 10
if _, act := p.Next(g, 0); act != None {
t.Errorf("rival out of reach: want None, got %d", act)
}
o.X = 5000 + 1000
o.AtkCD = g.T + 5
if _, act := p.Next(g, 0); act != None {
t.Errorf("rival can't swing yet: want None, got %d", act)
}
o.AtkCD = 0
me.Gold = 0
if _, act := p.Next(g, 0); act != None {
t.Errorf("nothing to lose: want None, got %d", act)
}
me.Gold = 3
p.Next(g, 0) // the last tick of wait 5
if _, act := p.Next(g, 0); act != None {
t.Errorf("after guard off: want None, got %d", act)
}
}
profile.gno
package brawl
import (
"errors"
"strconv"
)
// Bot profiles: a bot written as a handful of whole-number traits instead of
// code, so a player's own bot fits in one short string on chain. The page
// learns the traits from how you play; NewProfileBot plays with them.
//
// The string is eleven letter-digit pairs in this order, for example
// "c1t3i1f6j8r6a7b2s5d4k0":
//
// c class it plays, 0..4 (Hunter, Brawler, Coward, Trickster, Reader)
// t ticks between plans, 3..9 (lower re-plans more often)
// i chance to stand still when it plans, 5% per step, 0..9
// f chance to chase a rival who carries gold, 11% per step, 0..9
// j chance to go for the jackpot when it is out, 11% per step, 0..9
// r how far it looks for gold, in squares, 1..8
// a chance to swing at a rival in reach, each tick, 11% per step, 0..9
// b chance to block a rival in reach, each tick, 11% per step, 0..9
// s chance to fire its special when it pays, 11% per step, 0..9
// d chance to dodge right after losing gold, 11% per step, 0..9
// k runs from a rival closer than this many squares while ahead, 0..5 (0 never)
//
// The house levels (Easy, Normal, Hard) are left as they are.
// ProfileLen is the length of an encoded profile.
const ProfileLen = 22
const profileKeys = "ctifjrabsdk"
var profileLo = [11]int{0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0}
var profileHi = [11]int{4, 9, 9, 9, 9, 8, 9, 9, 9, 9, 5}
type Profile struct {
Class int
Think int
Idle int
Chase int
Jackpot int
Reach int
Attack int
Block int
Special int
Dodge int
Keep int
}
func (p *Profile) field(i int) *int {
switch i {
case 0:
return &p.Class
case 1:
return &p.Think
case 2:
return &p.Idle
case 3:
return &p.Chase
case 4:
return &p.Jackpot
case 5:
return &p.Reach
case 6:
return &p.Attack
case 7:
return &p.Block
case 8:
return &p.Special
case 9:
return &p.Dodge
}
return &p.Keep
}
// ParseProfile reads an encoded profile, refusing anything out of range.
func ParseProfile(s string) (*Profile, error) {
if len(s) != ProfileLen {
return nil, errors.New("profile: 11 letter-digit pairs, like c1t3i1f6j8r6a7b2s5d4k0")
}
p := &Profile{}
for i := 0; i < 11; i++ {
if s[2*i] != profileKeys[i] {
return nil, errors.New("profile: expected " + profileKeys[i:i+1] + " at " + strconv.Itoa(2*i+1))
}
v := int(s[2*i+1]) - '0'
if v < profileLo[i] || v > profileHi[i] {
return nil, errors.New("profile: " + profileKeys[i:i+1] + " is " + strconv.Itoa(profileLo[i]) + " to " + strconv.Itoa(profileHi[i]))
}
*p.field(i) = v
}
return p, nil
}
// MustProfile is ParseProfile that panics on a bad profile.
func MustProfile(s string) *Profile {
p, err := ParseProfile(s)
if err != nil {
panic(err.Error())
}
return p
}
// String writes the profile back in its encoded form.
func (p *Profile) String() string {
b := make([]byte, ProfileLen)
for i := 0; i < 11; i++ {
b[2*i], b[2*i+1] = profileKeys[i], byte('0'+*p.field(i))
}
return string(b)
}
// A ProfileBot plays one side of a match with a profile's traits. It moves
// like the house bot (plan, head for gold or the rival, slide round walls)
// and rolls its own dice for every choice, so a replay is exact.
type ProfileBot struct {
P Profile
rng uint32
wait int
dir int
target int
rescan int
stuck int
lastX int
lastY int
turn int
gold int
}
func NewProfileBot(p *Profile, seed uint32) *ProfileBot {
return &ProfileBot{P: *p, rng: seed*2654435761 + 7, dir: Still, target: -1}
}
func (b *ProfileBot) rand(n int) int {
b.rng = b.rng*1103515245 + 12345
return int(b.rng>>8) % n
}
// Act decides the bot's move and button for this tick, as side s.
func (b *ProfileBot) Act(g *Game, s int) (int, int) {
p := &b.P
me, o := &g.F[s], &g.F[1-s]
ex, ey := o.X-me.X, o.Y-me.Y
od := ex*ex + ey*ey
think := b.wait == 0
if !think {
b.wait--
} else {
b.wait = p.Think - 1
if b.rand(1000) < p.Idle*50 {
b.dir = Still
} else {
kr := p.Keep * U
if me.Gold > o.Gold && od < kr*kr {
b.dir = toward(-ex, -ey) // ahead: keep the rival away
} else {
tx, ty := o.X, o.Y
if !(o.Gold > 0 && od < 3000*3000 && b.rand(1000) < p.Chase*111) {
if g.Coin[Mid*Size+Mid] == 3 && b.rand(1000) < p.Jackpot*111 {
b.target = Mid*Size + Mid
} else if b.rescan <= 0 || b.target >= 0 && (g.Coin[b.target] == 0 || b.target == Mid*Size+Mid) {
// look again; after an empty look, wait 3 plans (it is the
// costly part of a replay when the floor is bare)
b.target = g.ringCoin(me, p.Reach)
b.rescan = 10
if b.target < 0 {
b.rescan = 3
}
}
b.rescan--
if b.target >= 0 {
tx, ty = b.target%Size*U+U/2, b.target/Size*U+U/2
}
}
b.dir = toward(tx-me.X, ty-me.Y)
}
if b.stuck > 2 {
if b.turn == 0 {
b.dir = (b.dir + 4) % 16
} else {
b.dir = (b.dir + 12) % 16
}
b.turn = 1 - b.turn
b.stuck = 0
b.wait = 3
}
}
}
if b.dir != Still && abs(me.X-b.lastX)+abs(me.Y-b.lastY) < 60 {
b.stuck++
} else {
b.stuck = 0
}
b.lastX, b.lastY = me.X, me.Y
lost := me.Gold < b.gold
b.gold = me.Gold
t := g.T
near := od <= Melee*Melee
act := None
if lost && t >= me.DodgeCD && b.rand(1000) < p.Dodge*111 {
act = Dodge
} else if think && t >= me.CD && specialPays(g, me, o, od, b.dir, b.target) && b.rand(1000) < p.Special*111 {
act = Special
} else if near && o.Gold > 0 && t >= me.AtkCD && b.rand(1000) < p.Attack*111 {
act = Attack
} else if near && t >= me.BlockCD && b.rand(1000) < p.Block*111 {
act = Block
}
return b.dir, act
}
// VersusProfile replays a run (side A's inputs) against a profile bot on
// side B, which plays the profile's class.
func VersusProfile(seed uint32, classA int, profile, inA string) (int, int) {
if classA < Hunter || classA > Reader {
panic("brawl: no such class")
}
if len(inA) > Ticks {
panic("brawl: inputs longer than a match")
}
p := MustProfile(profile)
g := New(seed, classA, p.Class)
b := NewProfileBot(p, seed)
for t := 0; t < Ticks; t++ {
m0, a0 := in(inA, t)
m1, a1 := b.Act(g, 1)
g.Step(m0, a0, m1, a1)
}
return g.F[0].Gold, g.F[1].Gold
}
profile_test.gno
package brawl
import "testing"
func TestProfileRoundTrip(t *testing.T) {
for _, s := range []string{"c1t3i1f6j8r6a7b2s5d4k0", "c0t3i0f9j9r8a9b9s9d9k5", "c4t9i9f0j0r1a0b0s0d0k0"} {
if got := MustProfile(s).String(); got != s {
t.Errorf("%s came back as %s", s, got)
}
}
}
func TestProfileRefused(t *testing.T) {
for _, s := range []string{"", "c5t3i1f6j8r6a7b2s5d4k0", "c1t1i1f6j8r6a7b2s5d4k0", "c1t2i1f6j8r6a7b2s5d4k0", "c1t3i1f6j8r9a7b2s5d4k0", "c1t3i1f6j8r6a7b2s5d4k6", "t3c1i1f6j8r6a7b2s5d4k0"} {
if _, err := ParseProfile(s); err == nil {
t.Errorf("%q should be refused", s)
}
}
}
// the busiest profile allowed: re-plans every 2 ticks, looks 8 squares out
func TestGasVersusProfileBusy(t *testing.T) {
VersusProfile(3, Hunter, "c0t3i0f9j9r8a9b9s9d9k5", gen(77))
}
func TestGasVersusProfileCollector(t *testing.T) {
VersusProfile(3, Hunter, "c4t3i0f0j9r8a0b0s9d0k0", gen(77))
}
func TestGasVersusProfileTypical(t *testing.T) {
VersusProfile(3, Hunter, "c1t3i1f6j8r6a7b2s5d4k0", gen(77))
}
// a profile bot saved and restored every 37 ticks plays the same match
func TestProfileSnapshot(t *testing.T) {
p := MustProfile("c2t4i2f1j5r4a3b6s9d8k3")
inA := gen(91)
a, b := VersusProfile(12, Brawler, p.String(), inA)
g := New(12, Brawler, p.Class)
var bot Actor = NewProfileBot(p, 12)
for i := 0; i < Ticks; i++ {
if i%37 == 0 {
bot = RestoreActor(bot.Snapshot())
g = Restore(g.Snapshot())
}
m0, a0 := in(inA, i)
m1, a1 := bot.Act(g, 1)
g.Step(m0, a0, m1, a1)
}
if g.F[0].Gold != a || g.F[1].Gold != b {
t.Errorf("restored match %d-%d, straight match %d-%d", g.F[0].Gold, g.F[1].Gold, a, b)
}
}
recipe.gno
package brawl
import (
"errors"
"strconv"
)
// Move recipes: a special move written as data, so anyone can design one and
// both the chain and the browser run it exactly. A fighter with a recipe uses
// it instead of its class special; everything else about the match is the same.
//
// A recipe is written as one short string:
//
// name/cooldown/effects
//
// Blink Thief/84/D82S11 dash 4 squares to the nearest gold, then steal 1 in melee
//
// The name is 1 to 16 letters, digits, spaces, '-' or '\'' (no space at either
// end). The cooldown is in ticks (10 a second), MinCD to MaxCD, written without
// leading zeros. Then come 1 to 3 effects, three characters each: a letter and
// two digits. They fire in order, the moment the move is used:
//
// Dxm dash x half-squares (1-8) in mode m: 0 the way you steer (away from
// the rival if you stand still), 1 at the rival, 2 to the nearest gold,
// 3 away from the rival
// Snr knock n gold (1-3) loose from the rival within range r (onto the
// floor round them, like any hit); a block saves one
// Pnr pull up to n coins (1-3) lying within r squares (1-5) into your purse
// H00 put up a shield, like the power-up: it saves one gold from the next steal
// Ttr stun the rival t ticks (1-9) within range r; a block stops it
// It0 turn untouchable for t ticks (1-9)
// Kpr knock the rival back with power p (1-9) within range r
//
// Ranges r are 1-5: 1.45, 2.4, 3.3, 4.2 or 5 squares. Beyond melee (r > 1) a
// wall in the way stops the effect, like the Hunter's beam. An untouchable
// rival shrugs off steal, stun and knockback.
//
// Budget: the cooldown must be at least the recipe's Cost, in ticks:
//
// D x(x+1)/2 (D82: 36)
// S n(n+1)/2 * (28+4r) (S11: 32, S15: 48, S21: 96)
// P n * (4r+4) (P24: 40, like the Reader's magnet)
// H 80
// T t * (2r+4)
// I 5t
// K (p(r+1)+2)/3
//
// plus half the cost of every effect but the dearest, and never under MinCD.
// The numbers come from sim/browser/recipes.js: scripted players fight the
// Hard bot with each built-in special and with hundreds of recipes at their
// cheapest cooldown, and the best recipes only match the best built-ins.
// Each letter may appear once.
const (
MinCD = 20
MaxCD = 200
MaxEffects = 3
MaxName = 16
)
// Effect letters.
const (
FxDash = 'D'
FxSteal = 'S'
FxPull = 'P'
FxShield = 'H'
FxStun = 'T'
FxGuard = 'I'
FxKnock = 'K'
)
// Dash modes.
const (
DashSteer = iota
DashRival
DashCoin
DashAway
)
// reach is the distance for ranges 1..5.
var reach = [6]int{0, Melee, 2400, 3300, 4200, Long}
type Effect struct {
Kind byte
A, B int
}
type Recipe struct {
Name string
CD int
Fx []Effect
}
// Cost is what one effect adds to the cooldown a recipe needs, in ticks.
func (e Effect) Cost() int {
a, b := e.A, e.B
switch e.Kind {
case FxDash:
return a * (a + 1) / 2
case FxSteal:
return a * (a + 1) / 2 * (28 + 4*b)
case FxPull:
return a * (4*b + 4)
case FxShield:
return 80
case FxStun:
return a * (2*b + 4)
case FxGuard:
return 5 * a
case FxKnock:
return (a*(b+1) + 2) / 3
}
return 0
}
// Cost is the shortest cooldown the recipe's effects allow: the sum of the
// effects' costs, plus half of all but the dearest one, since moves that do
// several things at once are worth more than their parts. Never below MinCD.
func (r *Recipe) Cost() int {
c, top := 0, 0
for _, e := range r.Fx {
v := e.Cost()
c += v
if v > top {
top = v
}
}
c += (c - top) / 2
if c < MinCD {
c = MinCD
}
return c
}
// limits holds the allowed range of each effect's two digits.
func limits(k byte) (int, int, int, int, bool) {
switch k {
case FxDash:
return 1, 8, 0, 3, true
case FxSteal, FxPull, FxKnock:
hi := 3
if k == FxKnock {
hi = 9
}
return 1, hi, 1, 5, true
case FxShield:
return 0, 0, 0, 0, true
case FxStun:
return 1, 9, 1, 5, true
case FxGuard:
return 1, 9, 0, 0, true
}
return 0, 0, 0, 0, false
}
func nameChar(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ' ' || c == '-' || c == '\''
}
// ParseRecipe reads and checks a recipe string. A valid recipe always writes
// back to the same string, so each move has exactly one spelling.
func ParseRecipe(s string) (*Recipe, error) {
a, b := -1, -1
for i := 0; i < len(s); i++ {
if s[i] == '/' {
if a < 0 {
a = i
} else if b < 0 {
b = i
} else {
return nil, errors.New("recipe: name/cooldown/effects")
}
}
}
if b < 0 {
return nil, errors.New("recipe: name/cooldown/effects")
}
name, cds, fx := s[:a], s[a+1:b], s[b+1:]
if len(name) == 0 || len(name) > MaxName || name[0] == ' ' || name[len(name)-1] == ' ' {
return nil, errors.New("recipe: name is 1 to 16 characters, no space at either end")
}
for i := 0; i < len(name); i++ {
if !nameChar(name[i]) {
return nil, errors.New("recipe: name uses letters, digits, spaces, - and ' only")
}
}
if len(cds) == 0 || len(cds) > 3 || cds[0] == '0' {
return nil, errors.New("recipe: bad cooldown")
}
cd := 0
for i := 0; i < len(cds); i++ {
if cds[i] < '0' || cds[i] > '9' {
return nil, errors.New("recipe: bad cooldown")
}
cd = cd*10 + int(cds[i]-'0')
}
if cd < MinCD || cd > MaxCD {
return nil, errors.New("recipe: cooldown is " + strconv.Itoa(MinCD) + " to " + strconv.Itoa(MaxCD) + " ticks")
}
if len(fx) == 0 || len(fx)%3 != 0 || len(fx) > 3*MaxEffects {
return nil, errors.New("recipe: 1 to 3 effects of 3 characters")
}
r := &Recipe{Name: name, CD: cd}
for i := 0; i < len(fx); i += 3 {
k, x, y := fx[i], int(fx[i+1])-'0', int(fx[i+2])-'0'
alo, ahi, blo, bhi, ok := limits(k)
if !ok {
return nil, errors.New("recipe: unknown effect " + fx[i:i+1])
}
if x < alo || x > ahi || y < blo || y > bhi {
return nil, errors.New("recipe: effect " + fx[i:i+3] + " out of range")
}
for _, e := range r.Fx {
if e.Kind == k {
return nil, errors.New("recipe: effect " + fx[i:i+1] + " twice")
}
}
r.Fx = append(r.Fx, Effect{Kind: k, A: x, B: y})
}
if c := r.Cost(); cd < c {
return nil, errors.New("recipe: these effects need a cooldown of at least " + strconv.Itoa(c))
}
return r, nil
}
// MustRecipe is ParseRecipe that panics on a bad recipe. "" gives nil: the
// class's own special.
func MustRecipe(s string) *Recipe {
if s == "" {
return nil
}
r, err := ParseRecipe(s)
if err != nil {
panic(err.Error())
}
return r
}
// String writes the recipe back in its one spelling.
func (r *Recipe) String() string {
b := []byte(r.Name + "/" + strconv.Itoa(r.CD) + "/")
for _, e := range r.Fx {
b = append(b, e.Kind, byte('0'+e.A), byte('0'+e.B))
}
return string(b)
}
// Equip gives side s a recipe in place of its class special; nil takes it away.
func (g *Game) Equip(s int, r *Recipe) { g.Move[s] = r }
// hits reports whether a rival-targeting effect with range r lands.
func (g *Game) hits(me, o *Fighter, r, dd int, oSafe bool) bool {
d := reach[r]
return !oSafe && dd <= d*d && (r == 1 || g.clear(me, o))
}
// recipe runs side s's recipe; act has already paid the cooldown.
func (g *Game) recipe(s int, rec *Recipe, mx, my, dd int, oBlocks, oSafe bool) {
t := g.T
me, o := &g.F[s], &g.F[1-s]
for _, e := range rec.Fx {
switch e.Kind {
case FxDash:
dx, dy := me.X-o.X, me.Y-o.Y // away
switch e.B {
case DashSteer:
if mx != 0 || my != 0 {
dx, dy = mx, my
}
case DashRival:
dx, dy = -dx, -dy
case DashCoin:
if c := g.nearestCoin(me, Size); c >= 0 {
dx, dy = c%Size*U+U/2-me.X, c/Size*U+U/2-me.Y
}
}
dash(me, dx, dy, e.A*500, (e.A+2)/3, t)
case FxSteal:
if g.hits(me, o, e.B, dd, oSafe) {
n := e.A
if oBlocks {
n--
}
g.hit(s, n)
}
case FxPull:
for k := 0; k < e.A; k++ {
c := g.nearestCoin(me, e.B)
if c < 0 {
break
}
v := int(g.Coin[c])
g.Coin[c] = 0
g.NCoins--
g.collect(me, v)
}
case FxShield:
me.Shield = true
case FxStun:
if !oBlocks && g.hits(me, o, e.B, dd, oSafe) {
o.StunT = imax(o.StunT, t+e.A)
}
case FxGuard:
me.InvT = imax(me.InvT, t+e.A)
case FxKnock:
if g.hits(me, o, e.B, dd, oSafe) {
knock(o, me, e.A)
}
}
}
}
// PlayMoves is Play with a recipe for each side ("" for the class special).
func PlayMoves(seed uint32, classA, classB int, inA, inB, moveA, moveB string) (int, int) {
return play(seed, classA, classB, inA, inB, false, MustRecipe(moveA), MustRecipe(moveB))
}
// DuelMoves is Duel with a recipe for each side ("" for the class special).
func DuelMoves(seed uint32, classA, classB int, inA, inB, moveA, moveB string) (int, int) {
return play(seed, classA, classB, inA, inB, true, MustRecipe(moveA), MustRecipe(moveB))
}
// VersusMove is Versus with a recipe for side A ("" for the class special).
// The house bot keeps its class special.
func VersusMove(seed uint32, classA, level int, inA, moveA string) (int, int) {
if level < Easy || level > Hard {
panic("brawl: no such bot level")
}
if len(inA) > Ticks {
panic("brawl: inputs longer than a match")
}
g := New(seed, classA, BotClass[level][seed%3])
g.Move[0] = MustRecipe(moveA)
b := NewBot(level, seed)
for t := 0; t < Ticks; t++ {
m0, a0 := in(inA, t)
m1, a1 := b.Act(g, 1)
g.Step(m0, a0, m1, a1)
}
return g.F[0].Gold, g.F[1].Gold
}
var dashModes = [4]string{"the way you steer", "at the rival", "to the nearest gold", "away from the rival"}
// squares writes a distance in squares: 1450 is "1.45", 2400 is "2.4".
func squares(d int) string {
s, f := strconv.Itoa(d/U), d%U
switch {
case f == 0:
return s
case f%100 == 0:
return s + "." + strconv.Itoa(f/100)
}
return s + "." + strconv.Itoa(f/10)
}
// Describe says what one effect does, in words.
func (e Effect) Describe() string {
a, b := strconv.Itoa(e.A), e.B
switch e.Kind {
case FxDash:
return "dash " + squares(e.A*500) + " squares " + dashModes[b]
case FxSteal:
return "steal " + a + " gold within " + squares(reach[b]) + " squares"
case FxPull:
if e.A == 1 {
return "pull the nearest coin within " + strconv.Itoa(b) + " squares"
}
return "pull up to " + a + " coins within " + strconv.Itoa(b) + " squares"
case FxShield:
return "raise a shield"
case FxStun:
return "stun the rival " + a + " ticks within " + squares(reach[b]) + " squares"
case FxGuard:
return "untouchable for " + a + " ticks"
case FxKnock:
return "knock the rival back (power " + a + ") within " + squares(reach[b]) + " squares"
}
return "?"
}
// Describe says what the recipe does, in words.
func (r *Recipe) Describe() string {
s := ""
for i, e := range r.Fx {
if i > 0 {
s += ", then "
}
s += e.Describe()
}
return s
}
recipe_test.gno
package brawl
import "testing"
func TestRecipeRoundTrip(t *testing.T) {
for _, s := range []string{"Blink Thief/84/D82S11", "O'Hare/150/S22P13T21", "Pick/20/P11", "Z-9/200/H00I90K11"} {
r, err := ParseRecipe(s)
if err != nil {
t.Fatalf("%s: %s", s, err.Error())
}
if r.String() != s {
t.Fatalf("%s wrote back as %s", s, r.String())
}
}
}
func TestRecipeRefused(t *testing.T) {
for _, s := range []string{"", "A/20/", "A/020/P11", "A/19/P11", "A/201/H00", " A/80/H00", "A/80/H01",
"A/32/S11S11", "A/32/Q11", "A/31/S11", "A/99/S11H00I90K11", "A|B/80/H00", "A/200/S32", "A/20/h00"} {
if _, err := ParseRecipe(s); err == nil {
t.Fatalf("%q should be refused", s)
}
}
}
// Recipes built like the built-in specials must cost at least as much as the
// class's own cooldown, so a copy is never a cheaper version of the original.
// (The Trickster's feint has no recipe effect, so it has no copy.)
func TestCopiesCostMore(t *testing.T) {
copies := []struct {
class int
fx string
}{
{Hunter, "S15K25T55"},
{Brawler, "S21K91T41"},
{Coward, "D82I70H00"},
{Reader, "P24"},
}
for _, c := range copies {
r, err := ParseRecipe("X/200/" + c.fx)
if err != nil {
t.Fatal(err.Error())
}
if r.Cost() < SpecialCD[c.class] {
t.Fatalf("%s costs %d, under the class's %d", c.fx, r.Cost(), SpecialCD[c.class])
}
}
}
// With no recipe the variants play exactly like Play, Duel and Versus.
func TestNoRecipeSame(t *testing.T) {
a, b := noisy(3), noisy(4)
x1, y1 := Play(9, Hunter, Reader, a, b)
x2, y2 := PlayMoves(9, Hunter, Reader, a, b, "", "")
x3, y3 := Duel(9, Hunter, Reader, a, b)
x4, y4 := DuelMoves(9, Hunter, Reader, a, b, "", "")
x5, y5 := Versus(9, Hunter, Hard, a)
x6, y6 := VersusMove(9, Hunter, Hard, a, "")
if x1 != x2 || y1 != y2 || x3 != x4 || y3 != y4 || x5 != x6 || y5 != y6 {
t.Fatal("a variant with no recipe plays differently")
}
}
// A recipe replaces the class special and sets its own cooldown.
func TestRecipeUsed(t *testing.T) {
g := New(5, Hunter, Brawler)
g.Equip(0, MustRecipe("Magnet/40/P24"))
g.Step(Still, Special, Still, None)
if g.F[0].CD != 40 {
t.Fatalf("cooldown %d, want 40", g.F[0].CD)
}
}
func TestDescribe(t *testing.T) {
got := MustRecipe("Blink Thief/84/D82S11").Describe()
want := "dash 4 squares to the nearest gold, then steal 1 gold within 1.45 squares"
if got != want {
t.Fatalf("%q", got)
}
}
// For gas: one ranked replay against the Hard bot, with and without a recipe.
// Run with gno test -print-runtime-metrics -run Gas.
func TestGasVersus(t *testing.T) { Versus(3, Hunter, Hard, gen(77)) }
func TestGasVersusMove(t *testing.T) { VersusMove(3, Hunter, Hard, gen(77), "Sniper/54/S15K25") }
func TestGasParse(t *testing.T) { MustRecipe("O'Hare/150/S22P13T21") }
snapshot.gno
package brawl
import (
"strconv"
"strings"
)
// Snapshot packs everything that changes during a match into a short string,
// so a realm can store a live match cheaply and carry on later with Restore.
// The floor isn't stored: it comes back from the seed.
func (g *Game) Snapshot() string {
n := []int{int(g.Seed), g.End, g.T, g.NCoins, g.NPower, g.nextCoin, g.nextPower, g.powerKind, b2i(g.jackpot), b2i(g.rushOn), int(g.rng)}
for s := 0; s < 2; s++ {
f := &g.F[s]
n = append(n, f.Class, f.X, f.Y, f.VX, f.VY, f.Gold, b2i(f.Shield), b2i(f.Double), f.CD, f.AtkCD, f.BlockCD, f.BlockT,
f.FeintT, f.InvT, f.DashT, f.DashX, f.DashY, f.StunT, f.TrapT, f.BoostT, f.PadT, f.SwingT, f.DodgeCD, f.Face, f.Cell, f.Combo, f.ComboT)
}
// coins and power-ups as square*4 + value pairs
for c := 0; c < Cells; c++ {
if g.Coin[c] != 0 {
n = append(n, c*4+int(g.Coin[c]))
}
}
n = append(n, -1)
for c := 0; c < Cells; c++ {
if g.Power[c] != 0 {
n = append(n, c*4+int(g.Power[c]))
}
}
return joinInts(n)
}
// Restore rebuilds a match from a Snapshot.
func Restore(snap string) *Game {
n := splitInts(snap)
g := New(uint32(n[0]), n[11], n[11+27])
g.End, g.T, g.NCoins, g.NPower, g.nextCoin, g.nextPower, g.powerKind = n[1], n[2], n[3], n[4], n[5], n[6], n[7]
g.jackpot, g.rushOn, g.rng = n[8] == 1, n[9] == 1, uint32(n[10])
i := 11
for s := 0; s < 2; s++ {
f := &g.F[s]
f.Class, f.X, f.Y, f.VX, f.VY, f.Gold = n[i], n[i+1], n[i+2], n[i+3], n[i+4], n[i+5]
f.Shield, f.Double = n[i+6] == 1, n[i+7] == 1
f.CD, f.AtkCD, f.BlockCD, f.BlockT, f.FeintT, f.InvT = n[i+8], n[i+9], n[i+10], n[i+11], n[i+12], n[i+13]
f.DashT, f.DashX, f.DashY, f.StunT, f.TrapT, f.BoostT = n[i+14], n[i+15], n[i+16], n[i+17], n[i+18], n[i+19]
f.PadT, f.SwingT, f.DodgeCD, f.Face, f.Cell, f.Combo, f.ComboT = n[i+20], n[i+21], n[i+22], n[i+23], n[i+24], n[i+25], n[i+26]
i += 27
}
g.Coin = [Cells]byte{}
g.Power = [Cells]byte{}
for ; n[i] != -1; i++ {
g.Coin[n[i]/4] = byte(n[i] % 4)
}
for i++; i < len(n); i++ {
g.Power[n[i]/4] = byte(n[i] % 4)
}
return g
}
// Snapshot packs a bot's memory the same way.
func (b *Bot) Snapshot() string {
return joinInts([]int{b.Level, int(b.rng), b.wait, b.dir, b.target, b.rescan, b.stuck, b.lastX, b.lastY, b.turn})
}
// RestoreBot rebuilds a bot from its Snapshot.
func RestoreBot(snap string) *Bot {
n := splitInts(snap)
return &Bot{Level: n[0], rng: uint32(n[1]), wait: n[2], dir: n[3], target: n[4], rescan: n[5], stuck: n[6], lastX: n[7], lastY: n[8], turn: n[9]}
}
func b2i(v bool) int {
if v {
return 1
}
return 0
}
func joinInts(n []int) string {
parts := make([]string, len(n))
for i, v := range n {
parts[i] = strconv.Itoa(v)
}
return strings.Join(parts, ",")
}
func splitInts(s string) []int {
parts := strings.Split(s, ",")
n := make([]int, len(parts))
for i, p := range parts {
v, err := strconv.Atoi(p)
if err != nil {
panic("brawl: bad snapshot")
}
n[i] = v
}
return n
}
// An Actor is a bot a realm can keep between rounds: a house Bot or a
// ProfileBot.
type Actor interface {
Act(g *Game, s int) (int, int)
Snapshot() string
}
// Snapshot packs a profile bot's memory: its profile, then its counters.
func (b *ProfileBot) Snapshot() string {
return b.P.String() + "," + joinInts([]int{int(b.rng), b.wait, b.dir, b.target, b.rescan, b.stuck, b.lastX, b.lastY, b.turn, b.gold})
}
// RestoreProfileBot rebuilds a profile bot from its Snapshot.
func RestoreProfileBot(snap string) *ProfileBot {
if len(snap) < ProfileLen+1 || snap[ProfileLen] != ',' {
panic("brawl: bad snapshot")
}
p := MustProfile(snap[:ProfileLen])
n := splitInts(snap[ProfileLen+1:])
if len(n) != 10 {
panic("brawl: bad snapshot")
}
return &ProfileBot{P: *p, rng: uint32(n[0]), wait: n[1], dir: n[2], target: n[3], rescan: n[4], stuck: n[5], lastX: n[6], lastY: n[7], turn: n[8], gold: n[9]}
}
// RestoreActor rebuilds either kind of bot from its Snapshot.
func RestoreActor(snap string) Actor {
if len(snap) > 0 && snap[0] == 'c' {
return RestoreProfileBot(snap)
}
return RestoreBot(snap)
}
snapshot_test.gno
package brawl
import "testing"
// A match stopped, packed and restored part-way gives the same result as one
// played straight through, for every arena and with bots on both sides.
func TestSnapshot(t *testing.T) {
for seed := uint32(3); seed < 6; seed++ {
straight := NewLength(seed, Reader, Brawler, 900)
a1, b1 := NewBot(Hard, seed), NewBot(Normal, seed+1)
for !straight.Over() {
m0, x0 := a1.Act(straight, 0)
m1, x1 := b1.Act(straight, 1)
straight.Step(m0, x0, m1, x1)
}
g := NewLength(seed, Reader, Brawler, 900)
a2, b2 := NewBot(Hard, seed), NewBot(Normal, seed+1)
for !g.Over() {
if g.T%137 == 0 {
g = Restore(g.Snapshot())
a2, b2 = RestoreBot(a2.Snapshot()), RestoreBot(b2.Snapshot())
}
m0, x0 := a2.Act(g, 0)
m1, x1 := b2.Act(g, 1)
g.Step(m0, x0, m1, x1)
}
if g.F[0].Gold != straight.F[0].Gold || g.F[1].Gold != straight.F[1].Gold || g.F[0].X != straight.F[0].X {
t.Fatalf("seed %d: restored %d-%d, straight %d-%d", seed, g.F[0].Gold, g.F[1].Gold, straight.F[0].Gold, straight.F[1].Gold)
}
t.Logf("seed %d: %d-%d, snapshot %d bytes", seed, g.F[0].Gold, g.F[1].Gold, len(g.Snapshot()))
}
}