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.

rpsoracle.gno

6.19 Kb · 217 lines
  1// Package rpsoracle is a rock-paper-scissors opponent that doesn't roll
  2// dice: it studies each player's move history and always throws the
  3// counter to whichever move that player has favored most. Play a fixed
  4// pattern and the oracle punishes it; play close to a uniform 1/3-1/3-1/3
  5// mix and it can't out-guess you better than chance.
  6package rpsoracle
  7
  8import (
  9	"strconv"
 10	"strings"
 11
 12	"chain"
 13	"chain/runtime"
 14
 15	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
 16	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rps/v0"
 17	"gno.land/p/nt/avl/v0"
 18)
 19
 20// beats returns the move that defeats m.
 21func beats(m rps.Move) rps.Move {
 22	return rps.Move((int(m) + 1) % 3)
 23}
 24
 25// playerState is the persisted record for one address.
 26type playerState struct {
 27	Counts     [3]int // history tally per move, what the oracle predicts from
 28	Rounds     int
 29	Wins       int // player beat the oracle
 30	Losses     int // oracle beat the player
 31	Draws      int
 32	BestStreak int
 33	streak     int // current player win streak against the oracle
 34}
 35
 36var (
 37	players avl.Tree // address string -> *playerState
 38
 39	nonce         int
 40	totalRounds   int
 41	oracleCorrect int // rounds the oracle won by successfully countering
 42
 43	topOutwitter     address
 44	topOutwitterWins int
 45)
 46
 47func getOrCreate(addr address) *playerState {
 48	key := addr.String()
 49	if v := players.Get(key); v != nil {
 50		return v.(*playerState)
 51	}
 52	ps := &playerState{}
 53	players.Set(key, ps)
 54	return ps
 55}
 56
 57// predict guesses the player's next move as the most-played move in their
 58// history so far. Ties (including a fresh player's all-zero history) fall
 59// back to a chain-height-derived seed so the oracle doesn't always break
 60// ties the same way.
 61func predict(ps *playerState, seed int64) rps.Move {
 62	best := rps.Rock
 63	bestCount := ps.Counts[rps.Rock]
 64	tied := []rps.Move{rps.Rock}
 65	for _, m := range []rps.Move{rps.Paper, rps.Scissors} {
 66		switch {
 67		case ps.Counts[m] > bestCount:
 68			bestCount = ps.Counts[m]
 69			best = m
 70			tied = []rps.Move{m}
 71		case ps.Counts[m] == bestCount:
 72			tied = append(tied, m)
 73		}
 74	}
 75	if len(tied) > 1 {
 76		if seed < 0 {
 77			seed = -seed
 78		}
 79		best = tied[int(seed)%len(tied)]
 80	}
 81	return best
 82}
 83
 84// Play pits the caller against the oracle: it predicts your next move from
 85// your own move history and throws the counter. Accepts
 86// "rock"/"paper"/"scissors" or the single-letter shorthand "r"/"p"/"s".
 87func Play(cur realm, moveStr string) string {
 88	if !cur.IsCurrent() {
 89		panic("invalid realm")
 90	}
 91	caller := cur.Previous().Address()
 92
 93	playerMove, ok := rps.Parse(moveStr)
 94	if !ok {
 95		panic("invalid move: use rock, paper, or scissors (r/p/s)")
 96	}
 97
 98	ps := getOrCreate(caller)
 99
100	nonce++
101	seed := runtime.ChainHeight() + int64(nonce)
102	predicted := predict(ps, seed)
103	oracleMove := beats(predicted)
104
105	result := rps.Beats(playerMove, oracleMove)
106
107	ps.Counts[playerMove]++
108	ps.Rounds++
109	totalRounds++
110
111	var msg string
112	switch result {
113	case 1:
114		ps.Wins++
115		ps.streak++
116		if ps.streak > ps.BestStreak {
117			ps.BestStreak = ps.streak
118		}
119		if ps.Wins > topOutwitterWins {
120			topOutwitterWins = ps.Wins
121			topOutwitter = caller
122		}
123		msg = "you outwitted the oracle!"
124	case 2:
125		ps.Losses++
126		ps.streak = 0
127		oracleCorrect++
128		msg = "the oracle read you like a book."
129	default:
130		ps.Draws++
131		ps.streak = 0
132		msg = "a draw — you and the oracle picked the same move."
133	}
134
135	chain.Emit("RoundPlayed",
136		"player", caller.String(),
137		"playerMove", playerMove.String(),
138		"oraclePredicted", predicted.String(),
139		"oracleMove", oracleMove.String(),
140		"result", strconv.Itoa(result),
141	)
142
143	return "you played " + playerMove.String() + ", the oracle predicted " +
144		predicted.String() + " and threw " + oracleMove.String() + " -> " + msg
145}
146
147func renderHome() string {
148	var b strings.Builder
149	b.WriteString("# Rock-Paper-Scissors Oracle\n\n")
150	b.WriteString("An adaptive opponent: it doesn't roll dice, it studies you. ")
151	b.WriteString("Every throw is logged, and the oracle always counters whichever ")
152	b.WriteString("move you've played most often. Play a uniform mixed strategy and ")
153	b.WriteString("it can't out-guess you; fall into a habit and it will.\n\n")
154
155	b.WriteString("- Total rounds played: " + strconv.Itoa(totalRounds) + "\n")
156	if totalRounds > 0 {
157		pct := oracleCorrect * 100 / totalRounds
158		b.WriteString("- Oracle win rate: " + strconv.Itoa(pct) + "%\n")
159	}
160	if topOutwitter.IsValid() {
161		b.WriteString("- Top outwitter: `" + topOutwitter.String() + "` (" +
162			strconv.Itoa(topOutwitterWins) + " wins against the oracle)\n")
163	} else {
164		b.WriteString("- No one has beaten the oracle yet.\n")
165	}
166
167	b.WriteString("\n## How to play\n\n")
168	b.WriteString("Call `Play(\"rock\"|\"paper\"|\"scissors\")` (or `r`/`p`/`s`). ")
169	b.WriteString("View your own record at this realm's path plus your address, ")
170	b.WriteString("e.g. `.../rpsoracle:g1youraddress...`\n")
171	return b.String()
172}
173
174func renderPlayer(rawAddr string) string {
175	addr := strings.TrimSpace(rawAddr)
176	safe := ui.Inline(addr)
177
178	v := players.Get(addr)
179	if v == nil {
180		return "# Player " + safe + "\n\nNo recorded rounds yet.\n"
181	}
182	ps := v.(*playerState)
183
184	var b strings.Builder
185	b.WriteString("# Player " + safe + "\n\n")
186	b.WriteString("- Rounds played: " + strconv.Itoa(ps.Rounds) + "\n")
187	b.WriteString("- Beat the oracle: " + strconv.Itoa(ps.Wins) + "\n")
188	b.WriteString("- Lost to the oracle: " + strconv.Itoa(ps.Losses) + "\n")
189	b.WriteString("- Draws: " + strconv.Itoa(ps.Draws) + "\n")
190	b.WriteString("- Best win streak vs oracle: " + strconv.Itoa(ps.BestStreak) + "\n")
191	b.WriteString("- Move history — rock: " + strconv.Itoa(ps.Counts[rps.Rock]) +
192		", paper: " + strconv.Itoa(ps.Counts[rps.Paper]) +
193		", scissors: " + strconv.Itoa(ps.Counts[rps.Scissors]) + "\n")
194
195	if ps.Rounds > 0 {
196		maxCount := ps.Counts[rps.Rock]
197		for _, c := range ps.Counts[1:] {
198			if c > maxCount {
199				maxCount = c
200			}
201		}
202		predictability := maxCount * 100 / ps.Rounds
203		b.WriteString("- Predictability score: " + strconv.Itoa(predictability) +
204			"% (lower is harder for the oracle to read)\n")
205	}
206	return b.String()
207}
208
209// Render shows the oracle's dashboard at "", or one player's record when
210// path is their bech32 address.
211func Render(path string) string {
212	path = strings.TrimPrefix(strings.TrimSpace(path), "/")
213	if path == "" {
214		return renderHome()
215	}
216	return renderPlayer(path)
217}