package rooms
import (
"strconv"
"strings"
rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl"
)
// Plain-text plans. Agents can write a round's plan in words and turn it
// into input characters with Compile (a free read, vm/qeval).
//
// Steps are separated by ";" or new lines:
//
// run
move that way for that many ticks (10 ticks = 1 s)
// wait stand still
// attack | block | special | dodge
// press the button on the next tick, still moving the
// way you were going
//
// 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.
var dirNames = map[string]int{"E": 0, "SE": 2, "S": 4, "SW": 6, "W": 8, "NW": 10, "N": 12, "NE": 14}
var buttons = map[string]int{"attack": rules.Attack, "block": rules.Block, "special": rules.Special, "dodge": rules.Dodge}
// Compile turns a plain-text plan into input characters (at most max ticks;
// extra steps are cut). It panics with the bad step if it can't read one.
func Compile(text string, max int) string {
var out []byte
dir := rules.Still
text = strings.ReplaceAll(text, "\n", ";")
for _, step := range strings.Split(text, ";") {
f := strings.Fields(strings.TrimSpace(step))
if len(f) == 0 {
continue
}
word := strings.ToLower(f[0])
if act, ok := buttons[word]; ok {
if len(f) != 1 {
panic("plan step " + strconv.Quote(step) + ": a button takes no number")
}
out = append(out, rules.Encode(dir, act))
continue
}
switch word {
case "run":
if len(f) != 3 {
panic("plan step " + strconv.Quote(step) + ": use run ")
}
d, ok := dirNames[strings.ToUpper(f[1])]
if !ok {
n, err := strconv.Atoi(f[1])
if err != nil || n < 0 || n > 15 {
panic("plan step " + strconv.Quote(step) + ": direction is N, NE, E, SE, S, SW, W, NW or 0-15")
}
d = n
}
dir = d
out = appendTicks(out, dir, f[2], step)
case "wait":
if len(f) != 2 {
panic("plan step " + strconv.Quote(step) + ": use wait ")
}
dir = rules.Still
out = appendTicks(out, dir, f[1], step)
default:
panic("plan step " + strconv.Quote(step) + ": unknown word " + strconv.Quote(f[0]))
}
if len(out) >= max {
break
}
}
if len(out) > max {
out = out[:max]
}
return string(out)
}
func appendTicks(out []byte, dir int, n, step string) []byte {
k, err := strconv.Atoi(n)
if err != nil || k < 1 || k > 300 {
panic("plan step " + strconv.Quote(step) + ": ticks must be 1 to 300")
}
c := rules.Encode(dir, rules.None)
for i := 0; i < k; i++ {
out = append(out, c)
}
return out
}