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

board_test.gno

package brawl

import (
	"strconv"
	"testing"
)

func fake(id int, who string, g int) string {
	return encode(&Ghost{ID: id, Player: address(who), Name: "p" + strconv.Itoa(id), Gold: g, Inputs: "a|b"})
}

func TestBoard(t *testing.T) {
	board = [TopSize]string{}
	for i := 0; i < 12; i++ {
		who := "player" + strconv.Itoa(i)
		g := 10 + i
		if p := place(who, g); p >= 0 {
			insert(fake(100+i, who, g), who)
		}
	}
	if gold(board[0]) != 21 || gold(board[TopSize-1]) != 12 {
		t.Fatalf("board ends: %d .. %d", gold(board[0]), gold(board[TopSize-1]))
	}
	if place("newcomer", 12) != -1 || place("newcomer", 13) != TopSize-1 {
		t.Fatal("a newcomer must beat the 10th place")
	}
	// a player keeps one place, and only a better score moves it
	if place("player5", 14) != -1 {
		t.Fatal("player5 already has 15")
	}
	insert(fake(200, "player5", 30), "player5")
	n := 0
	for _, s := range board {
		if player(s) == "player5" {
			n++
		}
	}
	if n != 1 || gold(board[0]) != 30 {
		t.Fatalf("player5 holds %d places, top is %d", n, gold(board[0]))
	}
	if g := decode(board[0]); g.Inputs != "a|b" || g.Name != "p200" {
		t.Fatalf("decode: %+v", g)
	}
	board = [TopSize]string{}
}

brawl.gno

// Package brawl keeps the scores of the Code Arena brawler.
//
// You play in the browser against a house bot (Easy, Normal or Hard) or a
// ghost (a top player's recorded run). When the match ends, the browser sends
// your inputs and the score it saw.
//
//   - Ranked runs are the ones against the Hard bot. A ranked score good
//     enough for the top 10 is replayed by the chain in full before it is
//     accepted, and the call fails if the replay disagrees. So the
//     leaderboard only ever holds scores the chain has checked itself.
//   - Every other run stores nothing. It goes out as a "Run" event, which is
//     part of the chain's history and free to keep.
//
// Built to be cheap: the only stored state is the top 10 itself. Each top
// run keeps its inputs so others can fight it as a ghost; when it drops off
// the board it is deleted, so once the board is full a new top run takes no
// extra storage.
package brawl

import (
	"chain"
	"chain/runtime"
	"strconv"
	"strings"

	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
	"gno.land/p/nt/ufmt/v0"
)

// TopSize is how many players the leaderboard holds.
const TopSize = 10

// Opponents: the three house bots, or a ghost's id (FirstGhost and up).
const (
	EasyBot    = 1
	NormalBot  = 2
	HardBot    = 3
	FirstGhost = 10
)

// A Ghost is a ranked top-10 run, kept so others can fight it.
type Ghost struct {
	ID      int
	Player  address
	Name    string
	Class   int
	Seed    uint32
	Gold    int
	BotGold int // what the Hard bot scored
	Height  int64
	Inputs  string
}

var (
	board  [TopSize]string // top runs, best first, encoded; "" is an empty place
	nextID = FirstGhost
	runs   int // runs submitted
)

// encode writes a ghost as "id|player|name|class|seed|gold|botGold|height|inputs".
// Inputs go last because their alphabet includes '|'; names can't.
func encode(g *Ghost) string {
	return strconv.Itoa(g.ID) + "|" + g.Player.String() + "|" + g.Name + "|" + strconv.Itoa(g.Class) + "|" +
		strconv.Itoa(int(g.Seed)) + "|" + strconv.Itoa(g.Gold) + "|" + strconv.Itoa(g.BotGold) + "|" +
		strconv.Itoa(int(g.Height)) + "|" + g.Inputs
}

func decode(s string) *Ghost {
	f := strings.SplitN(s, "|", 9)
	n := func(i int) int {
		v, _ := strconv.Atoi(f[i])
		return v
	}
	return &Ghost{ID: n(0), Player: address(f[1]), Name: f[2], Class: n(3), Seed: uint32(n(4)),
		Gold: n(5), BotGold: n(6), Height: int64(n(7)), Inputs: f[8]}
}

// gold reads only the gold of an encoded run.
func gold(s string) int {
	k := 0
	for i := 0; i < len(s); i++ {
		if s[i] != '|' {
			continue
		}
		k++
		if k == 5 {
			j := i + 1
			for j < len(s) && s[j] != '|' {
				j++
			}
			v, _ := strconv.Atoi(s[i+1 : j])
			return v
		}
	}
	return 0
}

func player(s string) string {
	a := strings.IndexByte(s, '|')
	b := strings.IndexByte(s[a+1:], '|')
	return s[a+1 : a+1+b]
}

func findGhost(id int) *Ghost {
	prefix := strconv.Itoa(id) + "|"
	for _, s := range board {
		if strings.HasPrefix(s, prefix) {
			return decode(s)
		}
	}
	return nil
}

func mustGhost(id int) *Ghost {
	g := findGhost(id)
	if g == nil {
		panic("no ghost #" + strconv.Itoa(id) + " (only top-10 runs can be fought as ghosts)")
	}
	return g
}

func cleanName(name string) string {
	name = strings.TrimSpace(name)
	if len(name) > 20 {
		panic("name: 20 characters at most")
	}
	for _, c := range name {
		if c < ' ' || c == '|' || c == '[' || c == ']' || c == '<' || c == '>' || c == '"' || c == '\\' {
			panic("name: letters, numbers and spaces only")
		}
	}
	return name
}

// place returns where a score from this player would go on the board, or -1.
// A player holds one place; a new score must beat their old one.
func place(addr string, g int) int {
	if g <= 0 {
		return -1
	}
	for _, s := range board {
		if s != "" && player(s) == addr && g <= gold(s) {
			return -1
		}
	}
	for i, s := range board {
		if s == "" || g > gold(s) {
			return i
		}
	}
	return -1
}

func insert(s, addr string) {
	kept := []string{}
	for _, old := range board {
		if old != "" && player(old) != addr {
			kept = append(kept, old)
		}
	}
	g := gold(s)
	i := 0
	for i < len(kept) && gold(kept[i]) >= g {
		i++
	}
	kept = append(kept, "")
	copy(kept[i+1:], kept[i:])
	kept[i] = s
	var nb [TopSize]string
	for j := 0; j < TopSize && j < len(kept); j++ {
		nb[j] = kept[j]
	}
	board = nb
}

// Submit records a run. opponent is EasyBot, NormalBot, HardBot or a ghost's
// id; seed sets the arena and the coins (for a ghost it must be the ghost's
// seed). inputs are your inputs, one character per tick (see the brawl
// package); gold and oppGold are the final score the browser showed.
//
// A ranked run (against HardBot) good enough for the top 10 is replayed
// first, and the call fails if the replay disagrees. It returns your new
// ghost's id if the run made the top 10, or 0.
func Submit(cur realm, opponent, seed, class int, name, inputs string, gold, oppGold int) int {
	addr := cur.Previous().Address()
	if class < rules.Hunter || class > rules.Reader {
		panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
	}
	if seed < 0 || seed >= 1<<31 {
		panic("seed out of range")
	}
	if opponent >= FirstGhost {
		if g := mustGhost(opponent); int(g.Seed) != seed {
			panic("a ghost is fought on its own seed: " + strconv.Itoa(int(g.Seed)))
		}
	} else if opponent < EasyBot || opponent > HardBot {
		panic("opponent: 1 easy bot, 2 normal bot, 3 hard bot, or a ghost id")
	}
	if !rules.Valid(inputs) {
		panic("inputs: one character per tick, at most " + strconv.Itoa(rules.Ticks))
	}
	if gold < 0 || oppGold < 0 {
		panic("gold can't be negative")
	}
	name = cleanName(name)
	runs++
	id := 0
	if opponent == HardBot && place(addr.String(), gold) >= 0 {
		a, b := rules.Versus(uint32(seed), class, rules.Hard, inputs)
		if a != gold || b != oppGold {
			panic(ufmt.Sprintf("the chain replayed this run and got %d-%d, not %d-%d", a, b, gold, oppGold))
		}
		id = nextID
		nextID++
		insert(encode(&Ghost{ID: id, Player: addr, Name: name, Class: class, Seed: uint32(seed),
			Gold: gold, BotGold: oppGold, Height: runtime.ChainHeight(), Inputs: inputs}), addr.String())
	}
	chain.Emit("Run",
		"player", addr.String(),
		"name", name,
		"opponent", strconv.Itoa(opponent),
		"seed", strconv.Itoa(seed),
		"class", strconv.Itoa(class),
		"gold", strconv.Itoa(gold),
		"oppGold", strconv.Itoa(oppGold),
		"top", strconv.Itoa(id),
	)
	return id
}

// Reads for the browser.

// GhostInputs returns a ghost's recorded inputs.
func GhostInputs(id int) string { return mustGhost(id).Inputs }

// Top lists the leaderboard as JSON, best first. Each entry can be fought as a ghost.
func Top() string {
	parts := []string{}
	for _, s := range board {
		if s != "" {
			parts = append(parts, ghostJSON(decode(s)))
		}
	}
	return "[" + strings.Join(parts, ",") + "]"
}

// GhostJSON describes one ghost as JSON.
func GhostJSON(id int) string { return ghostJSON(mustGhost(id)) }

func ghostJSON(g *Ghost) string {
	return ufmt.Sprintf(`{"id":%d,"player":"%s","name":%s,"class":%d,"seed":%d,"arena":"%s","gold":%d,"botGold":%d,"height":%d}`,
		g.ID, g.Player.String(), strconv.Quote(g.Name), g.Class, int(g.Seed), rules.ArenaName(g.Seed), g.Gold, g.BotGold, int(g.Height))
}

// RunCount is the number of runs submitted.
func RunCount() int { return runs }

gnomod.toml

module = "gno.land/r/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
gno = "0.9"

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

render.gno

package brawl

import (
	"strconv"
	"strings"

	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
	"gno.land/p/nt/ufmt/v0"
)

var classNames = [5]string{"Hunter", "Brawler", "Coward", "Trickster", "Reader"}

func who(g *Ghost) string {
	if g.Name != "" {
		return g.Name
	}
	s := g.Player.String()
	if len(s) < 12 {
		return s
	}
	return s[:6] + "…" + s[len(s)-4:]
}

// Render shows the leaderboard, or one ghost at "ghost/<id>".
func Render(path string) string {
	if strings.HasPrefix(path, "ghost/") {
		id, err := strconv.Atoi(path[6:])
		if err != nil {
			return "Bad ghost number."
		}
		g := findGhost(id)
		if g == nil {
			return "No such ghost: it may have dropped off the top 10."
		}
		return ufmt.Sprintf("# Ghost #%d\n\n**%s** (%s) scored **%d - %d** against the Hard bot in the %s, block %d. The chain replayed the run before accepting it. You can fight this run as a ghost in the game.\n",
			g.ID, who(g), classNames[g.Class], g.Gold, g.BotGold, rules.ArenaName(g.Seed), int(g.Height))
	}
	var b strings.Builder
	b.WriteString("# Code Arena brawl\n\n")
	b.WriteString("Ranked runs are against the Hard bot. Every score on this board was replayed by the chain before it counted, and each one can be fought as a ghost.\n\n")
	b.WriteString("## Top 10\n\n")
	if board[0] == "" {
		b.WriteString("Nobody yet. Play a ranked run against the Hard bot to get on the board.\n")
	} else {
		b.WriteString("| # | Player | Class | Gold | Hard bot | Arena | Ghost |\n|---|---|---|---|---|---|---|\n")
		for i, enc := range board {
			if enc == "" {
				break
			}
			g := decode(enc)
			b.WriteString(ufmt.Sprintf("| %d | %s | %s | %d | %d | %s | [#%d](:ghost/%d) |\n",
				i+1, who(g), classNames[g.Class], g.Gold, g.BotGold, rules.ArenaName(g.Seed), g.ID, g.ID))
		}
	}
	b.WriteString(ufmt.Sprintf("\n%d runs so far.\n", runs))
	b.WriteString("\nNeed testnet GNOT to play? Get it free at [faucet.gno.land](https://faucet.gno.land).\n")
	return b.String()
}