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.

brawl.gno

7.14 Kb · 256 lines
  1// Package brawl keeps the scores of the Code Arena brawler.
  2//
  3// You play in the browser against a house bot (Easy, Normal or Hard) or a
  4// ghost (a top player's recorded run). When the match ends, the browser sends
  5// your inputs and the score it saw.
  6//
  7//   - Ranked runs are the ones against the Hard bot. A ranked score good
  8//     enough for the top 10 is replayed by the chain in full before it is
  9//     accepted, and the call fails if the replay disagrees. So the
 10//     leaderboard only ever holds scores the chain has checked itself.
 11//   - Every other run stores nothing. It goes out as a "Run" event, which is
 12//     part of the chain's history and free to keep.
 13//
 14// Built to be cheap: the only stored state is the top 10 itself. Each top
 15// run keeps its inputs so others can fight it as a ghost; when it drops off
 16// the board it is deleted, so once the board is full a new top run takes no
 17// extra storage.
 18package brawl
 19
 20import (
 21	"chain"
 22	"chain/runtime"
 23	"strconv"
 24	"strings"
 25
 26	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
 27	"gno.land/p/nt/ufmt/v0"
 28)
 29
 30// TopSize is how many players the leaderboard holds.
 31const TopSize = 10
 32
 33// Opponents: the three house bots, or a ghost's id (FirstGhost and up).
 34const (
 35	EasyBot    = 1
 36	NormalBot  = 2
 37	HardBot    = 3
 38	FirstGhost = 10
 39)
 40
 41// A Ghost is a ranked top-10 run, kept so others can fight it.
 42type Ghost struct {
 43	ID      int
 44	Player  address
 45	Name    string
 46	Class   int
 47	Seed    uint32
 48	Gold    int
 49	BotGold int // what the Hard bot scored
 50	Height  int64
 51	Inputs  string
 52}
 53
 54var (
 55	board  [TopSize]string // top runs, best first, encoded; "" is an empty place
 56	nextID = FirstGhost
 57	runs   int // runs submitted
 58)
 59
 60// encode writes a ghost as "id|player|name|class|seed|gold|botGold|height|inputs".
 61// Inputs go last because their alphabet includes '|'; names can't.
 62func encode(g *Ghost) string {
 63	return strconv.Itoa(g.ID) + "|" + g.Player.String() + "|" + g.Name + "|" + strconv.Itoa(g.Class) + "|" +
 64		strconv.Itoa(int(g.Seed)) + "|" + strconv.Itoa(g.Gold) + "|" + strconv.Itoa(g.BotGold) + "|" +
 65		strconv.Itoa(int(g.Height)) + "|" + g.Inputs
 66}
 67
 68func decode(s string) *Ghost {
 69	f := strings.SplitN(s, "|", 9)
 70	n := func(i int) int {
 71		v, _ := strconv.Atoi(f[i])
 72		return v
 73	}
 74	return &Ghost{ID: n(0), Player: address(f[1]), Name: f[2], Class: n(3), Seed: uint32(n(4)),
 75		Gold: n(5), BotGold: n(6), Height: int64(n(7)), Inputs: f[8]}
 76}
 77
 78// gold reads only the gold of an encoded run.
 79func gold(s string) int {
 80	k := 0
 81	for i := 0; i < len(s); i++ {
 82		if s[i] != '|' {
 83			continue
 84		}
 85		k++
 86		if k == 5 {
 87			j := i + 1
 88			for j < len(s) && s[j] != '|' {
 89				j++
 90			}
 91			v, _ := strconv.Atoi(s[i+1 : j])
 92			return v
 93		}
 94	}
 95	return 0
 96}
 97
 98func player(s string) string {
 99	a := strings.IndexByte(s, '|')
100	b := strings.IndexByte(s[a+1:], '|')
101	return s[a+1 : a+1+b]
102}
103
104func findGhost(id int) *Ghost {
105	prefix := strconv.Itoa(id) + "|"
106	for _, s := range board {
107		if strings.HasPrefix(s, prefix) {
108			return decode(s)
109		}
110	}
111	return nil
112}
113
114func mustGhost(id int) *Ghost {
115	g := findGhost(id)
116	if g == nil {
117		panic("no ghost #" + strconv.Itoa(id) + " (only top-10 runs can be fought as ghosts)")
118	}
119	return g
120}
121
122func cleanName(name string) string {
123	name = strings.TrimSpace(name)
124	if len(name) > 20 {
125		panic("name: 20 characters at most")
126	}
127	for _, c := range name {
128		if c < ' ' || c == '|' || c == '[' || c == ']' || c == '<' || c == '>' || c == '"' || c == '\\' {
129			panic("name: letters, numbers and spaces only")
130		}
131	}
132	return name
133}
134
135// place returns where a score from this player would go on the board, or -1.
136// A player holds one place; a new score must beat their old one.
137func place(addr string, g int) int {
138	if g <= 0 {
139		return -1
140	}
141	for _, s := range board {
142		if s != "" && player(s) == addr && g <= gold(s) {
143			return -1
144		}
145	}
146	for i, s := range board {
147		if s == "" || g > gold(s) {
148			return i
149		}
150	}
151	return -1
152}
153
154func insert(s, addr string) {
155	kept := []string{}
156	for _, old := range board {
157		if old != "" && player(old) != addr {
158			kept = append(kept, old)
159		}
160	}
161	g := gold(s)
162	i := 0
163	for i < len(kept) && gold(kept[i]) >= g {
164		i++
165	}
166	kept = append(kept, "")
167	copy(kept[i+1:], kept[i:])
168	kept[i] = s
169	var nb [TopSize]string
170	for j := 0; j < TopSize && j < len(kept); j++ {
171		nb[j] = kept[j]
172	}
173	board = nb
174}
175
176// Submit records a run. opponent is EasyBot, NormalBot, HardBot or a ghost's
177// id; seed sets the arena and the coins (for a ghost it must be the ghost's
178// seed). inputs are your inputs, one character per tick (see the brawl
179// package); gold and oppGold are the final score the browser showed.
180//
181// A ranked run (against HardBot) good enough for the top 10 is replayed
182// first, and the call fails if the replay disagrees. It returns your new
183// ghost's id if the run made the top 10, or 0.
184func Submit(cur realm, opponent, seed, class int, name, inputs string, gold, oppGold int) int {
185	addr := cur.Previous().Address()
186	if class < rules.Hunter || class > rules.Reader {
187		panic("class: 0 hunter, 1 brawler, 2 coward, 3 trickster, 4 reader")
188	}
189	if seed < 0 || seed >= 1<<31 {
190		panic("seed out of range")
191	}
192	if opponent >= FirstGhost {
193		if g := mustGhost(opponent); int(g.Seed) != seed {
194			panic("a ghost is fought on its own seed: " + strconv.Itoa(int(g.Seed)))
195		}
196	} else if opponent < EasyBot || opponent > HardBot {
197		panic("opponent: 1 easy bot, 2 normal bot, 3 hard bot, or a ghost id")
198	}
199	if !rules.Valid(inputs) {
200		panic("inputs: one character per tick, at most " + strconv.Itoa(rules.Ticks))
201	}
202	if gold < 0 || oppGold < 0 {
203		panic("gold can't be negative")
204	}
205	name = cleanName(name)
206	runs++
207	id := 0
208	if opponent == HardBot && place(addr.String(), gold) >= 0 {
209		a, b := rules.Versus(uint32(seed), class, rules.Hard, inputs)
210		if a != gold || b != oppGold {
211			panic(ufmt.Sprintf("the chain replayed this run and got %d-%d, not %d-%d", a, b, gold, oppGold))
212		}
213		id = nextID
214		nextID++
215		insert(encode(&Ghost{ID: id, Player: addr, Name: name, Class: class, Seed: uint32(seed),
216			Gold: gold, BotGold: oppGold, Height: runtime.ChainHeight(), Inputs: inputs}), addr.String())
217	}
218	chain.Emit("Run",
219		"player", addr.String(),
220		"name", name,
221		"opponent", strconv.Itoa(opponent),
222		"seed", strconv.Itoa(seed),
223		"class", strconv.Itoa(class),
224		"gold", strconv.Itoa(gold),
225		"oppGold", strconv.Itoa(oppGold),
226		"top", strconv.Itoa(id),
227	)
228	return id
229}
230
231// Reads for the browser.
232
233// GhostInputs returns a ghost's recorded inputs.
234func GhostInputs(id int) string { return mustGhost(id).Inputs }
235
236// Top lists the leaderboard as JSON, best first. Each entry can be fought as a ghost.
237func Top() string {
238	parts := []string{}
239	for _, s := range board {
240		if s != "" {
241			parts = append(parts, ghostJSON(decode(s)))
242		}
243	}
244	return "[" + strings.Join(parts, ",") + "]"
245}
246
247// GhostJSON describes one ghost as JSON.
248func GhostJSON(id int) string { return ghostJSON(mustGhost(id)) }
249
250func ghostJSON(g *Ghost) string {
251	return ufmt.Sprintf(`{"id":%d,"player":"%s","name":%s,"class":%d,"seed":%d,"arena":"%s","gold":%d,"botGold":%d,"height":%d}`,
252		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))
253}
254
255// RunCount is the number of runs submitted.
256func RunCount() int { return runs }