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/moves"
gno = "0.9"

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

moves.gno

// Package moves is the book of move recipes for the Code Arena brawler.
//
// A recipe is a special move written as data, like "Blink Thief/84/D82S11":
// a name, a cooldown and up to three effects (see recipe.gno in the brawl
// package for the format and the budget). Anyone can publish one; the browser
// lets you equip any published move for practice, and the chain's rules run
// it exactly like the browser does.
//
// Built to be cheap: a recipe is stored as one short string, "author recipe",
// and bucketSize recipes share one tree node, so most publishes only pay for
// their own few dozen bytes. Each author also has one string listing their ids.
package moves

import (
	"chain"
	"strconv"
	"strings"

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

const (
	bucketSize   = 16
	MaxPerAuthor = 32
)

var (
	buckets  = avl.NewTree() // bucket number -> records joined by "\n"
	byAuthor = avl.NewTree() // address -> "id,id,..."
	count    int
)

func bucketKey(id int) string { return strconv.Itoa((id - 1) / bucketSize) }

// record returns "author recipe" for an id, or "".
func record(id int) string {
	if id < 1 || id > count {
		return ""
	}
	v := buckets.Get(bucketKey(id))
	if v == nil {
		return ""
	}
	// walk to the i-th record of the bucket
	b := v.(string)
	for i := (id - 1) % bucketSize; i > 0; i-- {
		k := strings.IndexByte(b, '\n')
		if k < 0 {
			return ""
		}
		b = b[k+1:]
	}
	if k := strings.IndexByte(b, '\n'); k >= 0 {
		b = b[:k]
	}
	return b
}

func split(rec string) (string, string) {
	i := strings.IndexByte(rec, ' ')
	return rec[:i], rec[i+1:]
}

func mustRecord(id int) (string, string) {
	rec := record(id)
	if rec == "" {
		panic("no move #" + strconv.Itoa(id))
	}
	return split(rec)
}

// authorCount is how many moves an author has published.
func authorCount(addr string) int {
	v := byAuthor.Get(addr)
	if v == nil {
		return 0
	}
	return strings.Count(v.(string), ",") + 1
}

func authorIDs(addr string) []int {
	v := byAuthor.Get(addr)
	if v == nil {
		return nil
	}
	ids := []int{}
	for _, s := range strings.Split(v.(string), ",") {
		n, _ := strconv.Atoi(s)
		ids = append(ids, n)
	}
	return ids
}

// Publish checks a recipe and stores it under the caller's address. It
// returns the move's id. An author can publish MaxPerAuthor moves.
func Publish(cur realm, recipe string) int {
	r, err := rules.ParseRecipe(recipe)
	if err != nil {
		panic(err.Error())
	}
	recipe = r.String()
	addr := cur.Previous().Address().String()
	if authorCount(addr) >= MaxPerAuthor {
		panic("an author can publish " + strconv.Itoa(MaxPerAuthor) + " moves")
	}
	count++
	id := count
	rec := addr + " " + recipe
	key := bucketKey(id)
	if v := buckets.Get(key); v != nil {
		rec = v.(string) + "\n" + rec
	}
	buckets.Set(key, rec)
	list := strconv.Itoa(id)
	if v := byAuthor.Get(addr); v != nil {
		list = v.(string) + "," + list
	}
	byAuthor.Set(addr, list)
	chain.Emit("Publish", "id", strconv.Itoa(id), "author", addr, "recipe", recipe)
	return id
}

// Reads for the browser.

// Count is how many moves have been published.
func Count() int { return count }

// Recipe returns a move's recipe string.
func Recipe(id int) string {
	_, r := mustRecord(id)
	return r
}

// Author returns who published a move.
func Author(id int) string {
	a, _ := mustRecord(id)
	return a
}

// Check reports whether a recipe is valid and what cooldown it needs, without
// storing anything: "ok <cost>" or the reason it is refused.
func Check(recipe string) string {
	r, err := rules.ParseRecipe(recipe)
	if err != nil {
		return err.Error()
	}
	return "ok " + strconv.Itoa(r.Cost())
}

func moveJSON(id int) string {
	a, s := mustRecord(id)
	r := rules.MustRecipe(s)
	return `{"id":` + strconv.Itoa(id) + `,"author":"` + a + `","recipe":` + strconv.Quote(s) +
		`,"name":` + strconv.Quote(r.Name) + `,"cd":` + strconv.Itoa(r.CD) + `,"cost":` + strconv.Itoa(r.Cost()) + `}`
}

// MoveJSON describes one move as JSON.
func MoveJSON(id int) string { return moveJSON(id) }

// List returns up to n moves as a JSON array, newest first, skipping the
// newest skip.
func List(skip, n int) string {
	if n > 50 {
		n = 50
	}
	parts := []string{}
	for id := count - skip; id >= 1 && len(parts) < n; id-- {
		parts = append(parts, moveJSON(id))
	}
	return "[" + strings.Join(parts, ",") + "]"
}

// ByAuthor returns an author's moves as a JSON array, oldest first.
func ByAuthor(addr string) string {
	parts := []string{}
	for _, id := range authorIDs(addr) {
		parts = append(parts, moveJSON(id))
	}
	return "[" + strings.Join(parts, ",") + "]"
}

render.gno

package moves

import (
	"strconv"
	"strings"

	rules "gno.land/p/g1ftppd2jpfx0p8cy08th4u9whwvqcpychhlad28/brawl"
)

func short(addr string) string {
	if len(addr) < 12 {
		return addr
	}
	return addr[:6] + "…" + addr[len(addr)-4:]
}

func secs(ticks int) string {
	s := strconv.Itoa(ticks / rules.TPS)
	if ticks%rules.TPS != 0 {
		s += "." + strconv.Itoa(ticks%rules.TPS)
	}
	return s + "s"
}

func row(b *strings.Builder, id int) {
	a, s := mustRecord(id)
	r := rules.MustRecipe(s)
	b.WriteString("| [#" + strconv.Itoa(id) + "](:move/" + strconv.Itoa(id) + ") | " + r.Name + " | " + secs(r.CD) +
		" | " + r.Describe() + " | [" + short(a) + "](:by/" + a + ") |\n")
}

const header = "| # | Move | Recharge | What it does | Author |\n|---|---|---|---|---|\n"

// Render shows the newest moves, one move at "move/<id>", or an author's
// moves at "by/<address>".
func Render(path string) string {
	var b strings.Builder
	switch {
	case strings.HasPrefix(path, "move/"):
		id, err := strconv.Atoi(path[5:])
		if err != nil || record(id) == "" {
			return "No such move."
		}
		a, s := mustRecord(id)
		r := rules.MustRecipe(s)
		b.WriteString("# " + r.Name + "\n\n")
		b.WriteString("Move #" + strconv.Itoa(id) + " by [" + short(a) + "](:by/" + a + "). Recharges in " + secs(r.CD) +
			" (its effects need at least " + secs(r.Cost()) + ").\n\n")
		for _, e := range r.Fx {
			b.WriteString("- " + e.Describe() + "\n")
		}
		b.WriteString("\nRecipe: `" + s + "`\n")
		return b.String()
	case strings.HasPrefix(path, "by/"):
		addr := path[3:]
		ids := authorIDs(addr)
		b.WriteString("# Moves by " + short(addr) + "\n\n")
		if len(ids) == 0 {
			b.WriteString("None yet.\n")
			return b.String()
		}
		b.WriteString(header)
		for _, id := range ids {
			row(&b, id)
		}
		return b.String()
	}
	b.WriteString("# Move recipes\n\n")
	b.WriteString("Special moves anyone can design, written as data. Equip one in the brawler to use it in place of your class special; the chain runs it with the same rules as the browser.\n\n")
	b.WriteString("A recipe is `name/cooldown/effects`, for example `Blink Thief/84/D82S11`: dash 4 squares to the nearest gold, then steal 1 gold in melee. ")
	b.WriteString("Stronger effects need longer cooldowns. Check one with `Check(recipe)` and publish it with `Publish(recipe)`.\n\n")
	if count == 0 {
		b.WriteString("No moves published yet.\n")
		return b.String()
	}
	b.WriteString("## Newest\n\n" + header)
	for id := count; id >= 1 && id > count-20; id-- {
		row(&b, id)
	}
	b.WriteString("\n" + strconv.Itoa(count) + " moves published.\n")
	return b.String()
}