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
}
var botLevels = [3]botLevel{
{think: 6, idle: 300, fight: 0, reach: 4},
{think: 3, idle: 80, fight: 600, reach: 6},
{think: 2, idle: 0, fight: 200, reach: 8},
}
// 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
}
// 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
chase := o.Gold > 0 && od < 2500*2500 && (o.Gold >= me.Gold || od < 1600*1600) && b.rand(1000) < lv.fight
if !chase {
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
}
}
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
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{42, 80, 34, 70, 38}
// 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
}
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 {
m := Cells - 1 - c
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
}
func (g *Game) spawnPair(power bool, val int) {
for i := 0; i < 40; i++ {
if g.spawnAt(g.rand()*Cells>>24, power, val) {
return
}
}
}
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
}
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 {
g.steal(1-s, 1)
me.StunT = t + 5
me.AtkCD = t + 9
} else {
g.steal(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.steal(s, 1)
knock(o, me, 2)
}
case Brawler:
if dd <= (Melee+150)*(Melee+150) && !oSafe {
n := 2
if oBlocks {
n = 1
}
g.steal(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
case Trickster:
me.FeintT = t + FeintT
if dd <= Melee*Melee && t >= o.SwingT && !oSafe {
g.steal(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)
}
}
}
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" gno = "0.9" [addpkg] creator = "g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28" height = 1523187 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)
}
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 steal n gold (1-3) from the rival within range r; 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.steal(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, "S15K25"},
{Brawler, "S21K91T41"},
{Coward, "D82I70"},
{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)
}
// 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+25])
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 = n[i+20], n[i+21], n[i+22], n[i+23], n[i+24]
i += 25
}
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()))
}
}