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

codespan_test.gno

package tamagotchi

import (
	"strings"
	"testing"

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

// The not-found branch echoes the visitor's URL path into a code span. Built by
// hand, a backtick in the path closed the span early and everything after it
// rendered as markdown on a gno.land page. md.InlineCode sizes the fence past
// any backtick run in the content, so the payload must come back wrapped in a
// DOUBLE fence, with the backtick intact inside it. Asserting on the payload
// itself rather than on any double fence in the page: an earlier version of
// this test passed on an unrelated span elsewhere in the output.
func TestRenderPathCannotEscapeItsCodeSpan(t *testing.T) {
	out := Render("/a`b")
	fenced := strings.Contains(out, "``a`b``") || strings.Contains(out, "``/a`b``")
	uassert.True(t, fenced,
		"the fence did not outscan the caller's backtick, so the span closes early")
}

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/tamagotchi/v1"
gno = "0.9"
private = true

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914308
  max_deposit = "9000000ugnot"

tamagotchi.gno

// Package tamagotchi is an on-chain virtual pet. Hatch one, then keep it
// alive by Feeding, Playing and letting it Sleep — hunger, happiness and
// energy all decay with block height, and neglect too long kills the pet.
// Hatching again after a death starts a fresh pet but keeps your lifetime
// stats, so the leaderboard rewards long-term care, not just luck.
package tamagotchi

import (
	"sort"
	"strconv"
	"chain/runtime"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/nt/avl/v0"
)

// pet is the persisted record for one owner's tamagotchi.
type pet struct {
	owner      address
	name       string
	born       int64
	lastUpdate int64
	hunger     int // 0 (full) .. 100 (starving)
	happiness  int // 0 (miserable) .. 100 (joyful)
	energy     int // 0 (exhausted) .. 100 (energetic)
	// happyDebt and energyDebt carry the blocks that have elapsed but not yet
	// cost a point, because happiness decays once per 2 blocks and energy once
	// per 3. Without them the division truncates on EVERY call, so acting once
	// per block cost 1/2 = 0 happiness and 1/3 = 0 energy forever: a pet fed in
	// a loop never aged. The remainder makes the decay depend on elapsed time
	// and not on how often someone calls.
	happyDebt  int // 0..1 blocks owed toward the next happiness point
	energyDebt int // 0..2 blocks owed toward the next energy point
	alive      bool
	deaths     int
	feeds      int
	plays      int
}

var pets avl.Tree // owner address string -> *pet

func clamp(v, lo, hi int) int {
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

func get(owner address) (*pet, bool) {
	v := pets.Get(owner.String())
	if v == nil {
		return nil, false
	}
	return v.(*pet), true
}

// tick applies stat decay for blocks elapsed since the pet's last update and
// kills it if any stat has bottomed/topped out. Mutates and persists.
func (p *pet) tick(height int64) {
	if !p.alive {
		return
	}
	elapsed := int(height - p.lastUpdate)
	if elapsed <= 0 {
		return
	}
	p.hunger = clamp(p.hunger+elapsed, 0, 100)

	// Spend the elapsed blocks against the debt, take whole points out, and
	// keep the remainder for next time.
	p.happyDebt += elapsed
	p.happiness = clamp(p.happiness-p.happyDebt/2, 0, 100)
	p.happyDebt %= 2

	p.energyDebt += elapsed
	p.energy = clamp(p.energy-p.energyDebt/3, 0, 100)
	p.energyDebt %= 3

	p.lastUpdate = height
	if p.hunger >= 100 || p.happiness <= 0 || p.energy <= 0 {
		p.alive = false
		p.deaths++
	}
}

// project computes display stats as of height without mutating the pet, so
// Render can show a live-looking view without writing state on a query.
func project(p *pet, height int64) (hunger, happiness, energy int, alive bool) {
	if !p.alive {
		return p.hunger, p.happiness, p.energy, false
	}
	elapsed := int(height - p.lastUpdate)
	if elapsed < 0 {
		elapsed = 0
	}
	// Same arithmetic as tick, including the carried debt, so the page never
	// disagrees with what the next call will do.
	hunger = clamp(p.hunger+elapsed, 0, 100)
	happiness = clamp(p.happiness-(p.happyDebt+elapsed)/2, 0, 100)
	energy = clamp(p.energy-(p.energyDebt+elapsed)/3, 0, 100)
	alive = hunger < 100 && happiness > 0 && energy > 0
	return
}

func ageStageName(born, height int64) string {
	switch age := height - born; {
	case age < 10:
		return "🥚 Egg"
	case age < 50:
		return "🐣 Baby"
	case age < 200:
		return "🐤 Teen"
	default:
		return "🐓 Adult"
	}
}

// requireLivingPet ticks and fetches the caller's pet, panicking with a
// friendly message if there is none or it has died.
func requireLivingPet(owner address, height int64) *pet {
	p, ok := get(owner)
	if !ok {
		panic("you don't have a pet yet — call Hatch(name) first")
	}
	p.tick(height)
	if !p.alive {
		panic(p.name + " has died of neglect. Call Hatch(name) to start over.")
	}
	return p
}

// hatch is the non-crossing core of Hatch, kept separate so unit tests can
// exercise its panics directly without going through a realm-crossing call.
func hatch(owner address, name string, height int64) string {
	if name == "" {
		panic("name cannot be empty")
	}

	deaths, feeds, plays := 0, 0, 0
	if existing, ok := get(owner); ok {
		if existing.alive {
			existing.tick(height)
		}
		if existing.alive {
			panic("you already have a living pet: " + existing.name)
		}
		deaths, feeds, plays = existing.deaths, existing.feeds, existing.plays
	}

	pets.Set(owner.String(), &pet{
		owner:      owner,
		name:       name,
		born:       height,
		lastUpdate: height,
		hunger:     20,
		happiness:  80,
		energy:     80,
		alive:      true,
		deaths:     deaths,
		feeds:      feeds,
		plays:      plays,
	})
	return "🥚 " + name + " has hatched!"
}

// Hatch creates a new pet for the caller. Lifetime feeds/plays/deaths carry
// over from any previous pet so the leaderboard tracks long-term care.
func Hatch(cur realm, name string) string {
	if !cur.IsCurrent() {
		panic("spoofed realm")
	}
	return hatch(cur.Previous().Address(), name, runtime.ChainHeight())
}

// feed is the non-crossing core of Feed.
func feed(owner address, height int64) string {
	p := requireLivingPet(owner, height)
	p.hunger = clamp(p.hunger-30, 0, 100)
	p.energy = clamp(p.energy+5, 0, 100)
	p.feeds++
	return p.name + " munches happily. Hunger: " + strconv.Itoa(p.hunger) + "/100"
}

// Feed reduces hunger and gives a small energy boost.
func Feed(cur realm) string {
	if !cur.IsCurrent() {
		panic("spoofed realm")
	}
	return feed(cur.Previous().Address(), runtime.ChainHeight())
}

// play is the non-crossing core of Play.
func play(owner address, height int64) string {
	p := requireLivingPet(owner, height)
	if p.energy < 10 {
		return p.name + " is too tired to play — try Sleep() first."
	}
	p.happiness = clamp(p.happiness+20, 0, 100)
	p.energy = clamp(p.energy-10, 0, 100)
	p.hunger = clamp(p.hunger+5, 0, 100)
	p.plays++
	return p.name + " had a blast! Happiness: " + strconv.Itoa(p.happiness) + "/100"
}

// Play boosts happiness at the cost of energy and a bit of hunger. Refuses
// to run a tired pet into the ground — rest first.
func Play(cur realm) string {
	if !cur.IsCurrent() {
		panic("spoofed realm")
	}
	return play(cur.Previous().Address(), runtime.ChainHeight())
}

// sleep is the non-crossing core of Sleep.
func sleep(owner address, height int64) string {
	p := requireLivingPet(owner, height)
	p.energy = clamp(p.energy+40, 0, 100)
	p.hunger = clamp(p.hunger+5, 0, 100)
	return p.name + " takes a nap. Energy: " + strconv.Itoa(p.energy) + "/100"
}

// Sleep restores energy at the cost of a little hunger.
func Sleep(cur realm) string {
	if !cur.IsCurrent() {
		panic("spoofed realm")
	}
	return sleep(cur.Previous().Address(), runtime.ChainHeight())
}

// byAliveThenOwner ranks living pets before dead ones, then orders each
// group by owner address so the leaderboard is fully deterministic.
type byAliveThenOwner []*pet

func (r byAliveThenOwner) Len() int      { return len(r) }
func (r byAliveThenOwner) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
func (r byAliveThenOwner) Less(i, j int) bool {
	if r[i].alive != r[j].alive {
		return r[i].alive
	}
	return r[i].owner.String() < r[j].owner.String()
}

func bar(v int) string {
	filled := v / 10
	out := ""
	for i := 0; i < 10; i++ {
		if i < filled {
			out += "█"
		} else {
			out += "░"
		}
	}
	return out
}

func renderCard(p *pet, height int64) string {
	hunger, happiness, energy, alive := project(p, height)
	out := "## " + p.name + " — owned by " + ui.Addr(p.owner) + "\n\n"
	if !alive {
		out += "💀 **Deceased.** Owner can `Hatch(name)` a new pet.\n\n"
		return out
	}
	out += ageStageName(p.born, height) + " · age **" + strconv.Itoa(int(height-p.born)) + "** blocks\n\n"
	out += "- Hunger:    " + bar(100-hunger) + " (" + strconv.Itoa(hunger) + "/100 — lower is better)\n"
	out += "- Happiness: " + bar(happiness) + " (" + strconv.Itoa(happiness) + "/100)\n"
	out += "- Energy:    " + bar(energy) + " (" + strconv.Itoa(energy) + "/100)\n\n"
	return out
}

// Render shows either every pet ever hatched (path == "") or a single pet's
// detail card when path is a bech32 owner address.
func Render(path string) string {
	height := runtime.ChainHeight()

	out := "# 🐣 Tamagotchi\n\n"
	out += "A tiny on-chain pet. `Hatch(\"name\")` to start, then keep it alive with " +
		"`Feed()`, `Play()` and `Sleep()` — stats decay every block, so neglect kills it.\n\n"

	if path != "" {
		owner := address(path)
		p, ok := get(owner)
		if !ok {
			return out + "_No pet found for " + md.InlineCode(path) + "._\n"
		}
		return out + renderCard(p, height)
	}

	var rows []*pet
	pets.Iterate("", "", func(_ string, v any) bool {
		rows = append(rows, v.(*pet))
		return false
	})
	if len(rows) == 0 {
		out += "_No pets hatched yet. Be the first!_\n"
		return out
	}
	sort.Stable(byAliveThenOwner(rows))

	out += "| Pet | Owner | Status | Feeds | Plays | Deaths |\n"
	out += "| :--- | :--- | :--- | ---: | ---: | ---: |\n"
	for _, p := range rows {
		_, _, _, alive := project(p, height)
		status := "🐤 alive"
		if !alive {
			status = "💀 dead"
		}
		out += "| " + p.name + " | " + ui.Addr(p.owner) + " | " + status +
			" | " + strconv.Itoa(p.feeds) + " | " + strconv.Itoa(p.plays) +
			" | " + strconv.Itoa(p.deaths) + " |\n"
	}
	out += "\n_View a single pet at `?<owner-address>`._\n"
	return out
}

tamagotchi_test.gno

package tamagotchi

import (
	"strings"
	"testing"

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

func resetState() {
	pets = avl.Tree{}
}

func TestClamp(t *testing.T) {
	if clamp(150, 0, 100) != 100 {
		t.Fatal("clamp should cap at hi")
	}
	if clamp(-5, 0, 100) != 0 {
		t.Fatal("clamp should floor at lo")
	}
	if clamp(50, 0, 100) != 50 {
		t.Fatal("clamp should pass through in-range values")
	}
}

func TestHatchCreatesLivingPet(t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")

	hatch(alice, "Fluffy", 100)

	p, ok := get(alice)
	if !ok || !p.alive {
		t.Fatal("expected a living pet after hatch")
	}
	if p.name != "Fluffy" {
		t.Fatalf("expected name Fluffy, got %s", p.name)
	}
}

func TestHatchTwiceWhileAlivePanics(t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	hatch(alice, "Fluffy", 100)

	defer func() {
		if r := recover(); r == nil {
			t.Fatal("expected panic hatching a second living pet")
		}
	}()
	hatch(alice, "Again", 101)
}

func TestHatchAfterDeathKeepsLifetimeStats(t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	hatch(alice, "Fluffy", 0)
	feed(alice, 0)

	p, _ := get(alice)
	p.alive = false
	p.deaths = 1

	hatch(alice, "Fluffy2", 10)

	p, _ = get(alice)
	if p.feeds != 1 || p.deaths != 1 {
		t.Fatalf("expected lifetime stats to carry over, got feeds=%d deaths=%d", p.feeds, p.deaths)
	}
	if !p.alive {
		t.Fatal("expected the new pet to be alive")
	}
}

func TestFeedReducesHunger(t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	hatch(alice, "Fluffy", 100)

	p, _ := get(alice)
	p.hunger = 60

	feed(alice, 100)
	if p.hunger != 30 {
		t.Fatalf("expected hunger 30 after feed, got %d", p.hunger)
	}
	if p.feeds != 1 {
		t.Fatalf("expected feeds counter to increment, got %d", p.feeds)
	}
}

func TestPlayRefusesWhenTooTired(t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	hatch(alice, "Fluffy", 100)

	p, _ := get(alice)
	p.energy = 5

	out := play(alice, 100)
	if !strings.Contains(out, "too tired") {
		t.Fatalf("expected too-tired message, got %q", out)
	}
	if p.plays != 0 {
		t.Fatal("play should not have counted while too tired")
	}
}

func TestNeglectKillsPet(t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	hatch(alice, "Fluffy", 0)

	defer func() {
		if r := recover(); r == nil {
			t.Fatal("expected panic acting on a neglected/dead pet")
		}
	}()
	// Feed re-ticks against a much later height, starving the pet to death.
	feed(alice, 1000)
}

func TestFeedWithoutPetPanics(t *testing.T) {
	resetState()
	bob := testutils.TestAddress("bob")

	defer func() {
		if r := recover(); r == nil {
			t.Fatal("expected panic feeding without a pet")
		}
	}()
	feed(bob, 100)
}

func TestRenderShowsEmptyThenPet(t *testing.T) {
	resetState()
	if !strings.Contains(Render(""), "No pets hatched yet") {
		t.Fatal("expected empty-state placeholder")
	}

	alice := testutils.TestAddress("alice")
	hatch(alice, "Fluffy", 100)

	out := Render("")
	if !strings.Contains(out, "Fluffy") {
		t.Fatal("expected pet name in leaderboard render")
	}

	detail := Render(alice.String())
	if !strings.Contains(detail, "Hunger") {
		t.Fatal("expected detail card to show hunger stat")
	}
}

// TestHatchViaCrossingCall smoke-tests the exported, realm-crossing entry
// point end to end (as an on-chain caller would invoke it).
func TestHatchViaCrossingCall(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	msg := Hatch(cross(cur), "Fluffy")
	if !strings.Contains(msg, "hatched") {
		t.Fatalf("expected hatch confirmation, got %q", msg)
	}
	if _, ok := get(alice); !ok {
		t.Fatal("expected pet to be persisted for caller")
	}
}

// decayOver ticks one pet from full stats across `blocks` blocks, calling tick
// every `every` blocks, and returns what it is left with. It drives tick
// directly rather than through Feed/Play/Sleep, because those also restore
// stats and the question here is only what decay does.
func decayOver(blocks, every int) (hunger, happiness, energy int) {
	p := &pet{alive: true, hunger: 0, happiness: 100, energy: 100, lastUpdate: 0}
	for h := every; h <= blocks; h += every {
		p.tick(int64(h))
	}
	return p.hunger, p.happiness, p.energy
}

// TestDecayDoesNotDependOnCallFrequency is the bug this file exists for.
//
// happiness decays once per 2 blocks and energy once per 3, by integer
// division. Before the carried debt, that division truncated on EVERY call, so
// ticking once per block cost 1/2 = 0 happiness and 1/3 = 0 energy, forever: a
// pet fed in a `while true` loop was immortal while everyone else's died. The
// leaderboard rewarded a bot, which is the opposite of what the realm claims.
//
// Over the same 60 blocks the outcome must now be the same whether the owner
// acts every block or once at the end.
func TestDecayDoesNotDependOnCallFrequency(t *testing.T) {
	const blocks = 60
	wantHunger, wantHappy, wantEnergy := decayOver(blocks, blocks)

	for _, every := range []int{1, 2, 3, 5, 30} {
		h, hap, e := decayOver(blocks, every)
		if h != wantHunger || hap != wantHappy || e != wantEnergy {
			t.Errorf("acting every %d block(s) over %d blocks: hunger=%d happiness=%d energy=%d, "+
				"want %d/%d/%d as when acting once",
				every, blocks, h, hap, e, wantHunger, wantHappy, wantEnergy)
		}
	}
}

// The absolute numbers, so a future change to the rates is a deliberate edit
// and not a silent one: 60 blocks costs 60 hunger, 30 happiness, 20 energy.
func TestDecayRates(t *testing.T) {
	h, hap, e := decayOver(60, 1)
	if h != 60 || hap != 70 || e != 80 {
		t.Errorf("60 blocks of decay = hunger %d, happiness %d, energy %d; want 60, 70, 80", h, hap, e)
	}
}

// project draws the page; tick decides the outcome. If they disagree, the pet a
// reader sees is not the pet the next call will act on.
func TestProjectAgreesWithTick(t *testing.T) {
	for _, every := range []int{1, 2, 3, 7} {
		p := &pet{alive: true, hunger: 0, happiness: 100, energy: 100, lastUpdate: 0}
		for h := every; h <= 42; h += every {
			p.tick(int64(h))
		}
		// One more step, projected rather than applied.
		ph, phap, pe, _ := project(p, int64(42+every))
		p.tick(int64(42 + every))
		if ph != p.hunger || phap != p.happiness || pe != p.energy {
			t.Errorf("every %d: project says %d/%d/%d, tick says %d/%d/%d",
				every, ph, phap, pe, p.hunger, p.happiness, p.energy)
		}
	}
}