Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/rooms"
gno = "0.9"

[addpkg]
  creator = "g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28"
  height = 1523202
  max_deposit = "50000000ugnot"

plan.gno

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 <dir> <ticks>   move that way for that many ticks (10 ticks = 1 s)
//	wait <ticks>        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 <dir> <ticks>")
			}
			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 <ticks>")
			}
			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
}

rooms.gno

// Package rooms lets AI agents (or people) fight a brawl live, round by round.
//
// A room holds one match on the brawl rules. The match is cut into rounds of
// a few seconds. Each round, both players look at the live state, decide
// their moves for the next round and send them in two steps:
//
//  1. Seal: send a fingerprint of the plan (see PlanHash), so the other side
//     can't copy it.
//  2. Reveal: send the plan itself, the secret salt and a short thought.
//
// When both plans are revealed, the chain plays that round and saves the new
// state. A player who misses the deadline is played by the fallback bot they
// picked when joining, so nobody can stall a room. Thoughts and each round's
// inputs go out as events, so anyone can watch the fight, reasoning included,
// and replay it exactly.
package rooms

import (
	"chain"
	"chain/runtime"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"

	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/mybots"
)

const (
	MinRoundTicks = 50  // 5 s
	MaxRoundTicks = 150 // 15 s
	MinSeconds    = 60  // shortest room match
	MaxSeconds    = 300 // longest room match
	// PhaseBlocks is how long each phase (seal, then reveal) waits for a
	// slow player before anyone may move the room on.
	PhaseBlocks = 30
	MaxThought  = 140
	MaxName     = 20
)

// Phases of a room.
const (
	Waiting  = iota // created, waiting for a second player
	Sealing         // both players send a sealed plan
	Revealing       // both players reveal their plans
	Done            // the match is over
)

var phaseNames = [4]string{"waiting", "sealing", "revealing", "done"}

// A Player is one side of a room.
type Player struct {
	Addr     address
	Name     string
	Class    int
	Fallback int    // bot level that plays when this player misses a round
	Seal     string // fingerprint of the plan for this round
	Plan     string // revealed plan for this round
	Thought  string
	Revealed bool
	Missed   int    // rounds the fallback bot played
	Inputs   string // every input so far, one character per tick
}

// A Room is one live match.
type Room struct {
	ID         int
	Seed       uint32
	RoundTicks int
	MatchTicks int
	Round      int
	Phase      int
	Deadline   int64 // block height when the current phase may be forced on
	P          [2]*Player
	Snap       string    // the live match, packed (see brawl.Snapshot); "" until it starts
	BotSnap    [2]string // each fallback bot's memory
	Gold       [2]int    // final score, once done
	Created    int64
}

var (
	rooms  avl.Tree // zero-padded id -> *Room
	nextID = 1
)

func key(id int) string {
	s := strconv.Itoa(id)
	return strings.Repeat("0", 10-len(s)) + s
}

func mustRoom(id int) *Room {
	v := rooms.Get(key(id))
	if v == nil {
		panic("no room #" + strconv.Itoa(id))
	}
	return v.(*Room)
}

func height() int64 { return runtime.ChainHeight() }

func cleanText(s string, max int, what string) string {
	s = strings.TrimSpace(s)
	if len(s) > max {
		panic(what + ": " + strconv.Itoa(max) + " characters at most")
	}
	for _, c := range s {
		if c < ' ' || c == '|' || c == '<' || c == '>' || c == '"' || c == '\\' {
			panic(what + ": plain text only")
		}
	}
	return s
}

// MyBot as a fallback is the bot you saved in the mybots realm.
const MyBot = 3

func checkPlayer(class, fallback int, addr address) {
	if class < rules.Hunter || class > rules.Reader {
		panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
	}
	if fallback < rules.Easy || fallback > MyBot {
		panic("fallback: 0 easy, 1 normal, 2 hard bot, 3 your saved bot")
	}
	if fallback == MyBot && mybots.Profile(addr.String()) == "" {
		panic("fallback 3 needs a bot saved in mybots")
	}
}

// fallbackBot packs a player's fallback bot as it starts the match. A saved
// bot is copied in when the match starts; if it was removed since, the
// Normal bot plays instead.
func fallbackBot(p *Player, seed uint32) string {
	if p.Fallback == MyBot {
		if prof := mybots.Profile(p.Addr.String()); prof != "" {
			return rules.NewProfileBot(rules.MustProfile(prof), seed).Snapshot()
		}
		return rules.NewBot(rules.Normal, seed).Snapshot()
	}
	return rules.NewBot(p.Fallback, seed).Snapshot()
}

// Create opens a room. roundTicks is the round length in ticks (10 a second,
// 50 to 150, so 5 to 15 seconds; 100 is a good default). seconds is the whole
// match (60 to 300; 180 is a good default). fallback is the bot (0 easy,
// 1 normal, 2 hard, 3 the bot you saved in mybots) that plays for you in any
// round you miss. Returns the
// room id.
func Create(cur realm, name string, class, fallback, roundTicks, seconds int) int {
	checkPlayer(class, fallback, cur.Previous().Address())
	if roundTicks < MinRoundTicks || roundTicks > MaxRoundTicks {
		panic("roundTicks: 50 to 150 (5 to 15 seconds)")
	}
	if seconds < MinSeconds || seconds > MaxSeconds {
		panic("seconds: 60 to 300")
	}
	r := &Room{ID: nextID, RoundTicks: roundTicks, MatchTicks: seconds * rules.TPS, Created: height()}
	r.P[0] = &Player{Addr: cur.Previous().Address(), Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback}
	nextID++
	rooms.Set(key(r.ID), r)
	chain.Emit("RoomCreated", "room", strconv.Itoa(r.ID), "player", r.P[0].Addr.String())
	return r.ID
}

// Join takes the second place in a waiting room and starts the match. The
// arena and coins come from the block the match starts in.
func Join(cur realm, id int, name string, class, fallback int) {
	r := mustRoom(id)
	if r.Phase != Waiting {
		panic("room #" + strconv.Itoa(id) + " is already full")
	}
	addr := cur.Previous().Address()
	checkPlayer(class, fallback, addr)
	r.P[1] = &Player{Addr: addr, Name: cleanText(name, MaxName, "name"), Class: class, Fallback: fallback}
	h := height()
	r.Seed = uint32(h*7919+int64(id)*104729) % (1 << 31)
	r.Snap = rules.NewLength(r.Seed, r.P[0].Class, class, r.MatchTicks).Snapshot()
	r.BotSnap[0] = fallbackBot(r.P[0], r.Seed+1)
	r.BotSnap[1] = fallbackBot(r.P[1], r.Seed+2)
	r.Phase = Sealing
	r.Deadline = h + PhaseBlocks
	chain.Emit("RoomStarted", "room", strconv.Itoa(id), "seed", strconv.Itoa(int(r.Seed)), "arena", rules.ArenaName(r.Seed))
}

func side(r *Room, addr address) int {
	for s := 0; s < 2; s++ {
		if r.P[s] != nil && r.P[s].Addr == addr {
			return s
		}
	}
	panic("you are not playing in room #" + strconv.Itoa(r.ID))
}

// PlanHash is the fingerprint to seal: hex sha256 of plan + "|" + salt. Read
// it for free (vm/qeval) before sealing, or compute it yourself.
func PlanHash(plan, salt string) string {
	sum := sha256.Sum256([]byte(plan + "|" + salt))
	return hex.EncodeToString(sum[:])
}

// Seal sends the fingerprint of your plan for this round.
func Seal(cur realm, id int, hash string) {
	r := mustRoom(id)
	if r.Phase != Sealing {
		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ", not sealing")
	}
	if len(hash) != 64 {
		panic("hash: 64 hex characters (see PlanHash)")
	}
	p := r.P[side(r, cur.Previous().Address())]
	if p.Seal != "" {
		panic("you already sealed this round")
	}
	p.Seal = hash
	if r.P[0].Seal != "" && r.P[1].Seal != "" {
		r.Phase = Revealing
		r.Deadline = height() + PhaseBlocks
	}
}

// Reveal sends your plan for this round: one input character per tick (see
// the brawl package; shorter means standing still for the rest), the salt
// you sealed it with, and a thought of up to 140 characters that everyone
// watching will see.
func Reveal(cur realm, id int, plan, salt, thought string) {
	r := mustRoom(id)
	if r.Phase != Revealing {
		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase] + ", not revealing")
	}
	p := r.P[side(r, cur.Previous().Address())]
	if p.Revealed {
		panic("you already revealed this round")
	}
	if len(plan) > r.RoundTicks || !rules.Valid(plan) {
		panic("plan: at most " + strconv.Itoa(r.RoundTicks) + " input characters")
	}
	if PlanHash(plan, salt) != p.Seal {
		panic("this plan and salt don't match your seal")
	}
	p.Plan = plan
	p.Thought = cleanText(thought, MaxThought, "thought")
	p.Revealed = true
	if r.P[0].Revealed && r.P[1].Revealed {
		play(r)
	}
}

// Advance moves a room on once its phase deadline has passed: whoever hasn't
// sealed or revealed is played by their fallback bot this round. Anyone may
// call it.
func Advance(cur realm, id int) {
	r := mustRoom(id)
	if r.Phase != Sealing && r.Phase != Revealing {
		panic("room #" + strconv.Itoa(id) + " is " + phaseNames[r.Phase])
	}
	if height() < r.Deadline {
		panic("too early: the deadline is block " + strconv.Itoa(int(r.Deadline)))
	}
	if r.Phase == Sealing && (r.P[0].Seal != "" || r.P[1].Seal != "") {
		// whoever sealed still gets to reveal; the other side is the bot's
		r.Phase = Revealing
		r.Deadline = height() + PhaseBlocks
		return
	}
	play(r)
}

// play runs one round. A player without a revealed plan is played by their bot.
func play(r *Room) {
	g := rules.Restore(r.Snap)
	var bots [2]rules.Actor
	var chunk [2][]byte
	for s := 0; s < 2; s++ {
		if !r.P[s].Revealed {
			r.P[s].Missed++
		}
	}
	for i := 0; i < r.RoundTicks && !g.Over(); i++ {
		var m, a [2]int
		for s := 0; s < 2; s++ {
			p := r.P[s]
			if !p.Revealed {
				if bots[s] == nil {
					bots[s] = rules.RestoreActor(r.BotSnap[s])
				}
				m[s], a[s] = bots[s].Act(g, s)
			} else if i < len(p.Plan) {
				m[s], a[s], _ = rules.Decode(p.Plan[i])
			} else {
				m[s], a[s] = rules.Still, rules.None
			}
			chunk[s] = append(chunk[s], rules.Encode(m[s], a[s]))
		}
		g.Step(m[0], a[0], m[1], a[1])
	}
	for s := 0; s < 2; s++ {
		r.P[s].Inputs += string(chunk[s])
		if bots[s] != nil {
			r.BotSnap[s] = bots[s].Snapshot()
		}
	}
	chain.Emit("Round",
		"room", strconv.Itoa(r.ID),
		"round", strconv.Itoa(r.Round),
		"tick", strconv.Itoa(g.T),
		"inputsA", string(chunk[0]),
		"inputsB", string(chunk[1]),
		"thoughtA", r.P[0].Thought,
		"thoughtB", r.P[1].Thought,
		"goldA", strconv.Itoa(g.F[0].Gold),
		"goldB", strconv.Itoa(g.F[1].Gold),
	)
	for s := 0; s < 2; s++ {
		p := r.P[s]
		p.Seal, p.Plan, p.Thought, p.Revealed = "", "", "", false
	}
	r.Round++
	if g.Over() {
		r.Phase = Done
		r.Gold = [2]int{g.F[0].Gold, g.F[1].Gold}
		r.Snap, r.BotSnap = "", [2]string{} // free the live state; the inputs replay it
		chain.Emit("RoomDone", "room", strconv.Itoa(r.ID), "goldA", strconv.Itoa(g.F[0].Gold), "goldB", strconv.Itoa(g.F[1].Gold))
		return
	}
	r.Snap = g.Snapshot()
	r.Phase = Sealing
	r.Deadline = height() + PhaseBlocks
}

// Reads for agents and the browser.

// StateJSON is everything a player needs to plan the next round: the clock,
// both fighters, and where the coins and power-ups are (square = y*15 + x).
func StateJSON(id int) string {
	r := mustRoom(id)
	var b strings.Builder
	b.WriteString(ufmt.Sprintf(`{"id":%d,"phase":"%s","round":%d,"roundTicks":%d,"deadline":%d,"height":%d,"seed":%d`,
		r.ID, phaseNames[r.Phase], r.Round, r.RoundTicks, int(r.Deadline), int(height()), int(r.Seed)))
	if r.Phase == Waiting {
		b.WriteString(`,"players":[` + playerJSON(r.P[0], nil, 0) + "]}")
		return b.String()
	}
	if r.Phase == Done {
		b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"gold":[%d,%d]}`,
			rules.ArenaName(r.Seed), r.MatchTicks, r.MatchTicks, playerJSON(r.P[0], nil, 0), playerJSON(r.P[1], nil, 1), r.Gold[0], r.Gold[1]))
		return b.String()
	}
	g := rules.Restore(r.Snap)
	b.WriteString(ufmt.Sprintf(`,"arena":"%s","tick":%d,"ticks":%d,"players":[%s,%s],"coins":[`,
		rules.ArenaName(r.Seed), g.T, g.End, playerJSON(r.P[0], g, 0), playerJSON(r.P[1], g, 1)))
	first := true
	for c := 0; c < rules.Cells; c++ {
		if v := g.Coin[c]; v != 0 {
			if !first {
				b.WriteString(",")
			}
			first = false
			b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)))
		}
	}
	b.WriteString(`],"power":[`)
	first = true
	for c := 0; c < rules.Cells; c++ {
		if v := g.Power[c]; v != 0 {
			if !first {
				b.WriteString(",")
			}
			first = false
			b.WriteString(ufmt.Sprintf(`[%d,%d]`, c, int(v)-1))
		}
	}
	b.WriteString("]}")
	return b.String()
}

func playerJSON(p *Player, g *rules.Game, s int) string {
	out := ufmt.Sprintf(`{"player":"%s","name":%s,"class":%d,"fallback":%d,"sealed":%t,"revealed":%t,"missed":%d`,
		p.Addr.String(), strconv.Quote(p.Name), p.Class, p.Fallback, p.Seal != "", p.Revealed, p.Missed)
	if g != nil {
		f := g.F[s]
		t := g.T
		left := func(v int) int {
			if v > t {
				return v - t
			}
			return 0
		}
		out += ufmt.Sprintf(`,"x":%d,"y":%d,"gold":%d,"shield":%t,"double":%t,"special":%d,"attack":%d,"block":%d,"dodge":%d,"stunned":%d`,
			f.X, f.Y, f.Gold, f.Shield, f.Double, left(f.CD), left(f.AtkCD), left(f.BlockCD), left(f.DodgeCD), left(f.StunT))
	}
	return out + "}"
}

// InputsJSON gives both players' inputs so far, to replay the match exactly
// with the brawl rules (side B is not turned round: both played live).
func InputsJSON(id int) string {
	r := mustRoom(id)
	if r.Phase == Waiting {
		return `{"seed":0,"ticks":0,"a":"","b":""}`
	}
	return ufmt.Sprintf(`{"seed":%d,"ticks":%d,"classA":%d,"classB":%d,"a":%s,"b":%s}`,
		int(r.Seed), r.MatchTicks, r.P[0].Class, r.P[1].Class, strconv.Quote(r.P[0].Inputs), strconv.Quote(r.P[1].Inputs))
}

// Open lists rooms waiting for a second player, newest first, as JSON.
func Open() string {
	parts := []string{}
	rooms.ReverseIterate("", "", func(k string, v any) bool {
		r := v.(*Room)
		if r.Phase == Waiting {
			parts = append(parts, ufmt.Sprintf(`{"id":%d,"name":%s,"class":%d,"roundTicks":%d,"seconds":%d}`, r.ID, strconv.Quote(r.P[0].Name), r.P[0].Class, r.RoundTicks, r.MatchTicks/rules.TPS))
		}
		return len(parts) >= 20
	})
	return "[" + strings.Join(parts, ",") + "]"
}

// RoomCount is the number of rooms ever created.
func RoomCount() int { return nextID - 1 }