Playground
bullscows.gno
// Package bullscows is a shared on-chain Bulls & Cows puzzle: one secret
// 4-digit code (distinct digits) per round, guessed cooperatively/competitively
// by anyone who calls Guess. Bulls = right digit, right spot. Cows = right
// digit, wrong spot. Whoever hits 4 bulls wins the round and a leaderboard
// entry; a fresh secret is drawn immediately after.
package bullscows
import (
"chain/runtime"
"strconv"
"strings"
"gno.land/p/nym-moultest123/kit/ui/v0"
)
const (
maxHistory = 10
maxRecords = 5
)
type guessLog struct {
player string
guess string
bulls int
cows int
}
type record struct {
player string
attempts int
round int
}
var (
secret [4]int
round int
attempts int
history []guessLog
records []record
)
func init() {
round = 1
secret = newSecret(seedFor(round))
}
// seedFor derives a per-round PRNG seed from the current chain height so
// nobody can precompute the next secret before the round actually starts.
func seedFor(r int) int64 {
return runtime.ChainHeight()*1000003 + int64(r)*7919 + 17
}
// nextRand is a minimal LCG (glibc constants) — no crypto strength needed
// for a casual puzzle, just enough spread across digits.
func nextRand(seed int64) int64 {
return (seed*1103515245 + 12345) & 0x7fffffff
}
func newSecret(seed int64) [4]int {
var used [10]bool
var digits [4]int
s := seed
for i := 0; i < 4; i++ {
for {
s = nextRand(s)
d := int(s % 10)
if !used[d] {
used[d] = true
digits[i] = d
break
}
}
}
return digits
}
// parseGuess validates a 4-digit, distinct-digit guess string.
func parseGuess(guess string) ([4]int, bool) {
var out [4]int
if len(guess) != 4 {
return out, false
}
var used [10]bool
for i := 0; i < 4; i++ {
c := guess[i]
if c < '0' || c > '9' {
return out, false
}
d := int(c - '0')
if used[d] {
return out, false
}
used[d] = true
out[i] = d
}
return out, true
}
// score returns (bulls, cows) for guess against target, assuming both have
// distinct digits (guaranteed by parseGuess / newSecret).
func score(target, guess [4]int) (int, int) {
bulls, cows := 0, 0
for i := 0; i < 4; i++ {
if guess[i] == target[i] {
bulls++
continue
}
for j := 0; j < 4; j++ {
if i != j && guess[i] == target[j] {
cows++
break
}
}
}
return bulls, cows
}
func addHistory(l guessLog) {
history = append(history, l)
if len(history) > maxHistory {
history = history[len(history)-maxHistory:]
}
}
// addRecord keeps the top maxRecords fastest solves, ascending by attempts.
func addRecord(r record) {
records = append(records, r)
for i := len(records) - 1; i > 0 && records[i].attempts < records[i-1].attempts; i-- {
records[i], records[i-1] = records[i-1], records[i]
}
if len(records) > maxRecords {
records = records[:maxRecords]
}
}
func startNewRound() {
round++
attempts = 0
history = nil
secret = newSecret(seedFor(round))
}
// Guess submits a 4-distinct-digit code against the current round's secret.
// Returns the bulls/cows feedback, or "solved!" text when it's a win.
func Guess(cur realm, guess string) string {
digits, ok := parseGuess(guess)
if !ok {
panic("guess must be 4 digits, 0-9, no repeats (e.g. \"1972\")")
}
player := cur.Previous().Address().String()
attempts++
bulls, cows := score(secret, digits)
addHistory(guessLog{player: player, guess: guess, bulls: bulls, cows: cows})
if bulls == 4 {
wonRound := round
wonAttempts := attempts
addRecord(record{player: player, attempts: wonAttempts, round: wonRound})
startNewRound()
return "*** SOLVED *** " + guess + " was it — round " + strconv.Itoa(wonRound) +
" cracked in " + strconv.Itoa(wonAttempts) + " guesses. New round " +
strconv.Itoa(round) + " has begun, good luck!"
}
return guess + " -> " + strconv.Itoa(bulls) + " bulls, " + strconv.Itoa(cows) + " cows"
}
// GiveUp reveals the current secret and starts a fresh round without
// awarding a leaderboard record.
func GiveUp(cur realm) string {
revealed := digitsToString(secret)
oldRound := round
startNewRound()
return "round " + strconv.Itoa(oldRound) + "'s code was " + revealed +
" — round " + strconv.Itoa(round) + " is live now."
}
func digitsToString(d [4]int) string {
var sb strings.Builder
for _, v := range d {
sb.WriteString(strconv.Itoa(v))
}
return sb.String()
}
func Render(path string) string {
var sb strings.Builder
sb.WriteString("# Bulls & Cows\n\n")
sb.WriteString("One shared secret 4-digit code (no repeated digits). Call `Guess(\"1972\")` ")
sb.WriteString("to get **bulls** (right digit, right spot) and **cows** (right digit, wrong spot). ")
sb.WriteString("First to 4 bulls wins the round; `GiveUp()` reveals the code and starts over.\n\n")
sb.WriteString("## Round " + strconv.Itoa(round) + "\n\n")
sb.WriteString("Attempts so far: **" + strconv.Itoa(attempts) + "**\n\n")
if len(history) == 0 {
sb.WriteString("_No guesses yet this round — be the first._\n\n")
} else {
sb.WriteString("### Recent guesses\n\n")
sb.WriteString("| player | guess | bulls | cows |\n|---|---|---|---|\n")
for i := len(history) - 1; i >= 0; i-- {
h := history[i]
sb.WriteString("| " + ui.AddrOf(h.player) + " | " + h.guess + " | " +
strconv.Itoa(h.bulls) + " | " + strconv.Itoa(h.cows) + " |\n")
}
sb.WriteString("\n")
}
sb.WriteString("## Leaderboard (fastest solves)\n\n")
if len(records) == 0 {
sb.WriteString("_Nobody has cracked a code yet._\n")
} else {
sb.WriteString("| rank | player | attempts | round |\n|---|---|---|---|\n")
for i, r := range records {
sb.WriteString("| " + strconv.Itoa(i+1) + " | " + ui.AddrOf(r.player) + " | " +
strconv.Itoa(r.attempts) + " | " + strconv.Itoa(r.round) + " |\n")
}
}
return sb.String()
}
bullscows_test.gno
package bullscows
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
)
func TestParseGuess(t *testing.T) {
cases := []struct {
in string
ok bool
}{
{"1972", true},
{"0123", true},
{"11 2", false},
{"123", false},
{"12345", false},
{"1123", false}, // repeated digit
{"12a3", false},
}
for _, c := range cases {
if _, ok := parseGuess(c.in); ok != c.ok {
t.Fatalf("parseGuess(%q) ok = %v, want %v", c.in, ok, c.ok)
}
}
}
func TestScore(t *testing.T) {
target := [4]int{1, 9, 7, 2}
if b, c := score(target, [4]int{1, 9, 7, 2}); b != 4 || c != 0 {
t.Fatalf("exact match: got bulls=%d cows=%d, want 4/0", b, c)
}
if b, c := score(target, [4]int{2, 7, 9, 1}); b != 0 || c != 4 {
t.Fatalf("full rotation: got bulls=%d cows=%d, want 0/4", b, c)
}
if b, c := score(target, [4]int{1, 3, 4, 5}); b != 1 || c != 0 {
t.Fatalf("one bull: got bulls=%d cows=%d, want 1/0", b, c)
}
if b, c := score(target, [4]int{5, 6, 7, 8}); b != 1 || c != 0 {
t.Fatalf("no overlap but position 7: got bulls=%d cows=%d, want 1/0", b, c)
}
}
func TestNewSecretDistinctDigits(t *testing.T) {
for seed := int64(0); seed < 50; seed++ {
d := newSecret(seed)
var seen [10]bool
for _, v := range d {
if v < 0 || v > 9 {
t.Fatalf("digit out of range: %d", v)
}
if seen[v] {
t.Fatalf("newSecret(%d) = %v has repeated digit", seed, d)
}
seen[v] = true
}
}
}
func TestAddRecordKeepsFastestSorted(t *testing.T) {
records = nil
addRecord(record{player: "a", attempts: 10, round: 1})
addRecord(record{player: "b", attempts: 3, round: 2})
addRecord(record{player: "c", attempts: 7, round: 3})
addRecord(record{player: "d", attempts: 1, round: 4})
addRecord(record{player: "e", attempts: 9, round: 5})
addRecord(record{player: "f", attempts: 2, round: 6}) // pushes out the worst
if len(records) != maxRecords {
t.Fatalf("len(records) = %d, want %d", len(records), maxRecords)
}
want := []int{1, 2, 3, 7, 9}
for i, w := range want {
if records[i].attempts != w {
t.Fatalf("records[%d].attempts = %d, want %d", i, records[i].attempts, w)
}
}
}
func TestAddHistoryCaps(t *testing.T) {
history = nil
for i := 0; i < maxHistory+5; i++ {
addHistory(guessLog{player: "p", guess: strconv.Itoa(i), bulls: 0, cows: 0})
}
if len(history) != maxHistory {
t.Fatalf("len(history) = %d, want %d", len(history), maxHistory)
}
if history[len(history)-1].guess != strconv.Itoa(maxHistory+4) {
t.Fatalf("history did not keep the most recent entries")
}
}
// Crossing: Guess mutates realm state, needs cur realm + cross(cur).
func TestGuessRoundtrip(cur realm, t *testing.T) {
alice := testutils.TestAddress("alice")
testing.SetRealm(testing.NewUserRealm(alice))
round = 1
attempts = 0
history = nil
records = nil
secret = [4]int{1, 9, 7, 2}
out := Guess(cross(cur), "1234")
if !strings.Contains(out, "bulls") {
t.Fatalf("Guess() = %q, want bulls/cows feedback", out)
}
if attempts != 1 {
t.Fatalf("attempts = %d, want 1", attempts)
}
testing.SetRealm(testing.NewUserRealm(alice))
out = Guess(cross(cur), "1972")
if !strings.Contains(out, "SOLVED") {
t.Fatalf("Guess() = %q, want a solved message", out)
}
if round != 2 {
t.Fatalf("round = %d, want 2 (new round should start on solve)", round)
}
if len(records) != 1 || records[0].attempts != 2 {
t.Fatalf("records = %v, want one entry with attempts=2", records)
}
}
func TestGiveUpStartsNewRound(cur realm, t *testing.T) {
round = 1
attempts = 3
secret = [4]int{4, 5, 6, 7}
out := GiveUp(cross(cur))
if !strings.Contains(out, "4567") {
t.Fatalf("GiveUp() = %q, want it to reveal 4567", out)
}
if round != 2 || attempts != 0 {
t.Fatalf("round=%d attempts=%d, want round=2 attempts=0", round, attempts)
}
}
gnomod.toml
module = "gno.land/r/nym-moultest123/x/daily/bullscows/v1" gno = "0.9" private = true [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186413 max_deposit = "7000000ugnot"
render_test.gno
package bullscows
import (
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
// clear restores the globals to their init() state so assertions do not depend
// on which tests ran first. Realm globals live for the whole test binary.
func clear() {
round = 1
attempts = 0
history = nil
records = nil
secret = newSecret(seedFor(round))
}
// ExampleRender pins the fresh-round view: no guesses, empty leaderboard.
func ExampleRender() {
clear()
print(Render(""))
// Output:
// # Bulls & Cows
//
// One shared secret 4-digit code (no repeated digits). Call `Guess("1972")` to get **bulls** (right digit, right spot) and **cows** (right digit, wrong spot). First to 4 bulls wins the round; `GiveUp()` reveals the code and starts over.
//
// ## Round 1
//
// Attempts so far: **0**
//
// _No guesses yet this round — be the first._
//
// ## Leaderboard (fastest solves)
//
// _Nobody has cracked a code yet._
}
// TestRenderHistoryNewestFirst checks the guess table is reverse-chronological.
func TestRenderHistoryNewestFirst(t *testing.T) {
clear()
addHistory(guessLog{player: "alice", guess: "1234", bulls: 1, cows: 2})
addHistory(guessLog{player: "bob", guess: "5678", bulls: 0, cows: 1})
out := Render("")
uassert.True(t, strings.Contains(out, "### Recent guesses"), "history section should appear")
uassert.True(t, strings.Contains(out, "| `bob` | 5678 | 0 | 1 |\n| `alice` | 1234 | 1 | 2 |\n"),
"newest guess should be listed first")
uassert.False(t, strings.Contains(out, "_No guesses yet"), "empty-history notice should be gone")
}
// TestRenderLeaderboard checks solved records render in rank order.
func TestRenderLeaderboard(t *testing.T) {
clear()
addRecord(record{player: "carol", attempts: 3, round: 1})
addRecord(record{player: "dave", attempts: 7, round: 2})
out := Render("")
uassert.True(t, strings.Contains(out, "| 1 | `carol` | 3 | 1 |\n| 2 | `dave` | 7 | 2 |\n"),
"leaderboard should rank fastest first")
uassert.False(t, strings.Contains(out, "_Nobody has cracked a code yet._"),
"empty-leaderboard notice should be gone")
}
// TestRenderShortensLongAddresses checks the bech32 addresses players actually
// have get elided rather than blowing out the table.
func TestRenderShortensLongAddresses(t *testing.T) {
clear()
long := "g1manfred47kzduec920z88wfr64ylksmdcedlf5"
addHistory(guessLog{player: long, guess: "1234", bulls: 0, cows: 0})
out := Render("")
uassert.False(t, strings.Contains(out, long), "full address should not be rendered")
uassert.True(t, strings.Contains(out, "| `"+long[:8]+"…"+long[len(long)-4:]+"` | 1234 |"),
"address should be shortened to prefix…suffix")
}
// TestRenderTracksRoundAndAttempts checks the counters reach the page.
func TestRenderTracksRoundAndAttempts(t *testing.T) {
clear()
round = 4
attempts = 11
out := Render("")
uassert.True(t, strings.Contains(out, "## Round 4\n"), "round should be shown")
uassert.True(t, strings.Contains(out, "Attempts so far: **11**"), "attempts should be shown")
}
// TestRenderIgnoresPath documents that Render has no sub-routes.
func TestRenderIgnoresPath(t *testing.T) {
clear()
uassert.Equal(t, Render(""), Render("/anything"))
}