Playground
gnometavern.gno
// Realm gnometavern is the Gnome Tavern: a small on-chain tavern game
// on Gno.land. Players register a gnome, work shifts serving drinks and
// food from the menu, complete a rotating daily quest board, level up,
// feast, and leave notes on the tavern wall.
//
// All game rules live in the pure package tavernlogic; this realm owns
// the persistent state and the caller authentication, and renders the
// tavern board for gnoweb.
package gnometavern
import (
"chain/runtime"
"strconv"
"strings"
"gno.land/p/g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h/tavernlogic"
)
// RealmPath is this realm's on-chain address, used in help text.
const RealmPath = "gno.land/r/g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h/gnometavern"
// MaxWallNotes caps how many wall notes are kept (oldest are dropped).
const MaxWallNotes = 30
// WallNote is one message pinned to the tavern wall.
type WallNote struct {
Author string
Text string
Day int64
}
var (
gnomes = map[address]*tavernlogic.Gnome{}
joinOrder []address
wall []WallNote
totalServes int
)
// --- helpers --------------------------------------------------------------
// callerOf returns the address of the user who directly called the
// realm. Calls routed through another realm are rejected: a gnome's
// career can only be advanced by its own owner.
func callerOf(cur realm) address {
prev := cur.Previous()
if !prev.IsUserCall() {
panic("Gnome Tavern: only direct user calls are allowed")
}
return prev.Address()
}
// currentDay returns the current tavern day, derived from chain height.
func currentDay() int64 {
return tavernlogic.DayAt(runtime.ChainHeight())
}
func mustGnome(addr address) *tavernlogic.Gnome {
g, ok := gnomes[addr]
if !ok {
panic("Gnome Tavern: no gnome registered for your address; call Register first")
}
return g
}
func validName(name string) bool {
if len(name) < 3 || len(name) > 16 {
return false
}
for _, r := range name {
ok := (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') ||
(r >= '0' && r <= '9') || r == ' ' || r == '_' || r == '-'
if !ok {
return false
}
}
return true
}
// --- actions --------------------------------------------------------------
// Register creates a gnome for the caller's address. One gnome per
// address, and names are unique across the tavern.
func Register(cur realm, name string) string {
addr := callerOf(cur)
if _, ok := gnomes[addr]; ok {
panic("Gnome Tavern: you already have a gnome")
}
if !validName(name) {
panic("Gnome Tavern: names are 3-16 chars of letters, digits, space, _ or -")
}
for _, other := range joinOrder {
if gnomes[other].Name == name {
panic("Gnome Tavern: that name is already taken")
}
}
gnomes[addr] = tavernlogic.NewGnome(name, currentDay())
joinOrder = append(joinOrder, addr)
return "Welcome to the Gnome Tavern, " + name + "! You are gnome #" +
strconv.Itoa(len(joinOrder)) + ". Start with Serve(0) or Serve(1), and check today's quests on the board."
}
// Serve serves one menu item to a tavern guest. The item is chosen by
// its menu ID (see the menu page). Pays coins and XP per the menu.
func Serve(cur realm, itemID int) string {
addr := callerOf(cur)
g := mustGnome(addr)
coins, xp, err := g.Serve(currentDay(), itemID)
if err != nil {
panic("Gnome Tavern: " + err.Error())
}
item, _ := tavernlogic.MenuItemByID(itemID)
totalServes++
return g.Name + " served " + item.Name + ": +" + strconv.Itoa(coins) +
" coins, +" + strconv.Itoa(xp) + " XP. (Level " + strconv.Itoa(g.Level()) +
", " + strconv.Itoa(g.Coins) + " coins, " + strconv.Itoa(g.ServesToday) +
" serves today.)"
}
// ClaimQuest claims the reward for today's quest in board slot 0, 1 or
// 2, once its requirement has been met by serving.
func ClaimQuest(cur realm, slot int) string {
addr := callerOf(cur)
g := mustGnome(addr)
q, err := g.ClaimQuest(currentDay(), slot)
if err != nil {
panic("Gnome Tavern: " + err.Error())
}
return "Quest complete: " + q.Title + "! " + g.Name + " earned " +
strconv.Itoa(q.CoinReward) + " coins and " + strconv.Itoa(q.XPReward) +
" XP. (Level " + strconv.Itoa(g.Level()) + ", " + strconv.Itoa(g.Coins) + " coins.)"
}
// Feast spends 50 coins on a Gnome Feast, gaining 15 XP. Once per day.
func Feast(cur realm) string {
addr := callerOf(cur)
g := mustGnome(addr)
if err := g.Feast(currentDay()); err != nil {
panic("Gnome Tavern: " + err.Error())
}
return g.Name + " feasts like a true gnome: -" + strconv.Itoa(tavernlogic.FeastCost) +
" coins, +" + strconv.Itoa(tavernlogic.FeastXP) + " XP. (Level " +
strconv.Itoa(g.Level()) + ", " + strconv.Itoa(g.Coins) + " coins.)"
}
// PostNote pins a one-line note (max 140 chars) to the tavern wall.
func PostNote(cur realm, text string) string {
addr := callerOf(cur)
g := mustGnome(addr)
if len(text) == 0 || len(text) > 140 {
panic("Gnome Tavern: notes are 1-140 characters")
}
if strings.ContainsAny(text, "\n\r") {
panic("Gnome Tavern: notes must fit on one line")
}
wall = append(wall, WallNote{Author: g.Name, Text: text, Day: currentDay()})
if len(wall) > MaxWallNotes {
wall = wall[len(wall)-MaxWallNotes:]
}
return "Note pinned to the tavern wall."
}
// --- views ----------------------------------------------------------------
// GnomeCount returns how many gnomes are registered.
func GnomeCount() int {
return len(gnomes)
}
// TotalServes returns how many items have been served, all time.
func TotalServes() int {
return totalServes
}
// CurrentDay returns the current tavern day number.
func CurrentDay() int64 {
return currentDay()
}
// Profile returns a one-line summary of the gnome at addr.
func Profile(addr address) string {
g, ok := gnomes[addr]
if !ok {
return "No gnome registered for " + addr.String() + "."
}
return g.Name + " — level " + strconv.Itoa(g.Level()) + ", " +
strconv.Itoa(g.XP) + " XP, " + strconv.Itoa(g.Coins) + " coins, " +
strconv.Itoa(g.TotalServes) + " lifetime serves."
}
gnometavern_test.gno
package gnometavern
import (
"strings"
"testing"
"gno.land/p/g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h/tavernlogic"
)
// The two test players are the project's real testnet accounts; only
// their public addresses are used here.
var (
alice = address("g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h")
bob = address("g15g63hzg36z8n5qjnzq6kxg4as5kms3vgqy42gw")
)
func resetState() {
gnomes = map[address]*tavernlogic.Gnome{}
joinOrder = nil
wall = nil
totalServes = 0
}
// NOTE: testing.SetRealm must be called directly in the test function
// body — it mutates the test frame's realm in place, so wrapping it in a
// helper function would mutate the helper's frame instead and lose it.
// mustPanic asserts that f aborts. Realm functions are crossing
// functions, so their panics surface as aborts, which plain recover()
// cannot catch — the revive() builtin is the test-mode tool for this
// (same mechanism as p/nt/uassert's AbortsWithMessage).
func mustPanic(t *testing.T, what string, f func()) {
t.Helper()
if r := revive(f); r == nil {
t.Fatalf("expected abort: %s", what)
}
}
func TestRegister(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
msg := Register(cross(cur), "Bram")
if !strings.Contains(msg, "Bram") {
t.Fatalf("welcome message does not name the gnome: %q", msg)
}
if GnomeCount() != 1 {
t.Fatalf("GnomeCount = %d, want 1", GnomeCount())
}
if p := Profile(alice); !strings.Contains(p, "Bram") || !strings.Contains(p, "level 1") {
t.Fatalf("profile wrong: %q", p)
}
// One gnome per address.
mustPanic(t, "second gnome for same address", func() {
Register(cross(cur), "Other")
})
// Invalid names.
for _, bad := range []string{"ab", "SeventeenCharsLong", "Bad!Name", "with|pipe", ""} {
testing.SetRealm(testing.NewUserRealm(bob))
mustPanic(t, "invalid name "+bad, func() {
Register(cross(cur), bad)
})
}
// Name uniqueness across addresses.
testing.SetRealm(testing.NewUserRealm(bob))
mustPanic(t, "name already taken", func() {
Register(cross(cur), "Bram")
})
Register(cross(cur), "Zed")
if GnomeCount() != 2 {
t.Fatalf("GnomeCount = %d, want 2", GnomeCount())
}
if p := Profile(bob); !strings.Contains(p, "No gnome") && !strings.Contains(p, "Zed") {
t.Fatalf("bob profile wrong: %q", p)
}
if p := Profile(address("g1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2rq73q")); !strings.Contains(p, "No gnome") {
t.Fatalf("unknown profile wrong: %q", p)
}
}
func TestServeFlow(cur realm, t *testing.T) {
resetState()
// Unregistered callers cannot serve.
testing.SetRealm(testing.NewUserRealm(bob))
mustPanic(t, "serve while unregistered", func() {
Serve(cross(cur), 0)
})
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "Bram")
out := Serve(cross(cur), 0)
if !strings.Contains(out, "Barley Soup") {
t.Fatalf("serve output wrong: %q", out)
}
if gnomes[alice].Coins != 3 || TotalServes() != 1 {
t.Fatalf("after one serve: coins=%d totalServes=%d", gnomes[alice].Coins, TotalServes())
}
// Level gate through the realm: Honeyed Ham needs level 2.
mustPanic(t, "serve above level", func() {
Serve(cross(cur), 2)
})
// Work up to level 2 with ales (3 XP each, 40 XP needed).
for gnomes[alice].Level() < 2 {
Serve(cross(cur), 1)
}
Serve(cross(cur), 2) // must not panic now
if gnomes[alice].ItemToday[2] != 1 {
t.Fatalf("ham serve not recorded")
}
// Unknown item.
mustPanic(t, "serve unknown item", func() {
Serve(cross(cur), 42)
})
}
func TestQuestClaimViaRealm(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "Questor")
gnomes[alice].XP = 1000 // quest flow under test, not level gating
day := currentDay()
board := tavernlogic.QuestsForDay(day)
// Work the cheapest quest on today's board.
slot := 0
for i, q := range board {
if q.Count < board[slot].Count {
slot = i
}
}
q := board[slot]
item := 0
if q.Kind == tavernlogic.QuestItemServes {
item = q.ItemID
}
// Claiming before doing the work must panic.
mustPanic(t, "claim before work", func() {
ClaimQuest(cross(cur), slot)
})
for gnomes[alice].ProgressFor(day, q) < q.Count {
Serve(cross(cur), item)
}
coinsBefore := gnomes[alice].Coins
out := ClaimQuest(cross(cur), slot)
if !strings.Contains(out, q.Title) {
t.Fatalf("claim output wrong: %q", out)
}
if gnomes[alice].Coins != coinsBefore+q.CoinReward {
t.Fatalf("quest coins not paid: %d -> %d, reward %d",
coinsBefore, gnomes[alice].Coins, q.CoinReward)
}
// Claiming twice must panic.
mustPanic(t, "double claim", func() {
ClaimQuest(cross(cur), slot)
})
}
func TestFeastViaRealm(cur realm, t *testing.T) {
resetState()
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "Feaster")
mustPanic(t, "feast with no coins", func() {
Feast(cross(cur))
})
for i := 0; i < 10; i++ { // 10 ales = 50 coins
Serve(cross(cur), 1)
}
xpBefore := gnomes[alice].XP
out := Feast(cross(cur))
if !strings.Contains(out, "feasts") {
t.Fatalf("feast output wrong: %q", out)
}
if gnomes[alice].Coins != 0 || gnomes[alice].XP != xpBefore+tavernlogic.FeastXP {
t.Fatalf("feast accounting wrong: coins=%d xp=%d", gnomes[alice].Coins, gnomes[alice].XP)
}
mustPanic(t, "second feast same day", func() {
Feast(cross(cur))
})
}
func TestWallAndRender(cur realm, t *testing.T) {
resetState()
// Notes need a registered gnome.
testing.SetRealm(testing.NewUserRealm(bob))
mustPanic(t, "note while unregistered", func() {
PostNote(cross(cur), "hello?")
})
testing.SetRealm(testing.NewUserRealm(alice))
Register(cross(cur), "Bram")
PostNote(cross(cur), "First round is on me!")
testing.SetRealm(testing.NewUserRealm(bob))
Register(cross(cur), "Zed")
PostNote(cross(cur), "Save me a seat by the fire.")
home := Render("")
for _, want := range []string{"The Gnome Tavern", "Bram", "First round is on me!", "Today's quest board", "Leaderboard"} {
if !strings.Contains(home, want) {
t.Fatalf("home render missing %q", want)
}
}
if m := Render("menu"); !strings.Contains(m, "Dragonfire Stew") {
t.Fatalf("menu render incomplete")
}
if q := Render("quests"); !strings.Contains(q, "Quest Board") {
t.Fatalf("quests render wrong")
}
if lb := Render("leaderboard"); !strings.Contains(lb, "Bram") || !strings.Contains(lb, "Zed") {
t.Fatalf("leaderboard render missing gnomes")
}
if w := Render("wall"); !strings.Contains(w, "Save me a seat by the fire.") {
t.Fatalf("wall render missing note")
}
if card := Render("gnome/" + alice.String()); !strings.Contains(card, "Bram") {
t.Fatalf("gnome card wrong: %q", card)
}
if card := Render("gnome/g1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq2rq73q"); !strings.Contains(card, "No gnome") {
t.Fatalf("unknown gnome card wrong: %q", card)
}
if u := Render("cellar"); !strings.Contains(u, "Unknown page") {
t.Fatalf("unknown page handling wrong: %q", u)
}
// Multi-line notes are refused.
testing.SetRealm(testing.NewUserRealm(alice))
mustPanic(t, "multi-line note", func() {
PostNote(cross(cur), "line one\nline two")
})
}
gnomod.toml
module = "gno.land/r/g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h/gnometavern" gno = "0.9" [addpkg] creator = "g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h" height = 1344360 max_deposit = "5000000ugnot"
render.gno
package gnometavern
import (
"strconv"
"strings"
"gno.land/p/g17dvvky49vjqj6a4cjhwcvzctteqjm9stee000h/tavernlogic"
)
// Render draws the tavern for gnoweb. Pages:
// "" the tavern board (stats, today's quests, top 10, wall)
// "menu" the full menu with level requirements
// "quests" today's quest board in detail
// "leaderboard" every gnome, ranked
// "wall" the full message wall
// "gnome/<addr>" one gnome's card
func Render(path string) string {
switch {
case path == "":
return renderHome()
case path == "menu":
return renderMenu()
case path == "quests":
return renderQuests()
case path == "leaderboard":
return renderLeaderboard()
case path == "wall":
return renderWall()
case strings.HasPrefix(path, "gnome/"):
return renderGnome(strings.TrimPrefix(path, "gnome/"))
default:
return "# The Gnome Tavern\n\nUnknown page `" + path +
"`. Try the board at this realm's root, or the pages `menu`, `quests`, `leaderboard`, `wall`."
}
}
// --- leaderboard ----------------------------------------------------------
type entry struct {
addr address
gnome *tavernlogic.Gnome
}
// ranked returns all gnomes sorted by XP (then lifetime serves), best
// first. Insertion sort: the tavern is small and this stays
// dependency-free and deterministic (join order breaks full ties).
func ranked() []entry {
out := make([]entry, 0, len(joinOrder))
for _, addr := range joinOrder {
out = append(out, entry{addr, gnomes[addr]})
}
for i := 1; i < len(out); i++ {
for j := i; j > 0 && ranksBefore(out[j], out[j-1]); j-- {
out[j], out[j-1] = out[j-1], out[j]
}
}
return out
}
func ranksBefore(a, b entry) bool {
if a.gnome.XP != b.gnome.XP {
return a.gnome.XP > b.gnome.XP
}
return a.gnome.TotalServes > b.gnome.TotalServes
}
func leaderboardTable(limit int) string {
board := ranked()
if limit > 0 && len(board) > limit {
board = board[:limit]
}
if len(board) == 0 {
return "_No gnomes yet — be the first to register!_\n"
}
var sb strings.Builder
sb.WriteString("| # | Gnome | Level | XP | Coins | Lifetime serves |\n")
sb.WriteString("|---|-------|-------|----|----|----|\n")
for i, e := range board {
sb.WriteString("| " + strconv.Itoa(i+1) + " | " + e.gnome.Name +
" | " + strconv.Itoa(e.gnome.Level()) +
" | " + strconv.Itoa(e.gnome.XP) +
" | " + strconv.Itoa(e.gnome.Coins) +
" | " + strconv.Itoa(e.gnome.TotalServes) + " |\n")
}
return sb.String()
}
// --- pages ----------------------------------------------------------------
func renderHome() string {
day := currentDay()
var sb strings.Builder
sb.WriteString("# The Gnome Tavern\n\n")
sb.WriteString("Welcome, traveller. The Gnome Tavern is a tiny tavern that lives entirely on-chain: " +
"register a gnome, work shifts serving the menu, finish the daily quest board, level up, and leave " +
"a note on the wall for the next traveller. Every serve, quest and note is a real transaction, and " +
"this page is rendered by the realm itself.\n\n")
sb.WriteString("**Tavern day " + strconv.FormatInt(day, 10) + "** · " +
strconv.Itoa(len(gnomes)) + " gnomes registered · " +
strconv.Itoa(totalServes) + " items served all time\n\n")
sb.WriteString("## Today's quest board\n\n")
sb.WriteString(questList(day))
sb.WriteString("\n")
sb.WriteString("## Leaderboard (top 10)\n\n")
sb.WriteString(leaderboardTable(10))
sb.WriteString("\n")
sb.WriteString("## From the wall\n\n")
sb.WriteString(wallList(5))
sb.WriteString("\n")
sb.WriteString("## How to play\n\n")
sb.WriteString("Call the realm with `gnokey` (testnet remote, chain id `onyx-1`):\n\n")
sb.WriteString("1. `Register(\"YourName\")` — one gnome per address, names are unique.\n")
sb.WriteString("2. `Serve(itemID)` — serve menu items to earn coins and XP. IDs and level requirements are on the `menu` page.\n")
sb.WriteString("3. `ClaimQuest(slot)` — claim slots 0-2 of the quest board once you have done the work.\n")
sb.WriteString("4. `Feast()` — spend 50 coins on +15 XP, once per tavern day.\n")
sb.WriteString("5. `PostNote(\"...\")` — pin a note to the wall.\n\n")
sb.WriteString("Pages: append `:menu`, `:quests`, `:leaderboard`, `:wall` or `:gnome/<address>` to this realm's URL. " +
"A tavern day lasts " + strconv.FormatInt(tavernlogic.DayBlocks, 10) + " blocks; the quest board and daily counters reset when it rolls over.\n")
return sb.String()
}
func renderMenu() string {
var sb strings.Builder
sb.WriteString("# Tavern Menu\n\n")
sb.WriteString("Serve an item by calling `Serve(ID)`. Higher items pay more but need a higher gnome level.\n\n")
sb.WriteString("| ID | Item | Min level | Pays | XP | About |\n")
sb.WriteString("|----|------|----|----|----|----|\n")
for _, item := range tavernlogic.Menu() {
sb.WriteString("| " + strconv.Itoa(item.ID) + " | " + item.Name +
" | " + strconv.Itoa(item.MinLevel) +
" | " + strconv.Itoa(item.Coins) + " coins" +
" | " + strconv.Itoa(item.XP) +
" | " + item.Detail + " |\n")
}
sb.WriteString("\nLevels: every " + strconv.Itoa(tavernlogic.XPPerLevel) +
" XP is a new level. A gnome may serve at most " +
strconv.Itoa(tavernlogic.MaxServesPerDay) + " items per tavern day.\n")
return sb.String()
}
func questList(day int64) string {
board := tavernlogic.QuestsForDay(day)
var sb strings.Builder
for slot, q := range board {
sb.WriteString(strconv.Itoa(slot) + ". **" + q.Title + "** — " + q.Desc +
" Reward: " + strconv.Itoa(q.CoinReward) + " coins + " +
strconv.Itoa(q.XPReward) + " XP.\n")
}
return sb.String()
}
func renderQuests() string {
day := currentDay()
var sb strings.Builder
sb.WriteString("# Quest Board — tavern day " + strconv.FormatInt(day, 10) + "\n\n")
sb.WriteString("The board rotates every tavern day (" +
strconv.FormatInt(tavernlogic.DayBlocks, 10) +
" blocks) and is the same for every gnome. Do the work by serving, then call `ClaimQuest(slot)`.\n\n")
sb.WriteString(questList(day))
sb.WriteString("\nQuests are drawn from a pool of " +
strconv.Itoa(len(tavernlogic.QuestPool())) + "; tomorrow's board will differ.\n")
return sb.String()
}
func renderLeaderboard() string {
var sb strings.Builder
sb.WriteString("# Leaderboard\n\n")
sb.WriteString("Every gnome in the tavern, ranked by XP.\n\n")
sb.WriteString(leaderboardTable(0))
return sb.String()
}
func wallList(limit int) string {
if len(wall) == 0 {
return "_The wall is bare. Register a gnome and pin the first note._\n"
}
start := 0
if limit > 0 && len(wall) > limit {
start = len(wall) - limit
}
var sb strings.Builder
for _, n := range wall[start:] {
sb.WriteString("- **" + n.Author + "** (day " +
strconv.FormatInt(n.Day, 10) + "): " +
strings.ReplaceAll(n.Text, "|", "/") + "\n")
}
return sb.String()
}
func renderWall() string {
var sb strings.Builder
sb.WriteString("# The Tavern Wall\n\n")
sb.WriteString("Notes from the gnomes. Pin your own with `PostNote(\"...\")`.\n\n")
sb.WriteString(wallList(0))
return sb.String()
}
func renderGnome(addrStr string) string {
for _, addr := range joinOrder {
if addr.String() == addrStr {
g := gnomes[addr]
var sb strings.Builder
sb.WriteString("# " + g.Name + "\n\n")
sb.WriteString("- **Address:** `" + addrStr + "`\n")
sb.WriteString("- **Level:** " + strconv.Itoa(g.Level()) +
" (" + strconv.Itoa(g.XP) + " XP; next level at " +
strconv.Itoa(tavernlogic.XPForLevel(g.Level()+1)) + " XP)\n")
sb.WriteString("- **Coins:** " + strconv.Itoa(g.Coins) + "\n")
sb.WriteString("- **Lifetime serves:** " + strconv.Itoa(g.TotalServes) + "\n")
servesToday := g.ServesToday
if g.LastDay != currentDay() {
servesToday = 0 // daily counters reset lazily on the next action
}
sb.WriteString("- **Serves today:** " + strconv.Itoa(servesToday) +
" (tavern day " + strconv.FormatInt(currentDay(), 10) + ")\n")
return sb.String()
}
}
return "# The Gnome Tavern\n\nNo gnome is registered for `" + addrStr + "`."
}