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/nym-moultest123/x/daily/rpgroom/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186408
  max_deposit = "7000000ugnot"

render_test.gno

package rpgroom

import (
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

// ExampleRender pins the empty-room view. resetState() puts the realm back to
// its init() shape, so the example does not depend on test ordering.
func ExampleRender() {
	resetState()
	print(Render(""))
	// Output:
	// # RPG Room
	//
	// A single dungeon room with one monster in it at a time. Call `Spawn("name")` to enter, `Attack()` to fight the resident monster, `Rest()` to heal up, and `Revive()` if you fall.
	//
	// ## Current monster
	//
	// **Slime** — level 1
	//
	// `##########` 35/35 HP
	//
	// - Attack: 5
	// - Monsters cleared so far: 0
	//
	// ## Leaderboard
	//
	// _No heroes yet. Be the first: `Spawn("name")`._
}

// TestRenderLeaderboard checks spawned heroes replace the empty notice and are
// listed in rank order.
func TestRenderLeaderboard(cur realm, t *testing.T) {
	resetState()

	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("alice")))
	Spawn(cross(cur), "Alice the Bold")
	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bob")))
	Spawn(cross(cur), "Bob the Brave")

	out := Render("")
	uassert.False(t, strings.Contains(out, "_No heroes yet"), "empty notice should be gone")
	uassert.True(t, strings.Contains(out, "| # | Hero | Lvl | HP | Kills | Gold | Status |"),
		"leaderboard header should render")
	uassert.True(t, strings.Contains(out, "Alice the Bold"), "alice should be listed")
	uassert.True(t, strings.Contains(out, "Bob the Brave"), "bob should be listed")
	uassert.True(t, strings.Contains(out, "| alive |"), "a fresh hero is alive")
}

// TestRenderHeroPage checks the per-address detail route.
func TestRenderHeroPage(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	testing.SetRealm(testing.NewUserRealm(alice))
	Spawn(cross(cur), "Alice the Bold")

	out := Render(alice.String())
	uassert.True(t, strings.HasPrefix(out, "# Alice the Bold\n"), "hero page should be titled by name")
	uassert.True(t, strings.Contains(out, "- Level: 1\n"), "level should be shown")
	uassert.True(t, strings.Contains(out, "- Kills: 0\n"), "kills should be shown")
	uassert.True(t, strings.Contains(out, "- Gold: 0\n"), "gold should be shown")
	uassert.False(t, strings.Contains(out, "- Status: fallen"), "a live hero has no fallen status")
}

// TestRenderUnknownHero covers the not-found branch of the detail route.
func TestRenderUnknownHero(t *testing.T) {
	resetState()
	stranger := testutils.TestAddress("stranger").String()

	uassert.Equal(t, "> [!WARNING]\n> No hero found for `"+stranger+"`.\n", Render(stranger))
}

// TestRenderTrimsPath checks surrounding whitespace still routes to the room.
func TestRenderTrimsPath(t *testing.T) {
	resetState()
	uassert.Equal(t, Render(""), Render("   "))
}

// TestRenderMonsterHPBar checks the monster's bar tracks damage.
func TestRenderMonsterHPBar(t *testing.T) {
	resetState()
	monster.HP = monster.MaxHP / 2

	uassert.True(t, strings.Contains(Render(""), hpBar(monster.HP, monster.MaxHP)),
		"the room should render the monster's current HP bar")
}

rpgroom.gno

// Package rpgroom is a tiny single-room on-chain RPG. There is exactly one
// monster in the room at a time. Spawn a hero, take a swing, and see what
// happens: land the killing blow and the room's monster gets replaced by a
// tougher one while your hero gains XP, gold, and (eventually) a level; get
// hit hard enough and your hero falls until it's revived. A room-wide
// leaderboard tracks who has climbed the highest.
package rpgroom

import (
	"sort"
	"strconv"
	"strings"

	"chain"
	"chain/runtime"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/markdown/sanitize/v0"
)

// Hero is one player's on-chain character in the room.
type Hero struct {
	Name   string
	Level  int
	XP     int
	HP     int
	MaxHP  int
	Attack int
	Kills  int
	Gold   int
	Alive  bool
}

// Monster is the room's current resident.
type Monster struct {
	Name   string
	Level  int
	HP     int
	MaxHP  int
	Attack int
}

var (
	heroes     avl.Tree // address string -> *Hero
	monster    *Monster
	roomLevel  int
	totalKills int
)

var monsterNames = []string{
	"Slime", "Giant Rat", "Goblin", "Skeleton", "Cave Bat",
	"Orc Grunt", "Wraith", "Stone Troll", "Dread Wolf", "Young Dragon",
}

func init() {
	roomLevel = 1
	monster = spawnMonster(roomLevel)
}

func spawnMonster(level int) *Monster {
	name := monsterNames[(level-1)%len(monsterNames)]
	hp := 20 + level*15
	return &Monster{
		Name:   name,
		Level:  level,
		HP:     hp,
		MaxHP:  hp,
		Attack: 3 + level*2,
	}
}

// Spawn creates the caller's hero in the room. Each address gets exactly one
// hero; call Revive (not Spawn again) if it dies.
func Spawn(cur realm, name string) {
	if !cur.Previous().IsUserCall() {
		panic("only a direct EOA call can spawn a hero")
	}
	name = strings.TrimSpace(name)
	if name == "" {
		panic("name required")
	}
	if len(name) > 24 {
		panic("name too long (max 24 chars)")
	}
	addr := cur.Previous().Address().String()
	if heroes.Has(addr) {
		panic("you already have a hero in this room")
	}
	heroes.Set(addr, &Hero{
		Name:   name,
		Level:  1,
		HP:     30,
		MaxHP:  30,
		Attack: 5,
		Alive:  true,
	})
	chain.Emit("HeroSpawned", "addr", addr, "name", name)
}

// Attack swings the caller's hero at the room's current monster. Killing it
// grants XP and gold and replaces it with a tougher one; otherwise the
// monster strikes back.
func Attack(cur realm) {
	if !cur.Previous().IsUserCall() {
		panic("only a direct EOA call can attack")
	}
	addr := cur.Previous().Address().String()
	v := heroes.Get(addr)
	if v == nil {
		panic("no hero found; call Spawn first")
	}
	hero := v.(*Hero)
	if !hero.Alive {
		panic("your hero is dead; call Revive first")
	}

	dmg := hero.Attack
	if runtime.ChainHeight()%7 == 0 {
		dmg *= 2 // occasional critical hit, tied to block height parity
	}
	monster.HP -= dmg
	chain.Emit("HeroAttacked", "addr", addr, "damage", strconv.Itoa(dmg), "monsterHP", strconv.Itoa(monster.HP))

	if monster.HP <= 0 {
		reward := monster.Level * 10
		gained := monster.Level * 20
		hero.Gold += reward
		hero.XP += gained
		hero.Kills++
		levelUp(hero)
		chain.Emit("MonsterSlain", "addr", addr, "monster", monster.Name, "level", strconv.Itoa(monster.Level))

		totalKills++
		roomLevel++
		monster = spawnMonster(roomLevel)
		return
	}

	hero.HP -= monster.Attack
	if hero.HP <= 0 {
		hero.HP = 0
		hero.Alive = false
		chain.Emit("HeroDied", "addr", addr, "monster", monster.Name)
	}
}

// Rest heals the caller's hero for a quarter of its max HP.
func Rest(cur realm) {
	if !cur.Previous().IsUserCall() {
		panic("only a direct EOA call can rest")
	}
	addr := cur.Previous().Address().String()
	v := heroes.Get(addr)
	if v == nil {
		panic("no hero found; call Spawn first")
	}
	hero := v.(*Hero)
	if !hero.Alive {
		panic("your hero is dead; call Revive first")
	}
	if hero.HP >= hero.MaxHP {
		panic("already at full health")
	}
	heal := hero.MaxHP / 4
	if heal < 1 {
		heal = 1
	}
	hero.HP += heal
	if hero.HP > hero.MaxHP {
		hero.HP = hero.MaxHP
	}
	chain.Emit("HeroRested", "addr", addr, "hp", strconv.Itoa(hero.HP))
}

// Revive brings a fallen hero back at half max HP.
func Revive(cur realm) {
	if !cur.Previous().IsUserCall() {
		panic("only a direct EOA call can revive")
	}
	addr := cur.Previous().Address().String()
	v := heroes.Get(addr)
	if v == nil {
		panic("no hero found; call Spawn first")
	}
	hero := v.(*Hero)
	if hero.Alive {
		panic("your hero is not dead")
	}
	hero.Alive = true
	hero.HP = hero.MaxHP / 2
	if hero.HP < 1 {
		hero.HP = 1
	}
	chain.Emit("HeroRevived", "addr", addr, "hp", strconv.Itoa(hero.HP))
}

// levelUp applies every level-up a hero's current XP qualifies for. The
// threshold to reach level N+1 from level N is N*50 XP.
func levelUp(h *Hero) {
	for h.XP >= h.Level*50 {
		h.XP -= h.Level * 50
		h.Level++
		h.MaxHP += 10
		h.HP = h.MaxHP
		h.Attack += 3
	}
}

// byRank orders heroes for the leaderboard: highest level first, then XP,
// then kills, as a tiebreaker.
type byRank []*Hero

func (r byRank) Len() int      { return len(r) }
func (r byRank) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r byRank) Less(i, j int) bool {
	if r[i].Level != r[j].Level {
		return r[i].Level > r[j].Level
	}
	if r[i].XP != r[j].XP {
		return r[i].XP > r[j].XP
	}
	return r[i].Kills > r[j].Kills
}

func collectHeroes() []*Hero {
	var out []*Hero
	heroes.Iterate("", "", func(key string, value any) bool {
		out = append(out, value.(*Hero))
		return false
	})
	return out
}

func hpBar(hp, maxHP int) string {
	if maxHP <= 0 {
		maxHP = 1
	}
	filled := hp * 10 / maxHP
	if filled < 0 {
		filled = 0
	}
	if filled > 10 {
		filled = 10
	}
	bar := strings.Repeat("#", filled) + strings.Repeat("-", 10-filled)
	return "`" + bar + "` " + strconv.Itoa(hp) + "/" + strconv.Itoa(maxHP) + " HP"
}

// Render shows the room overview and leaderboard at path "", or a single
// hero's detail page when path is a bech32 address.
func Render(path string) string {
	path = strings.TrimSpace(path)
	if path != "" {
		return renderHero(path)
	}
	return renderRoom()
}

func renderRoom() string {
	var b strings.Builder
	b.WriteString("# RPG Room\n\n")
	b.WriteString("A single dungeon room with one monster in it at a time. ")
	b.WriteString("Call `Spawn(\"name\")` to enter, `Attack()` to fight the resident monster, ")
	b.WriteString("`Rest()` to heal up, and `Revive()` if you fall.\n\n")

	b.WriteString("## Current monster\n\n")
	b.WriteString("**" + sanitize.InlineText(monster.Name) + "** — level " + strconv.Itoa(monster.Level) + "\n\n")
	b.WriteString(hpBar(monster.HP, monster.MaxHP) + "\n\n")
	b.WriteString("- Attack: " + strconv.Itoa(monster.Attack) + "\n")
	b.WriteString("- Monsters cleared so far: " + strconv.Itoa(totalKills) + "\n\n")

	b.WriteString("## Leaderboard\n\n")
	all := collectHeroes()
	if len(all) == 0 {
		b.WriteString("_No heroes yet. Be the first: `Spawn(\"name\")`._\n")
		return b.String()
	}
	sort.Sort(byRank(all))
	b.WriteString("| # | Hero | Lvl | HP | Kills | Gold | Status |\n")
	b.WriteString("|---|---|---|---|---|---|---|\n")
	limit := len(all)
	if limit > 20 {
		limit = 20
	}
	for i := 0; i < limit; i++ {
		h := all[i]
		status := "alive"
		if !h.Alive {
			status = "fallen"
		}
		b.WriteString("| " + strconv.Itoa(i+1) + " | " + sanitize.InlineText(h.Name) + " | " +
			strconv.Itoa(h.Level) + " | " + strconv.Itoa(h.HP) + "/" + strconv.Itoa(h.MaxHP) + " | " +
			strconv.Itoa(h.Kills) + " | " + strconv.Itoa(h.Gold) + " | " + status + " |\n")
	}
	return b.String()
}

func renderHero(addr string) string {
	v := heroes.Get(addr)
	if v == nil {
		return "> [!WARNING]\n> No hero found for `" + sanitize.InlineText(addr) + "`.\n"
	}
	h := v.(*Hero)
	var b strings.Builder
	b.WriteString("# " + sanitize.InlineText(h.Name) + "\n\n")
	b.WriteString(hpBar(h.HP, h.MaxHP) + "\n\n")
	b.WriteString("- Level: " + strconv.Itoa(h.Level) + "\n")
	b.WriteString("- XP: " + strconv.Itoa(h.XP) + " (next level at " + strconv.Itoa(h.Level*50) + ")\n")
	b.WriteString("- Attack: " + strconv.Itoa(h.Attack) + "\n")
	b.WriteString("- Kills: " + strconv.Itoa(h.Kills) + "\n")
	b.WriteString("- Gold: " + strconv.Itoa(h.Gold) + "\n")
	if !h.Alive {
		b.WriteString("- Status: fallen — call `Revive()` to return\n")
	}
	return b.String()
}

rpgroom_test.gno

package rpgroom

import (
	"testing"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
)

func resetState() {
	heroes = avl.Tree{}
	roomLevel = 1
	totalKills = 0
	monster = spawnMonster(roomLevel)
}

func TestSpawnMonster(t *testing.T) {
	m1 := spawnMonster(1)
	m5 := spawnMonster(5)
	if m1.Level != 1 || m5.Level != 5 {
		t.Fatal("spawnMonster should carry the requested level")
	}
	if m5.HP <= m1.HP {
		t.Fatal("a higher-level monster should have more HP")
	}
	if m5.Attack <= m1.Attack {
		t.Fatal("a higher-level monster should hit harder")
	}
}

func TestLevelUp(t *testing.T) {
	h := &Hero{Level: 1, XP: 0, HP: 30, MaxHP: 30, Attack: 5}
	h.XP = 50 // exactly the level-1 threshold
	levelUp(h)
	if h.Level != 2 {
		t.Fatalf("Level = %d, want 2", h.Level)
	}
	if h.XP != 0 {
		t.Fatalf("XP = %d, want 0 (fully consumed)", h.XP)
	}
	if h.MaxHP != 40 || h.HP != 40 {
		t.Fatalf("MaxHP/HP = %d/%d, want 40/40 (healed on level up)", h.MaxHP, h.HP)
	}
	if h.Attack != 8 {
		t.Fatalf("Attack = %d, want 8", h.Attack)
	}
}

func TestLevelUpMultipleLevels(t *testing.T) {
	h := &Hero{Level: 1, XP: 200, HP: 30, MaxHP: 30, Attack: 5}
	levelUp(h)
	// level 1->2 costs 50, 2->3 costs 100: 200 - 50 - 100 = 50 left, still short of 150 for 3->4
	if h.Level != 3 {
		t.Fatalf("Level = %d, want 3", h.Level)
	}
	if h.XP != 50 {
		t.Fatalf("XP = %d, want 50 remaining", h.XP)
	}
}

func TestHPBar(t *testing.T) {
	full := hpBar(10, 10)
	empty := hpBar(0, 10)
	if full == empty {
		t.Fatal("full and empty bars should render differently")
	}
}

// Crossing: Spawn/Attack/Rest/Revive mutate realm state, so the test needs `cur realm`.
func TestFullHeroLifecycle(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	testing.SetRealm(testing.NewUserRealm(alice))
	Spawn(cross(cur), "Alice the Bold")

	v := heroes.Get(alice.String())
	if v == nil {
		t.Fatal("expected a hero for alice")
	}
	hero := v.(*Hero)
	if hero.Level != 1 || !hero.Alive {
		t.Fatalf("fresh hero should be level 1 and alive, got level=%d alive=%v", hero.Level, hero.Alive)
	}

	// Grind the starter monster down; it starts at 35 HP with our hero
	// hitting for 5 (ignoring the rare crit), so a handful of swings should
	// clear it without the hero dying (monster only hits for 5).
	startMonster := monster
	for i := 0; i < 20 && monster == startMonster; i++ {
		if !hero.Alive {
			testing.SetRealm(testing.NewUserRealm(alice))
			Revive(cross(cur))
		}
		testing.SetRealm(testing.NewUserRealm(alice))
		Attack(cross(cur))
	}
	if monster == startMonster {
		t.Fatal("expected the starter monster to be replaced after repeated attacks")
	}
	if hero.Kills < 1 {
		t.Fatalf("Kills = %d, want at least 1", hero.Kills)
	}
	if hero.Gold < 1 {
		t.Fatalf("Gold = %d, want at least 1", hero.Gold)
	}
	if roomLevel < 2 {
		t.Fatalf("roomLevel = %d, want at least 2 after a kill", roomLevel)
	}
}

func TestDoubleSpawnPanics(cur realm, t *testing.T) {
	resetState()
	bob := testutils.TestAddress("bob")
	testing.SetRealm(testing.NewUserRealm(bob))
	Spawn(cross(cur), "Bob")

	testing.SetRealm(testing.NewUserRealm(bob))
	// Spawn panics inside a cross-realm call; a plain defer/recover in this
	// test does not catch a cross-boundary panic, so use revive().
	rec := revive(func() { Spawn(cross(cur), "Bob Again") })
	if rec == nil {
		t.Fatal("expected a second Spawn for the same address to panic")
	}
}

func TestRestRequiresDamage(cur realm, t *testing.T) {
	resetState()
	carol := testutils.TestAddress("carol")
	testing.SetRealm(testing.NewUserRealm(carol))
	Spawn(cross(cur), "Carol")

	testing.SetRealm(testing.NewUserRealm(carol))
	rec := revive(func() { Rest(cross(cur)) })
	if rec == nil {
		t.Fatal("expected Rest at full HP to panic")
	}
}