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/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/games/idle/v0"
gno = "0.9"
private = true

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

idle.gno

// Package idle is a mine that keeps working while you are not looking at it.
//
// Ore accrues at a rate set by your level. Claim banks it, Upgrade spends the
// bank to dig faster, and at level 10 you may Prestige: start over at level 1
// carrying a permanent multiplier. There are no turns, no block hook and no
// keeper. The realm stores what you had and when, and everything else is
// arithmetic done at the moment somebody asks.
//
// The three decisions that make it a game rather than a counter:
//
//  1. THE MINE IS SMALL. It holds two hours of production and then spills.
//     Without a ceiling the optimal play is to never log in and claim once at
//     the end, which is not a game, it is a savings account. The ceiling is
//     what makes showing up the skill, and it scales with the rate, so two
//     hours stays two hours at every level.
//  2. UPGRADES ARE QUADRATIC AGAINST LINEAR PRODUCTION. Level L costs
//     UpgradeBase*L*L and pays L per period, so the next level always takes
//     about UpgradeBase*L periods to afford: the curve bends without ever
//     stalling. Linear against linear never ends, and exponential against
//     linear dies at level four.
//  3. PRESTIGE EXISTS. Without a reset the leaderboard is settled by whoever
//     started first and nobody else has a reason to join. Trading a level-10
//     mine for a permanent multiplier means a player who starts today has a
//     reachable ceiling.
//
// Time is unix seconds from the block, not block height. A height-denominated
// economy silently repriced itself every time the chain's block time moved,
// and gno.land's has moved from about 4.1s to 3.405s inside a month.
//
// Nothing here rolls dice. Everything a player can do is a pure function of
// when they did it, so there is no block hash to grind and no ordering to
// front-run, and the page can tell you exactly what an action will produce
// before you sign it.
//
// The arithmetic is [p/moul/x/games/accrual](/p/moul/x/games/accrual/v0),
// which owns the one rule that makes lazy time honest: how often you claim
// must not change what you end up with.
package idle

import (
	"errors"
	"strconv"
	"time"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/games/accrual/v0"
	"gno.land/p/nt/avl/v0"
)

// The economy. Ore is a bare integer: there is no token here, and nothing
// leaves the realm.
const (
	// Period is one minute of unix time. A level-1 mine digs one ore a minute.
	Period = int64(60)
	// CapPeriods is how much production the mine holds before it spills, in
	// periods. It multiplies the rate, so the fill time is level-independent.
	CapPeriods = int64(120)
	// UpgradeBase sets the cost curve: level L costs UpgradeBase*L*L to leave.
	UpgradeBase = int64(10)
	// PrestigeAt is the level at which a reset becomes available.
	PrestigeAt = int64(10)
	// MaxLevel is a safety rail on the cost curve, not a mechanic: it is far
	// beyond anything reachable, and keeps every product inside int64.
	MaxLevel = int64(1000)
	// MaxPrestige bounds the multiplier for the same reason.
	MaxPrestige = int64(100)
)

var errNoMine = errors.New("idle: you have no mine yet, call Start first")

// mine is one player's state. pending and anchor are the accrual pair: what
// was in the mine, and as of when. Everything else is bookkeeping.
type mine struct {
	owner    address
	level    int64
	prestige int64
	pending  int64 // ore in the mine at anchor, capped
	anchor   int64 // unix seconds; the accrual clock, not "last seen"
	banked   int64 // claimed ore, spendable, uncapped
	lifetime int64 // every ore ever claimed, never reset by Prestige
	claims   int64
	started  int64
}

var mines avl.Tree // address string -> *mine

// now is the chain's own clock in unix seconds. time.Now() in a realm returns
// the block timestamp, so it is consensus-deterministic rather than wall time.
func now() int64 { return time.Now().Unix() }

// rate is the accrual Rate for a level and prestige. It is rebuilt on each
// call rather than stored, so a mine's stored state cannot disagree with the
// economy after a redeploy changes a constant.
func rate(level, prestige int64) accrual.Rate {
	perPeriod := level * (1 + prestige)
	r, err := accrual.New(perPeriod, Period, CapPeriods*perPeriod)
	if err != nil {
		panic("idle: " + err.Error())
	}
	return r
}

// upgradeCost is what it costs to leave the given level.
func upgradeCost(level int64) int64 { return UpgradeBase * level * level }

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

// settle moves the mine's clock to at, banking nothing. It is the only place
// that writes the accrual pair, and it is deliberately the same call Render
// makes read-only, so the page can never promise a number an action will not
// honour.
func (m *mine) settle(at int64) {
	pending, anchor, err := rate(m.level, m.prestige).Advance(m.pending, m.anchor, at)
	if err != nil {
		panic("idle: " + err.Error())
	}
	m.pending, m.anchor = pending, anchor
}

// view is settle without the write, for Render and for the read helpers.
func (m *mine) view(at int64) int64 {
	pending, err := rate(m.level, m.prestige).At(m.pending, m.anchor, at)
	if err != nil {
		panic("idle: " + err.Error())
	}
	return pending
}

// fullAt is the unix second at which this mine starts wasting production.
func (m *mine) fullAt(at int64) int64 {
	pending := m.view(at)
	full, err := rate(m.level, m.prestige).Full(pending, at)
	if err != nil {
		panic("idle: " + err.Error())
	}
	return full
}

// start opens a mine for owner. Non-crossing so tests can drive the clock.
func start(owner address, at int64) string {
	if _, ok := get(owner); ok {
		panic("idle: you already have a mine")
	}
	mines.Set(owner.String(), &mine{
		owner:   owner,
		level:   1,
		anchor:  at,
		started: at,
	})
	return "Mine opened at level 1. It digs " + strconv.FormatInt(Period, 10) +
		"s per ore and holds " + strconv.FormatInt(CapPeriods, 10) + " before it spills."
}

func mustGet(owner address) *mine {
	m, ok := get(owner)
	if !ok {
		panic(errNoMine.Error())
	}
	return m
}

// claim banks everything the mine has dug.
func claim(owner address, at int64) string {
	m := mustGet(owner)
	m.settle(at)
	if m.pending == 0 {
		panic("idle: nothing to claim yet")
	}
	got := m.pending
	m.pending = 0
	m.banked += got
	m.lifetime += got
	m.claims++
	return "Claimed " + strconv.FormatInt(got, 10) + " ore. Banked: " +
		strconv.FormatInt(m.banked, 10) + "."
}

// upgrade spends the bank to raise the level.
func upgrade(owner address, at int64) string {
	m := mustGet(owner)
	m.settle(at)
	if m.level >= MaxLevel {
		panic("idle: this mine is at the maximum level")
	}
	cost := upgradeCost(m.level)
	if m.banked < cost {
		panic("idle: upgrade costs " + strconv.FormatInt(cost, 10) +
			" ore, you have " + strconv.FormatInt(m.banked, 10))
	}
	m.banked -= cost
	m.level++
	return "Level " + strconv.FormatInt(m.level, 10) + ". Digging " +
		strconv.FormatInt(m.level*(1+m.prestige), 10) + " ore per period."
}

// prestige trades the mine for a permanent multiplier.
func prestige(owner address, at int64) string {
	m := mustGet(owner)
	m.settle(at)
	if m.level < PrestigeAt {
		panic("idle: prestige unlocks at level " + strconv.FormatInt(PrestigeAt, 10) +
			", you are at " + strconv.FormatInt(m.level, 10))
	}
	if m.prestige >= MaxPrestige {
		panic("idle: this mine is at the maximum prestige")
	}
	m.prestige++
	m.level = 1
	m.pending = 0
	m.banked = 0
	m.anchor = at
	return "Prestige " + strconv.FormatInt(m.prestige, 10) +
		". Back to level 1, digging " + strconv.FormatInt(1+m.prestige, 10) +
		" ore per period. Lifetime ore: " + strconv.FormatInt(m.lifetime, 10) + "."
}

// Start opens a mine for the caller. One per address, forever: Prestige is the
// only way to start over, and it keeps your lifetime total.
func Start(cur realm) string {
	return start(cur.Previous().Address(), now())
}

// Claim banks whatever the mine has dug since the last claim. Claiming often
// and claiming rarely pay exactly the same, by construction: see accrual.
func Claim(cur realm) string {
	return claim(cur.Previous().Address(), now())
}

// Upgrade spends banked ore to raise the level, which raises both the rate and
// the ceiling.
func Upgrade(cur realm) string {
	return upgrade(cur.Previous().Address(), now())
}

// Prestige resets a level-10 mine to level 1 for a permanent +1 multiplier.
// Banked and pending ore are burned; the lifetime total is not.
func Prestige(cur realm) string {
	return prestige(cur.Previous().Address(), now())
}

// Pending reports what is sitting in an address's mine right now, unclaimed.
func Pending(owner address) int64 {
	m, ok := get(owner)
	if !ok {
		return 0
	}
	return m.view(now())
}

// Banked reports an address's spendable ore.
func Banked(owner address) int64 {
	m, ok := get(owner)
	if !ok {
		return 0
	}
	return m.banked
}

// Level reports an address's level and prestige.
func Level(owner address) (int64, int64) {
	m, ok := get(owner)
	if !ok {
		return 0, 0
	}
	return m.level, m.prestige
}

// FullAt reports the unix second at which an address's mine starts wasting
// what it digs, which is the only deadline in this game.
func FullAt(owner address) int64 {
	m, ok := get(owner)
	if !ok {
		return 0
	}
	return m.fullAt(now())
}

idle_test.gno

package idle

import (
	"strings"
	"testing"

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

// reset clears the realm between tests. Package state carries over from one
// test to the next even though the block height does not, so every test that
// looks at the board has to start from a known tree.
func reset() { mines = avl.Tree{} }

// t0 is an arbitrary unix second to hang the tests off. Nothing asserts an
// absolute time, only differences from this one.
//
// It is only legal for the non-crossing helpers, which take the time as an
// argument. Anything reaching now() (Render and the read helpers) reads the
// BLOCK timestamp, which in a test is far below t0, so a mine anchored here
// would make the chain's clock look like it ran backwards. Those tests anchor
// at now() instead.
const t0 = int64(1700000000)

func TestStartOpensALevelOneMine(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")

	out := start(alice, t0)
	uassert.True(t, strings.Contains(out, "level 1"), "expected the opening message")

	m, ok := get(alice)
	uassert.True(t, ok, "expected a mine")
	uassert.Equal(t, int64(1), m.level)
	uassert.Equal(t, int64(0), m.prestige)
	uassert.Equal(t, t0, m.anchor)
	uassert.Equal(t, int64(0), m.pending)
}

func TestStartTwicePanics(cur realm, t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	uassert.PanicsContains(t, cur, "already have a mine", func() { start(alice, t0) })
}

func TestActingWithoutAMinePanics(cur realm, t *testing.T) {
	reset()
	bob := testutils.TestAddress("bob")
	uassert.PanicsContains(t, cur, "no mine yet", func() { claim(bob, t0) })
	uassert.PanicsContains(t, cur, "no mine yet", func() { upgrade(bob, t0) })
	uassert.PanicsContains(t, cur, "no mine yet", func() { prestige(bob, t0) })
}

func TestAccrualAndClaim(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)

	m, _ := get(alice)
	uassert.Equal(t, int64(0), m.view(t0+Period-1), "nothing before the first whole period")
	uassert.Equal(t, int64(1), m.view(t0+Period), "one ore after one period")
	uassert.Equal(t, int64(30), m.view(t0+30*Period))

	out := claim(alice, t0+30*Period)
	uassert.True(t, strings.Contains(out, "Claimed 30 ore"), "got: "+out)
	uassert.Equal(t, int64(30), m.banked)
	uassert.Equal(t, int64(30), m.lifetime)
	uassert.Equal(t, int64(0), m.pending)
	uassert.Equal(t, int64(1), m.claims)
}

func TestClaimingNothingPanics(cur realm, t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	uassert.PanicsContains(t, cur, "nothing to claim", func() { claim(alice, t0+Period-1) })
}

// TestClaimCadenceDoesNotMatter is the game-level statement of the invariant
// the accrual package exists for: two players who dig for the same span end up
// with the same ore whatever their claiming habits. A realm that re-anchored
// to now would pay the busy player less, and a realm that decayed would pay
// them more.
//
// "Whatever their habits" has exactly one limit, and it is the design rather
// than the arithmetic: a cadence longer than the mine takes to fill spills,
// and is meant to. Every cadence here stays under that, and
// TestTheMineSpills covers the other side.
func TestClaimCadenceDoesNotMatter(t *testing.T) {
	const span = 600 * Period
	fill := CapPeriods * Period

	for _, cadence := range []int64{Period, 2*Period + 1, 7 * Period, 599, 6001, fill} {
		if cadence > fill {
			t.Fatalf("cadence %d would spill, which is not what this test is about", cadence)
		}
		reset()
		alice := testutils.TestAddress("alice")
		start(alice, t0)
		m, _ := get(alice)

		for at := t0 + cadence; at <= t0+span; at += cadence {
			if m.view(at) > 0 {
				claim(alice, at)
			}
		}
		if m.view(t0+span) > 0 {
			claim(alice, t0+span)
		}
		uassert.Equal(t, int64(600), m.lifetime, "cadence changed the payout")
	}
}

// TestTheMineSpills pins the ceiling: production past the cap is lost, and
// coming back late is what costs you, which is decision 1 of the design.
func TestTheMineSpills(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	m, _ := get(alice)

	uassert.Equal(t, CapPeriods, m.view(t0+CapPeriods*Period), "full exactly at the cap")
	uassert.Equal(t, CapPeriods, m.view(t0+10*CapPeriods*Period), "and no more, ever")

	claim(alice, t0+10*CapPeriods*Period)
	uassert.Equal(t, CapPeriods, m.lifetime, "ten cap-fulls of absence paid one")
}

func TestFullAtIsTheOnlyDeadline(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	m, _ := get(alice)

	uassert.Equal(t, t0+CapPeriods*Period, m.fullAt(t0), "an empty mine fills in CapPeriods")

	half := t0 + (CapPeriods/2)*Period
	uassert.Equal(t, half+(CapPeriods/2)*Period, m.fullAt(half), "half full, half the time left")

	late := t0 + 99*CapPeriods*Period
	uassert.Equal(t, late, m.fullAt(late), "already full reads as now")
}

func TestUpgrade(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	m, _ := get(alice)

	uassert.Equal(t, UpgradeBase, upgradeCost(1))
	uassert.Equal(t, 4*UpgradeBase, upgradeCost(2))

	claim(alice, t0+UpgradeBase*Period)
	out := upgrade(alice, t0+UpgradeBase*Period)
	uassert.True(t, strings.Contains(out, "Level 2"), "got: "+out)
	uassert.Equal(t, int64(2), m.level)
	uassert.Equal(t, int64(0), m.banked, "the upgrade spent the bank")

	// The rate and the ceiling both doubled, so the fill time did not move.
	uassert.Equal(t, int64(2), rate(m.level, m.prestige).Amount)
	uassert.Equal(t, 2*CapPeriods, rate(m.level, m.prestige).Cap)
}

func TestUpgradeTooPoorPanics(cur realm, t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	uassert.PanicsContains(t, cur, "upgrade costs 10 ore, you have 0",
		func() { upgrade(alice, t0) })
}

func TestPrestigeIsLockedUntilLevelTen(cur realm, t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	uassert.PanicsContains(t, cur, "prestige unlocks at level 10",
		func() { prestige(alice, t0) })
}

func TestPrestigeResetsButKeepsLifetime(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)
	m, _ := get(alice)

	// Hand the mine to level 10 rather than grinding it, then bank something
	// so the reset has ore to burn.
	m.level = PrestigeAt
	claim(alice, t0+50*Period)
	banked, lifetime := m.banked, m.lifetime
	uassert.True(t, banked > 0, "expected ore to burn")

	out := prestige(alice, t0+50*Period)
	uassert.True(t, strings.Contains(out, "Prestige 1"), "got: "+out)
	uassert.Equal(t, int64(1), m.prestige)
	uassert.Equal(t, int64(1), m.level)
	uassert.Equal(t, int64(0), m.banked, "prestige burns the bank")
	uassert.Equal(t, int64(0), m.pending)
	uassert.Equal(t, lifetime, m.lifetime, "lifetime survives the reset")

	// A level-1 prestige-1 mine digs what a level-2 mine does.
	uassert.Equal(t, int64(2), rate(m.level, m.prestige).Amount)
}

func TestReadHelpersAreSafeOnAStranger(t *testing.T) {
	reset()
	carol := testutils.TestAddress("carol")
	uassert.Equal(t, int64(0), Pending(carol))
	uassert.Equal(t, int64(0), Banked(carol))
	uassert.Equal(t, int64(0), FullAt(carol))
	lvl, pre := Level(carol)
	uassert.Equal(t, int64(0), lvl)
	uassert.Equal(t, int64(0), pre)
}

func TestSpan(t *testing.T) {
	cases := []struct {
		secs int64
		want string
	}{
		{0, "0s"},
		{-5, "0s"},
		{1, "1s"},
		{59, "59s"},
		{60, "1m"},
		{61, "1m 1s"},
		{3600, "1h"},
		{3661, "1h 1m"},
		{86400, "1d"},
		{90061, "1d 1h"},
		{7200, "2h"},
	}
	for _, tc := range cases {
		uassert.Equal(t, tc.want, span(tc.secs), "span("+tc.want+")")
	}
}

func TestRenderBoard(t *testing.T) {
	reset()
	uassert.True(t, strings.Contains(board(t0), "Nobody is digging yet"),
		"expected the empty placeholder")

	alice := testutils.TestAddress("alice")
	start(alice, t0)
	out := board(t0 + 30*Period)
	uassert.True(t, strings.Contains(out, "The Mine"), "expected the title")
	uassert.True(t, strings.Contains(out, "30"), "expected the live pending figure")
	uassert.True(t, strings.Contains(out, "to spill"), "expected the spill countdown")
}

func TestRenderCard(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)

	out := card(alice, t0+30*Period)
	uassert.True(t, strings.Contains(out, "Level **1**"), "got: "+out)
	uassert.True(t, strings.Contains(out, "30 / 120"), "expected stock over cap")
	uassert.True(t, strings.Contains(out, "1h 30m"), "expected the spill countdown")
	uassert.True(t, strings.Contains(out, "10 short"), "expected the shortfall")
	uassert.True(t, strings.Contains(out, "9 to go"), "expected the prestige distance")

	full := card(alice, t0+999*Period)
	uassert.True(t, strings.Contains(full, "already full"), "expected the waste warning")

	bob := testutils.TestAddress("bob")
	uassert.True(t, strings.Contains(card(bob, t0), "No mine at"), "expected the stranger card")
}

// TestRenderIsLive is the property the whole design is for: the page changes
// with nothing but the passage of time, so gnoweb serves a live dashboard and
// no transaction was needed to move it.
func TestRenderIsLive(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	start(alice, t0)

	early := board(t0 + 10*Period)
	later := board(t0 + 20*Period)
	uassert.NotEqual(t, early, later, "the board did not move with time")
	uassert.Equal(t, int64(0), Pending(testutils.TestAddress("nobody")),
		"and reading it wrote nothing")
}

render.gno

package idle

import (
	"sort"
	"strconv"
	"strings"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
)

// Render shows every mine, or one mine's card at /r/.../idle:<address>.
//
// The numbers move on their own: the same URL renders differently a minute
// later because the mine kept digging, and nothing wrote to the chain in
// between. That is the whole point of the accrual pair, and it is why every
// figure here comes from the read-only view rather than from stored state.
func Render(path string) string {
	at := now()
	if addr := strings.TrimSpace(path); addr != "" {
		return card(address(addr), at)
	}
	return board(at)
}

// byLifetimeThenOwner ranks by lifetime ore, then by address so the order is
// identical on every node.
type byLifetimeThenOwner []*mine

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

func board(at int64) string {
	var b strings.Builder
	b.WriteString("# The Mine\n\n")
	b.WriteString("Ore accrues while you are away. The mine holds " +
		strconv.FormatInt(CapPeriods, 10) + " periods of production and then spills, so the only thing that costs you anything is not showing up.\n\n")

	all := []*mine{}
	mines.Iterate("", "", func(_ string, v any) bool {
		all = append(all, v.(*mine))
		return false
	})
	sort.Sort(byLifetimeThenOwner(all))

	t := ui.NewTable("#", "Miner", "Lv", "Prestige", "In the mine", "Banked", "Lifetime")
	for i, m := range all {
		pending := m.view(at)
		full := ""
		if r := m.fullAt(at); r > at {
			full = " (" + span(r-at) + " to spill)"
		} else {
			full = " (**full**)"
		}
		t.Row(
			ui.Podium(i)+strconv.Itoa(i+1),
			ui.Addr(m.owner),
			strconv.FormatInt(m.level, 10),
			strconv.FormatInt(m.prestige, 10),
			strconv.FormatInt(pending, 10)+full,
			strconv.FormatInt(m.banked, 10),
			strconv.FormatInt(m.lifetime, 10),
		)
	}
	b.WriteString(t.OrEmpty("Nobody is digging yet."))
	b.WriteString("\n")
	b.WriteString(ui.Join(" | ",
		ui.Action("Open a mine", "Start"),
		ui.Action("Claim", "Claim"),
		ui.Action("Upgrade", "Upgrade"),
		ui.Action("Prestige", "Prestige"),
	))
	b.WriteString("\n")
	return b.String()
}

func card(owner address, at int64) string {
	m, ok := get(owner)
	if !ok {
		return "# The Mine\n\n" + ui.Empty("No mine at "+ui.Addr(owner)+".")
	}

	pending := m.view(at)
	r := rate(m.level, m.prestige)
	var b strings.Builder

	b.WriteString("# " + ui.Addr(m.owner) + "'s mine\n\n")
	b.WriteString("Level **" + strconv.FormatInt(m.level, 10) + "**")
	if m.prestige > 0 {
		b.WriteString(", prestige **" + strconv.FormatInt(m.prestige, 10) + "**")
	}
	b.WriteString(", digging **" + strconv.FormatInt(r.Amount, 10) + "** ore every " +
		span(Period) + ".\n\n")

	t := ui.NewTable("", "")
	t.Row("In the mine", strconv.FormatInt(pending, 10)+" / "+strconv.FormatInt(r.Cap, 10))
	if full := m.fullAt(at); full > at {
		t.Row("Spills in", span(full-at))
	} else {
		t.Row("Spills in", "**already full, every period is being wasted**")
	}
	t.Row("Banked", strconv.FormatInt(m.banked, 10))
	t.Row("Lifetime ore", strconv.FormatInt(m.lifetime, 10))
	t.Row("Claims", strconv.FormatInt(m.claims, 10))
	t.Row("Digging for", span(at-m.started))
	if m.level < MaxLevel {
		cost := upgradeCost(m.level)
		short := cost - m.banked
		next := strconv.FormatInt(cost, 10) + " ore"
		if short > 0 {
			next += " (" + strconv.FormatInt(short, 10) + " short)"
		} else {
			next += " (**affordable now**)"
		}
		t.Row("Next level", next)
	}
	if m.prestige < MaxPrestige {
		if m.level >= PrestigeAt {
			t.Row("Prestige", "**available**, and it burns "+
				strconv.FormatInt(m.banked+pending, 10)+" ore")
		} else {
			t.Row("Prestige", "at level "+strconv.FormatInt(PrestigeAt, 10)+
				", "+strconv.FormatInt(PrestigeAt-m.level, 10)+" to go")
		}
	}
	b.WriteString(t.String())
	b.WriteString("\n")
	b.WriteString(ui.Join(" | ",
		ui.Action("Claim", "Claim"),
		ui.Action("Upgrade", "Upgrade"),
		ui.Action("Prestige", "Prestige"),
	))
	b.WriteString("\n")
	return b.String()
}

// span renders a number of seconds the way a player reads it. It rounds down
// and stops at two units, because "2h 3m 11s to spill" is noise when the
// question is whether to claim now or after lunch.
func span(secs int64) string {
	if secs <= 0 {
		return "0s"
	}
	units := []struct {
		size int64
		name string
	}{
		{86400, "d"},
		{3600, "h"},
		{60, "m"},
		{1, "s"},
	}
	parts := []string{}
	for i, u := range units {
		if secs < u.size {
			continue
		}
		n := secs / u.size
		secs -= n * u.size
		parts = append(parts, strconv.FormatInt(n, 10)+u.name)
		if len(parts) == 2 || i == len(units)-1 {
			break
		}
	}
	return strings.Join(parts, " ")
}

render_example_test.gno

package idle

import (
	"strings"
	"testing"

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

// TestRenderRoutes pins that Render dispatches on the path: empty is the
// board, anything else is read as an address.
func TestRenderRoutes(t *testing.T) {
	reset()
	alice := testutils.TestAddress("alice")
	// Anchored at the block clock, not at t0: Render reads now().
	start(alice, now())

	uassert.True(t, strings.Contains(Render(""), "The Mine"), "empty path is the board")
	uassert.True(t, strings.Contains(Render(alice.String()), "'s mine"), "an address is a card")
	uassert.True(t, strings.Contains(Render("  "+alice.String()+"  "), "'s mine"),
		"a padded address is still a card")
	uassert.True(t, strings.Contains(Render("g1nobody"), "No mine at"), "a stranger is handled")
}

// ExampleRender pins the realm's empty board. It resets the tree first because
// examples run after every Test in the package and would otherwise render
// whatever they left behind.
func ExampleRender() {
	reset()
	print(Render(""))
	// Output:
	// # The Mine
	//
	// Ore accrues while you are away. The mine holds 120 periods of production and then spills, so the only thing that costs you anything is not showing up.
	//
	// *Nobody is digging yet.*
	//
	// [Open a mine](/r/moul/x/games/idle/v0$help&func=Start) | [Claim](/r/moul/x/games/idle/v0$help&func=Claim) | [Upgrade](/r/moul/x/games/idle/v0$help&func=Upgrade) | [Prestige](/r/moul/x/games/idle/v0$help&func=Prestige)
}