rpsmatch.gno
5.40 Kb · 205 lines
1// Package rpsmatch is a best-of-three rock-paper-scissors arena against the
2// house. Unlike a single stateless throw, a match persists across calls:
3// the first player to win two rounds takes the match, and every player's
4// match record accumulates on-chain.
5package rpsmatch
6
7import (
8 "strconv"
9 "strings"
10
11 "chain"
12 "chain/runtime"
13
14 "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
15 "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/rps/v0"
16 "gno.land/p/nt/avl/v0"
17)
18
19// winsNeeded is the number of round wins required to take a match.
20const winsNeeded = 2
21
22// match tracks an in-progress best-of-three series for one player.
23type match struct {
24 PlayerWins int
25 HouseWins int
26 Rounds int
27}
28
29// playerState is the persisted record for one address.
30type playerState struct {
31 Active *match
32 MatchWins int
33 MatchLosses int
34 MatchesPlayed int
35 RoundsPlayed int
36}
37
38var (
39 players avl.Tree // address string -> *playerState
40
41 nonce int
42 totalRounds int
43
44 champion address
45 championWins int
46)
47
48// pickHouseMove derives a deterministic pseudo-random move from the current
49// chain height, a monotonic per-realm nonce, and the caller's address, so
50// repeated throws in the same block still diverge.
51func pickHouseMove(caller address, n int) rps.Move {
52 seed := runtime.ChainHeight() + int64(n)
53 s := caller.String()
54 for i := 0; i < len(s); i++ {
55 seed += int64(s[i])
56 }
57 if seed < 0 {
58 seed = -seed
59 }
60 return rps.Move(seed % 3)
61}
62
63func getOrCreate(addr address) *playerState {
64 key := addr.String()
65 if v := players.Get(key); v != nil {
66 return v.(*playerState)
67 }
68 ps := &playerState{}
69 players.Set(key, ps)
70 return ps
71}
72
73// Throw plays one round of the caller's current match, starting a fresh
74// match if none is in progress. Accepts "rock"/"paper"/"scissors" or the
75// single-letter shorthand "r"/"p"/"s".
76func Throw(cur realm, moveStr string) string {
77 if !cur.IsCurrent() {
78 panic("invalid realm")
79 }
80 caller := cur.Previous().Address()
81
82 playerMove, ok := rps.Parse(moveStr)
83 if !ok {
84 panic("invalid move: use rock, paper, or scissors (r/p/s)")
85 }
86
87 ps := getOrCreate(caller)
88 if ps.Active == nil {
89 ps.Active = &match{}
90 }
91 m := ps.Active
92
93 nonce++
94 houseMove := pickHouseMove(caller, nonce)
95 round := rps.Beats(playerMove, houseMove)
96
97 m.Rounds++
98 totalRounds++
99 ps.RoundsPlayed++
100
101 var roundMsg string
102 switch round {
103 case 1:
104 m.PlayerWins++
105 roundMsg = "you win the round"
106 case 2:
107 m.HouseWins++
108 roundMsg = "house wins the round"
109 default:
110 roundMsg = "round tied"
111 }
112
113 out := "round " + strconv.Itoa(m.Rounds) + ": you played " + playerMove.String() +
114 ", house played " + houseMove.String() + " -> " + roundMsg +
115 " (score " + strconv.Itoa(m.PlayerWins) + "-" + strconv.Itoa(m.HouseWins) + ")"
116
117 if m.PlayerWins >= winsNeeded || m.HouseWins >= winsNeeded {
118 ps.Active = nil
119 ps.MatchesPlayed++
120 playerTookMatch := m.PlayerWins > m.HouseWins
121 if playerTookMatch {
122 ps.MatchWins++
123 if ps.MatchWins > championWins {
124 championWins = ps.MatchWins
125 champion = caller
126 }
127 out += ". MATCH WON!"
128 } else {
129 ps.MatchLosses++
130 out += ". match lost."
131 }
132 chain.Emit("MatchFinished",
133 "player", caller.String(),
134 "playerWins", strconv.Itoa(m.PlayerWins),
135 "houseWins", strconv.Itoa(m.HouseWins),
136 )
137 }
138
139 chain.Emit("RoundPlayed",
140 "player", caller.String(),
141 "playerMove", playerMove.String(),
142 "houseMove", houseMove.String(),
143 "result", strconv.Itoa(round),
144 )
145
146 return out
147}
148
149func renderHome() string {
150 var b strings.Builder
151 b.WriteString("# Rock-Paper-Scissors Arena\n\n")
152 b.WriteString("Best-of-three matches against the house. First to " +
153 strconv.Itoa(winsNeeded) + " round wins takes the match.\n\n")
154 b.WriteString("- Total rounds played: " + strconv.Itoa(totalRounds) + "\n")
155
156 if champion.IsValid() {
157 b.WriteString("- Reigning champion: `" + champion.String() +
158 "` (" + strconv.Itoa(championWins) + " match wins)\n")
159 } else {
160 b.WriteString("- No champion yet — be the first to win a match.\n")
161 }
162
163 b.WriteString("\n## How to play\n\n")
164 b.WriteString("Call `Throw(\"rock\"|\"paper\"|\"scissors\")` (or `r`/`p`/`s`). " +
165 "Your throw starts a new match if you don't have one in progress, " +
166 "and each call plays one round of it.\n\n")
167 b.WriteString("View your own record at this realm's path plus your address, " +
168 "e.g. `.../rpsmatch:g1youraddress...`\n")
169 return b.String()
170}
171
172func renderPlayer(rawAddr string) string {
173 addr := strings.TrimSpace(rawAddr)
174 safe := ui.Inline(addr)
175
176 v := players.Get(addr)
177 if v == nil {
178 return "# Player " + safe + "\n\nNo recorded throws yet.\n"
179 }
180 ps := v.(*playerState)
181
182 var b strings.Builder
183 b.WriteString("# Player " + safe + "\n\n")
184 b.WriteString("- Matches won: " + strconv.Itoa(ps.MatchWins) + "\n")
185 b.WriteString("- Matches lost: " + strconv.Itoa(ps.MatchLosses) + "\n")
186 b.WriteString("- Matches played: " + strconv.Itoa(ps.MatchesPlayed) + "\n")
187 b.WriteString("- Rounds played: " + strconv.Itoa(ps.RoundsPlayed) + "\n")
188
189 if ps.Active != nil {
190 b.WriteString("\n**Match in progress:** " + strconv.Itoa(ps.Active.PlayerWins) +
191 "-" + strconv.Itoa(ps.Active.HouseWins) + " through " +
192 strconv.Itoa(ps.Active.Rounds) + " round(s).\n")
193 }
194 return b.String()
195}
196
197// Render shows the arena dashboard at "", or one player's record when path
198// is their bech32 address.
199func Render(path string) string {
200 path = strings.TrimPrefix(strings.TrimSpace(path), "/")
201 if path == "" {
202 return renderHome()
203 }
204 return renderPlayer(path)
205}