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

closestguess.gno

// Package closestguess is a blind, multiplayer number-guessing puzzle.
//
// Unlike a classic higher/lower guessing game, closestguess gives NO feedback
// per guess. Each round hides a target in 1..1000 (derived deterministically
// from the block height the round started at); every address may submit
// exactly one blind Guess for the round. Whenever someone calls Reveal, the
// round closes: the target is disclosed, the guess with the smallest absolute
// distance wins (ties go to whoever guessed first), the winner is recorded on
// the leaderboard, and a fresh round starts immediately.
package closestguess

import (
	"strconv"
	"strings"

	"chain"
	"chain/runtime"
)

const (
	minTarget = 1
	maxTarget = 1000
)

// roundT holds the mutable state of the open round. The target stays hidden
// (never rendered, never returned) until Reveal closes the round.
type roundT struct {
	number      int
	startHeight int64
	target      int
}

// winRecord is one closed-round result, kept for the leaderboard.
type winRecord struct {
	round    int
	winner   string
	target   int
	guess    int
	distance int
	players  int
}

// guessEntry is one address's blind guess for the current round.
type guessEntry struct {
	addr string
	n    int
}

var (
	current *roundT
	// entries holds one guessEntry per address for the CURRENT round only, in
	// submission order (so Reveal can break distance ties in favor of
	// whoever guessed first). Reset on every Reveal. A plain slice is fine
	// here: rounds are player-scoped and small, unlike long-lived global
	// state where avl.Tree would matter.
	entries []guessEntry
	// leaderboard is append-only across all rounds; sorted on render.
	leaderboard []winRecord
)

func init() {
	current = newRound(1, runtime.ChainHeight())
}

// newRound builds a fresh round whose hidden target derives deterministically
// from the start height and round number. Gno has no runtime RNG, so mixing
// height with the round number is the only available entropy, and it also
// keeps consecutive rounds at the same height from repeating a target.
func newRound(number int, height int64) *roundT {
	return &roundT{
		number:      number,
		startHeight: height,
		target:      targetFromHeight(height, number),
	}
}

func targetFromHeight(h int64, round int) int {
	if h < 0 {
		h = -h
	}
	span := int64(maxTarget - minTarget + 1)
	mixed := h*2654435761 + int64(round)*40503 + 12345
	if mixed < 0 {
		mixed = -mixed
	}
	return int(mixed%span) + minTarget
}

// Guess records the caller's single blind guess for the current round. It
// returns no hint about correctness — that is the whole point of the puzzle.
// Crossing function: caller invokes as Guess(cross(cur), n).
func Guess(cur realm, n int) string {
	if n < minTarget || n > maxTarget {
		panic("guess must be in " + strconv.Itoa(minTarget) + ".." + strconv.Itoa(maxTarget))
	}

	caller := cur.Previous().Address().String()
	if hasGuessed(caller) {
		panic("you already guessed this round; wait for Reveal()")
	}

	entries = append(entries, guessEntry{addr: caller, n: n})

	chain.Emit("GuessSubmitted",
		"round", strconv.Itoa(current.number),
		"player", caller,
	)

	return "guess recorded for round " + strconv.Itoa(current.number) + " (" +
		strconv.Itoa(len(entries)) + " player(s) so far) — call Reveal() to see who's closest"
}

func hasGuessed(addr string) bool {
	for _, e := range entries {
		if e.addr == addr {
			return true
		}
	}
	return false
}

// Reveal closes the current round: discloses the target, crowns whoever
// landed closest (ties favor the earliest guesser), records a leaderboard
// entry, and opens a fresh round. Panics if nobody has guessed yet.
// Crossing function.
func Reveal(cur realm) string {
	if len(entries) == 0 {
		panic("no guesses submitted yet this round")
	}

	target := current.target
	winner := entries[0]
	best := distance(winner.n, target)
	for _, e := range entries[1:] {
		if d := distance(e.n, target); d < best {
			best = d
			winner = e
		}
	}

	rec := winRecord{
		round:    current.number,
		winner:   winner.addr,
		target:   target,
		guess:    winner.n,
		distance: best,
		players:  len(entries),
	}
	leaderboard = append(leaderboard, rec)

	chain.Emit("RoundRevealed",
		"round", strconv.Itoa(rec.round),
		"winner", winner.addr,
		"target", strconv.Itoa(target),
		"distance", strconv.Itoa(best),
	)

	closedRound := current.number
	current = newRound(closedRound+1, runtime.ChainHeight())
	entries = nil

	return "round " + strconv.Itoa(closedRound) + " revealed: target was " + strconv.Itoa(target) +
		" — " + shortAddr(winner.addr) + " wins, guessed " + strconv.Itoa(winner.n) +
		" (distance " + strconv.Itoa(best) + ") among " + strconv.Itoa(rec.players) +
		" player(s). Round " + strconv.Itoa(current.number) + " is now open."
}

func distance(guess, target int) int {
	d := guess - target
	if d < 0 {
		d = -d
	}
	return d
}

// Render produces the gnoweb Markdown view. The current round's target and
// individual guess values are never shown — only the player count — so
// rendering the page can't leak the puzzle.
func Render(path string) string {
	var b strings.Builder

	b.WriteString("# Closest Guess\n\n")
	b.WriteString("A blind, multiplayer number-guessing puzzle. Each round hides a target in ")
	b.WriteString("**" + strconv.Itoa(minTarget) + ".." + strconv.Itoa(maxTarget) + "**. ")
	b.WriteString("Call `Guess(n)` once per round — you get no feedback. ")
	b.WriteString("Anyone can call `Reveal()` to close the round: the target is disclosed and ")
	b.WriteString("whoever landed closest wins.\n\n")

	b.WriteString("## Current round\n\n")
	b.WriteString("- Round: **" + strconv.Itoa(current.number) + "**\n")
	b.WriteString("- Started at block height: " + strconv.FormatInt(current.startHeight, 10) + "\n")
	b.WriteString("- Players guessed so far: " + strconv.Itoa(len(entries)) + "\n")
	b.WriteString("- Status: **open** — target hidden until `Reveal()` is called.\n\n")

	b.WriteString("## Leaderboard (closest-ever wins)\n\n")
	b.WriteString(renderLeaderboard())

	b.WriteString("\n## How to play\n\n")
	b.WriteString("```\n")
	b.WriteString("Guess(n)   // n in 1..1000, one shot per address per round, no feedback\n")
	b.WriteString("Reveal()   // closes the round: reveals target, crowns the closest guess\n")
	b.WriteString("```\n")

	return b.String()
}

// renderLeaderboard formats closed rounds ranked by smallest distance (ties:
// earlier round first). Sorted on a copy so state is untouched.
func renderLeaderboard() string {
	if len(leaderboard) == 0 {
		return "_No round has been revealed yet — be the first to call `Reveal()`!_\n"
	}

	ranked := make([]winRecord, len(leaderboard))
	copy(ranked, leaderboard)
	sortByClosest(ranked)

	var b strings.Builder
	b.WriteString("| Rank | Player | Round | Target | Guess | Distance | Players |\n")
	b.WriteString("|---|---|---|---|---|---|---|\n")
	for i, w := range ranked {
		b.WriteString("| " + strconv.Itoa(i+1) + " | `" + shortAddr(w.winner) + "` | " +
			strconv.Itoa(w.round) + " | " + strconv.Itoa(w.target) + " | " +
			strconv.Itoa(w.guess) + " | " + strconv.Itoa(w.distance) + " | " +
			strconv.Itoa(w.players) + " |\n")
	}
	return b.String()
}

// sortByClosest does an in-place insertion sort: smallest distance first,
// then earlier round first on ties. Small n; insertion sort keeps it
// deterministic and dependency-free.
func sortByClosest(rs []winRecord) {
	for i := 1; i < len(rs); i++ {
		j := i
		for j > 0 && closer(rs[j], rs[j-1]) {
			rs[j], rs[j-1] = rs[j-1], rs[j]
			j--
		}
	}
}

func closer(a, b winRecord) bool {
	if a.distance != b.distance {
		return a.distance < b.distance
	}
	return a.round < b.round
}

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

closestguess_test.gno

package closestguess

import (
	"strings"
	"testing"

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

// resetGame re-initializes package globals so each test starts clean; init()
// runs only once for the whole test binary.
func resetGame(height int64) {
	current = newRound(1, height)
	entries = nil
	leaderboard = nil
}

func TestTargetFromHeight(t *testing.T) {
	tests := []struct {
		name   string
		height int64
	}{
		{"zero", 0},
		{"one", 1},
		{"large", 123456},
		{"negative", -42},
	}
	for _, tt := range tests {
		got := targetFromHeight(tt.height, 1)
		if got < minTarget || got > maxTarget {
			t.Errorf("%s: targetFromHeight(%d,1)=%d, want in %d..%d", tt.name, tt.height, got, minTarget, maxTarget)
		}
		if again := targetFromHeight(tt.height, 1); again != got {
			t.Errorf("%s: non-deterministic: %d != %d", tt.name, again, got)
		}
	}

	// Different round numbers at the same height should (almost always) mix
	// to different targets, so consecutive rounds don't repeat.
	a := targetFromHeight(100, 1)
	b := targetFromHeight(100, 2)
	if a == b {
		t.Errorf("targetFromHeight(100,1) == targetFromHeight(100,2) == %d, want them to differ", a)
	}
}

func TestDistance(t *testing.T) {
	cases := []struct{ a, b, want int }{
		{5, 5, 0},
		{5, 8, 3},
		{8, 5, 3},
		{0, 1000, 1000},
	}
	for _, c := range cases {
		if got := distance(c.a, c.b); got != c.want {
			t.Errorf("distance(%d,%d) = %d, want %d", c.a, c.b, got, c.want)
		}
	}
}

// TestGuessRejectsOutOfRangeAndDuplicate exercises the crossing Guess
// function, so it takes cur realm and calls through cross(cur). A panic
// raised across the crossing call boundary isn't catchable by a plain
// defer/recover; revive() is the boundary-aware way to assert on it.
func TestGuessRejectsOutOfRangeAndDuplicate(cur realm, t *testing.T) {
	resetGame(10)

	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))
	if r := revive(func() { Guess(cross(cur), 0) }); r == nil {
		t.Error("Guess(0) should panic: out of range")
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	msg := Guess(cross(cur), 500)
	if !strings.Contains(msg, "recorded") {
		t.Errorf("Guess(500) = %q, want it to mention 'recorded'", msg)
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	if r := revive(func() { Guess(cross(cur), 501) }); r == nil {
		t.Error("second Guess from the same address should panic")
	}
}

// TestRevealPicksClosestAndStartsNewRound exercises Guess + Reveal together.
func TestRevealPicksClosestAndStartsNewRound(cur realm, t *testing.T) {
	resetGame(50)
	target := current.target
	prevRound := current.number

	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")

	far := target + 100
	if far > maxTarget {
		far = target - 100
	}
	if far < minTarget {
		far = minTarget
	}
	near := target + 1
	if near > maxTarget {
		near = target - 1
	}
	if near < minTarget {
		near = minTarget
	}

	testing.SetRealm(testing.NewUserRealm(alice))
	Guess(cross(cur), far)
	testing.SetRealm(testing.NewUserRealm(bob))
	Guess(cross(cur), near)

	msg := Reveal(cross(cur))
	if !strings.Contains(msg, "revealed") {
		t.Errorf("Reveal() = %q, want it to mention 'revealed'", msg)
	}
	if len(leaderboard) != 1 {
		t.Fatalf("leaderboard len = %d, want 1", len(leaderboard))
	}
	if leaderboard[0].winner != bob.String() {
		t.Errorf("winner = %q, want %q (closer guess)", leaderboard[0].winner, bob.String())
	}
	if current.number != prevRound+1 {
		t.Errorf("round number = %d, want %d", current.number, prevRound+1)
	}
	if len(entries) != 0 {
		t.Errorf("entries should reset after Reveal, got %d", len(entries))
	}
}

// TestRevealPanicsWithNoGuesses checks the panic path via revive() (see the
// note on TestGuessRejectsOutOfRangeAndDuplicate).
func TestRevealPanicsWithNoGuesses(cur realm, t *testing.T) {
	resetGame(1)
	if r := revive(func() { Reveal(cross(cur)) }); r == nil {
		t.Error("Reveal() with no guesses should panic")
	}
}

// TestRenderContainsState is a plain read — no cur.
func TestRenderContainsState(t *testing.T) {
	resetGame(3)
	out := Render("")
	for _, want := range []string{"Closest Guess", "Current round", "Leaderboard"} {
		if !strings.Contains(out, want) {
			t.Errorf("Render() missing %q", want)
		}
	}
}

gnomod.toml

module = "gno.land/r/nym-moultest123/x/daily/closestguess/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186407
  max_deposit = "6000000ugnot"