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/daily/rpsoracle/v1"
gno = "0.9"
private = true

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

render_example_test.gno

package rpsoracle

// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
	print(Render(""))
	// Output:
	// # Rock-Paper-Scissors Oracle
	//
	// An adaptive opponent: it doesn't roll dice, it studies you. Every throw is logged, and the oracle always counters whichever move you've played most often. Play a uniform mixed strategy and it can't out-guess you; fall into a habit and it will.
	//
	// - Total rounds played: 0
	// - No one has beaten the oracle yet.
	//
	// ## How to play
	//
	// Call `Play("rock"|"paper"|"scissors")` (or `r`/`p`/`s`). View your own record at this realm's path plus your address, e.g. `.../rpsoracle:g1youraddress...`
}

rpsoracle.gno

// Package rpsoracle is a rock-paper-scissors opponent that doesn't roll
// dice: it studies each player's move history and always throws the
// counter to whichever move that player has favored most. Play a fixed
// pattern and the oracle punishes it; play close to a uniform 1/3-1/3-1/3
// mix and it can't out-guess you better than chance.
package rpsoracle

import (
	"strconv"
	"strings"

	"chain"
	"chain/runtime"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rps/v0"
	"gno.land/p/nt/avl/v0"
)

// beats returns the move that defeats m.
func beats(m rps.Move) rps.Move {
	return rps.Move((int(m) + 1) % 3)
}

// playerState is the persisted record for one address.
type playerState struct {
	Counts     [3]int // history tally per move, what the oracle predicts from
	Rounds     int
	Wins       int // player beat the oracle
	Losses     int // oracle beat the player
	Draws      int
	BestStreak int
	streak     int // current player win streak against the oracle
}

var (
	players avl.Tree // address string -> *playerState

	nonce         int
	totalRounds   int
	oracleCorrect int // rounds the oracle won by successfully countering

	topOutwitter     address
	topOutwitterWins int
)

func getOrCreate(addr address) *playerState {
	key := addr.String()
	if v := players.Get(key); v != nil {
		return v.(*playerState)
	}
	ps := &playerState{}
	players.Set(key, ps)
	return ps
}

// predict guesses the player's next move as the most-played move in their
// history so far. Ties (including a fresh player's all-zero history) fall
// back to a chain-height-derived seed so the oracle doesn't always break
// ties the same way.
func predict(ps *playerState, seed int64) rps.Move {
	best := rps.Rock
	bestCount := ps.Counts[rps.Rock]
	tied := []rps.Move{rps.Rock}
	for _, m := range []rps.Move{rps.Paper, rps.Scissors} {
		switch {
		case ps.Counts[m] > bestCount:
			bestCount = ps.Counts[m]
			best = m
			tied = []rps.Move{m}
		case ps.Counts[m] == bestCount:
			tied = append(tied, m)
		}
	}
	if len(tied) > 1 {
		if seed < 0 {
			seed = -seed
		}
		best = tied[int(seed)%len(tied)]
	}
	return best
}

// Play pits the caller against the oracle: it predicts your next move from
// your own move history and throws the counter. Accepts
// "rock"/"paper"/"scissors" or the single-letter shorthand "r"/"p"/"s".
func Play(cur realm, moveStr string) string {
	if !cur.IsCurrent() {
		panic("invalid realm")
	}
	caller := cur.Previous().Address()

	playerMove, ok := rps.Parse(moveStr)
	if !ok {
		panic("invalid move: use rock, paper, or scissors (r/p/s)")
	}

	ps := getOrCreate(caller)

	nonce++
	seed := runtime.ChainHeight() + int64(nonce)
	predicted := predict(ps, seed)
	oracleMove := beats(predicted)

	result := rps.Beats(playerMove, oracleMove)

	ps.Counts[playerMove]++
	ps.Rounds++
	totalRounds++

	var msg string
	switch result {
	case 1:
		ps.Wins++
		ps.streak++
		if ps.streak > ps.BestStreak {
			ps.BestStreak = ps.streak
		}
		if ps.Wins > topOutwitterWins {
			topOutwitterWins = ps.Wins
			topOutwitter = caller
		}
		msg = "you outwitted the oracle!"
	case 2:
		ps.Losses++
		ps.streak = 0
		oracleCorrect++
		msg = "the oracle read you like a book."
	default:
		ps.Draws++
		ps.streak = 0
		msg = "a draw — you and the oracle picked the same move."
	}

	chain.Emit("RoundPlayed",
		"player", caller.String(),
		"playerMove", playerMove.String(),
		"oraclePredicted", predicted.String(),
		"oracleMove", oracleMove.String(),
		"result", strconv.Itoa(result),
	)

	return "you played " + playerMove.String() + ", the oracle predicted " +
		predicted.String() + " and threw " + oracleMove.String() + " -> " + msg
}

func renderHome() string {
	var b strings.Builder
	b.WriteString("# Rock-Paper-Scissors Oracle\n\n")
	b.WriteString("An adaptive opponent: it doesn't roll dice, it studies you. ")
	b.WriteString("Every throw is logged, and the oracle always counters whichever ")
	b.WriteString("move you've played most often. Play a uniform mixed strategy and ")
	b.WriteString("it can't out-guess you; fall into a habit and it will.\n\n")

	b.WriteString("- Total rounds played: " + strconv.Itoa(totalRounds) + "\n")
	if totalRounds > 0 {
		pct := oracleCorrect * 100 / totalRounds
		b.WriteString("- Oracle win rate: " + strconv.Itoa(pct) + "%\n")
	}
	if topOutwitter.IsValid() {
		b.WriteString("- Top outwitter: `" + topOutwitter.String() + "` (" +
			strconv.Itoa(topOutwitterWins) + " wins against the oracle)\n")
	} else {
		b.WriteString("- No one has beaten the oracle yet.\n")
	}

	b.WriteString("\n## How to play\n\n")
	b.WriteString("Call `Play(\"rock\"|\"paper\"|\"scissors\")` (or `r`/`p`/`s`). ")
	b.WriteString("View your own record at this realm's path plus your address, ")
	b.WriteString("e.g. `.../rpsoracle:g1youraddress...`\n")
	return b.String()
}

func renderPlayer(rawAddr string) string {
	addr := strings.TrimSpace(rawAddr)
	safe := ui.Inline(addr)

	v := players.Get(addr)
	if v == nil {
		return "# Player " + safe + "\n\nNo recorded rounds yet.\n"
	}
	ps := v.(*playerState)

	var b strings.Builder
	b.WriteString("# Player " + safe + "\n\n")
	b.WriteString("- Rounds played: " + strconv.Itoa(ps.Rounds) + "\n")
	b.WriteString("- Beat the oracle: " + strconv.Itoa(ps.Wins) + "\n")
	b.WriteString("- Lost to the oracle: " + strconv.Itoa(ps.Losses) + "\n")
	b.WriteString("- Draws: " + strconv.Itoa(ps.Draws) + "\n")
	b.WriteString("- Best win streak vs oracle: " + strconv.Itoa(ps.BestStreak) + "\n")
	b.WriteString("- Move history — rock: " + strconv.Itoa(ps.Counts[rps.Rock]) +
		", paper: " + strconv.Itoa(ps.Counts[rps.Paper]) +
		", scissors: " + strconv.Itoa(ps.Counts[rps.Scissors]) + "\n")

	if ps.Rounds > 0 {
		maxCount := ps.Counts[rps.Rock]
		for _, c := range ps.Counts[1:] {
			if c > maxCount {
				maxCount = c
			}
		}
		predictability := maxCount * 100 / ps.Rounds
		b.WriteString("- Predictability score: " + strconv.Itoa(predictability) +
			"% (lower is harder for the oracle to read)\n")
	}
	return b.String()
}

// Render shows the oracle's dashboard at "", or one player's record when
// path is their bech32 address.
func Render(path string) string {
	path = strings.TrimPrefix(strings.TrimSpace(path), "/")
	if path == "" {
		return renderHome()
	}
	return renderPlayer(path)
}

rpsoracle_test.gno

package rpsoracle

import (
	"testing"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rps/v0"
	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
)

func resetState() {
	players = avl.Tree{}
	nonce = 0
	totalRounds = 0
	oracleCorrect = 0
	var zero address
	topOutwitter = zero
	topOutwitterWins = 0
}

func TestBeats(t *testing.T) {
	if beats(rps.Rock) != rps.Paper {
		t.Fatal("beats(Rock) should be Paper")
	}
	if beats(rps.Paper) != rps.Scissors {
		t.Fatal("beats(Paper) should be Scissors")
	}
	if beats(rps.Scissors) != rps.Rock {
		t.Fatal("beats(Scissors) should be Rock")
	}
}

func TestPredictPicksMostFrequent(t *testing.T) {
	ps := &playerState{}
	ps.Counts[rps.Paper] = 5
	ps.Counts[rps.Rock] = 1
	if got := predict(ps, 0); got != rps.Paper {
		t.Fatalf("predict = %v, want Paper", got)
	}
}

// Crossing: Play mutates realm state, so the test needs `cur realm`.
func TestOracleCountersPredictableRock(cur realm, t *testing.T) {
	resetState()
	alice := testutils.TestAddress("alice")
	testing.SetRealm(testing.NewUserRealm(alice))

	for i := 0; i < 5; i++ {
		Play(cross(cur), "rock")
	}
	ps := getOrCreate(alice)
	if ps.Losses == 0 {
		t.Fatal("expected the oracle to eventually counter an all-rock player")
	}
	if ps.Rounds != 5 {
		t.Fatalf("Rounds = %d, want 5", ps.Rounds)
	}
}

// Non-crossing: Render is a plain read.
func TestRenderHome(t *testing.T) {
	resetState()
	out := Render("")
	if out == "" {
		t.Fatal("Render(\"\") should not be empty")
	}
}