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.

moves.gno

4.50 Kb · 181 lines
  1// Package moves is the book of move recipes for the Code Arena brawler.
  2//
  3// A recipe is a special move written as data, like "Blink Thief/84/D82S11":
  4// a name, a cooldown and up to three effects (see recipe.gno in the brawl
  5// package for the format and the budget). Anyone can publish one; the browser
  6// lets you equip any published move for practice, and the chain's rules run
  7// it exactly like the browser does.
  8//
  9// Built to be cheap: a recipe is stored as one short string, "author recipe",
 10// and bucketSize recipes share one tree node, so most publishes only pay for
 11// their own few dozen bytes. Each author also has one string listing their ids.
 12package moves
 13
 14import (
 15	"chain"
 16	"strconv"
 17	"strings"
 18
 19	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl/v2"
 20	"gno.land/p/nt/avl/v0"
 21)
 22
 23const (
 24	bucketSize   = 16
 25	MaxPerAuthor = 32
 26)
 27
 28var (
 29	buckets  = avl.NewTree() // bucket number -> records joined by "\n"
 30	byAuthor = avl.NewTree() // address -> "id,id,..."
 31	count    int
 32)
 33
 34func bucketKey(id int) string { return strconv.Itoa((id - 1) / bucketSize) }
 35
 36// record returns "author recipe" for an id, or "".
 37func record(id int) string {
 38	if id < 1 || id > count {
 39		return ""
 40	}
 41	v := buckets.Get(bucketKey(id))
 42	if v == nil {
 43		return ""
 44	}
 45	// walk to the i-th record of the bucket
 46	b := v.(string)
 47	for i := (id - 1) % bucketSize; i > 0; i-- {
 48		k := strings.IndexByte(b, '\n')
 49		if k < 0 {
 50			return ""
 51		}
 52		b = b[k+1:]
 53	}
 54	if k := strings.IndexByte(b, '\n'); k >= 0 {
 55		b = b[:k]
 56	}
 57	return b
 58}
 59
 60func split(rec string) (string, string) {
 61	i := strings.IndexByte(rec, ' ')
 62	return rec[:i], rec[i+1:]
 63}
 64
 65func mustRecord(id int) (string, string) {
 66	rec := record(id)
 67	if rec == "" {
 68		panic("no move #" + strconv.Itoa(id))
 69	}
 70	return split(rec)
 71}
 72
 73// authorCount is how many moves an author has published.
 74func authorCount(addr string) int {
 75	v := byAuthor.Get(addr)
 76	if v == nil {
 77		return 0
 78	}
 79	return strings.Count(v.(string), ",") + 1
 80}
 81
 82func authorIDs(addr string) []int {
 83	v := byAuthor.Get(addr)
 84	if v == nil {
 85		return nil
 86	}
 87	ids := []int{}
 88	for _, s := range strings.Split(v.(string), ",") {
 89		n, _ := strconv.Atoi(s)
 90		ids = append(ids, n)
 91	}
 92	return ids
 93}
 94
 95// Publish checks a recipe and stores it under the caller's address. It
 96// returns the move's id. An author can publish MaxPerAuthor moves.
 97func Publish(cur realm, recipe string) int {
 98	r, err := rules.ParseRecipe(recipe)
 99	if err != nil {
100		panic(err.Error())
101	}
102	recipe = r.String()
103	addr := cur.Previous().Address().String()
104	if authorCount(addr) >= MaxPerAuthor {
105		panic("an author can publish " + strconv.Itoa(MaxPerAuthor) + " moves")
106	}
107	count++
108	id := count
109	rec := addr + " " + recipe
110	key := bucketKey(id)
111	if v := buckets.Get(key); v != nil {
112		rec = v.(string) + "\n" + rec
113	}
114	buckets.Set(key, rec)
115	list := strconv.Itoa(id)
116	if v := byAuthor.Get(addr); v != nil {
117		list = v.(string) + "," + list
118	}
119	byAuthor.Set(addr, list)
120	chain.Emit("Publish", "id", strconv.Itoa(id), "author", addr, "recipe", recipe)
121	return id
122}
123
124// Reads for the browser.
125
126// Count is how many moves have been published.
127func Count() int { return count }
128
129// Recipe returns a move's recipe string.
130func Recipe(id int) string {
131	_, r := mustRecord(id)
132	return r
133}
134
135// Author returns who published a move.
136func Author(id int) string {
137	a, _ := mustRecord(id)
138	return a
139}
140
141// Check reports whether a recipe is valid and what cooldown it needs, without
142// storing anything: "ok <cost>" or the reason it is refused.
143func Check(recipe string) string {
144	r, err := rules.ParseRecipe(recipe)
145	if err != nil {
146		return err.Error()
147	}
148	return "ok " + strconv.Itoa(r.Cost())
149}
150
151func moveJSON(id int) string {
152	a, s := mustRecord(id)
153	r := rules.MustRecipe(s)
154	return `{"id":` + strconv.Itoa(id) + `,"author":"` + a + `","recipe":` + strconv.Quote(s) +
155		`,"name":` + strconv.Quote(r.Name) + `,"cd":` + strconv.Itoa(r.CD) + `,"cost":` + strconv.Itoa(r.Cost()) + `}`
156}
157
158// MoveJSON describes one move as JSON.
159func MoveJSON(id int) string { return moveJSON(id) }
160
161// List returns up to n moves as a JSON array, newest first, skipping the
162// newest skip.
163func List(skip, n int) string {
164	if n > 50 {
165		n = 50
166	}
167	parts := []string{}
168	for id := count - skip; id >= 1 && len(parts) < n; id-- {
169		parts = append(parts, moveJSON(id))
170	}
171	return "[" + strings.Join(parts, ",") + "]"
172}
173
174// ByAuthor returns an author's moves as a JSON array, oldest first.
175func ByAuthor(addr string) string {
176	parts := []string{}
177	for _, id := range authorIDs(addr) {
178		parts = append(parts, moveJSON(id))
179	}
180	return "[" + strings.Join(parts, ",") + "]"
181}