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

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

rps.gno

package rps

import (
	"chain"
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"

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

// Outcomes.
const (
	outLose = 0 // player loses
	outDraw = 1
	outWin  = 2 // player wins
)

// tally holds a single player's cumulative record.
type tally struct {
	wins   int
	losses int
	draws  int
	plays  int // total rounds this player has played (drives entropy)
}

// round is one recorded game (for the recent-rounds table).
type round struct {
	player   address
	height   int64
	player_m rps.Move
	house_m  rps.Move
	outcome  int
}

// State.
var (
	players = avl.NewTree() // address string -> *tally
	rounds  []round         // append-only history; Render shows the tail

	// Global tally (caller-agnostic).
	totalWins   int // player wins
	totalLosses int // player losses
	totalDraws  int
	totalRounds int
)

const maxRecent = 8

// houseMove derives the house move deterministically from the chain height
// and the caller's play count (so repeated calls in the same block differ).
func houseMove(height int64, playCount int) rps.Move {
	x := height + int64(playCount)*7
	m := x % 3
	if m < 0 {
		m += 3
	}
	return rps.Move(m)
}

// decide returns the outcome from the player's perspective.
func decide(playerMove, houseM rps.Move) int {
	switch rps.Beats(playerMove, houseM) {
	case 1:
		return outWin
	case 2:
		return outLose
	}
	return outDraw
}

func getTally(key string) *tally {
	if v := players.Get(key); v != nil {
		return v.(*tally)
	}
	return nil
}

// Play plays one round against the chain. choice is "rock"|"paper"|"scissors"
// (single-letter shortcuts accepted). It panics on an invalid choice.
func Play(cur realm, choice string) {
	mv, ok := rps.Parse(choice)
	if !ok {
		panic("invalid choice: use rock, paper, or scissors")
	}

	caller := unsafe.PreviousRealm().Address()
	key := caller.String()

	t := getTally(key)
	if t == nil {
		t = &tally{}
		players.Set(key, t)
	}

	height := runtime.ChainHeight()
	hm := houseMove(height, t.plays)
	outcome := decide(mv, hm)

	t.plays++
	switch outcome {
	case outWin:
		t.wins++
		totalWins++
	case outLose:
		t.losses++
		totalLosses++
	default:
		t.draws++
		totalDraws++
	}
	totalRounds++

	rounds = append(rounds, round{
		player:   caller,
		height:   height,
		player_m: mv,
		house_m:  hm,
		outcome:  outcome,
	})

	chain.Emit(
		"RoundPlayed",
		"player", key,
		"choice", mv.String(),
		"house", hm.String(),
		"outcome", outcomeName(outcome),
	)
}

func outcomeName(o int) string {
	switch o {
	case outWin:
		return "win"
	case outLose:
		return "lose"
	default:
		return "draw"
	}
}

func winRate(wins, plays int) string {
	if plays == 0 {
		return "0%"
	}
	return strconv.Itoa(wins*100/plays) + "%"
}

// Render returns a Markdown dashboard: global tally, per-player table, and the
// last few rounds. It is caller-agnostic (no cur).
func Render(path string) string {
	var b strings.Builder

	b.WriteString("# Rock-Paper-Scissors — play vs the chain\n\n")
	b.WriteString("Call `Play(cur, \"rock\"|\"paper\"|\"scissors\")`. ")
	b.WriteString("The house move is derived deterministically from the current block height ")
	b.WriteString("and your personal play count.\n\n")

	// Global tally.
	b.WriteString("## Global tally\n\n")
	b.WriteString("| Rounds | Player wins | Player losses | Draws | Player win rate |\n")
	b.WriteString("|---|---|---|---|---|\n")
	b.WriteString("| " + strconv.Itoa(totalRounds))
	b.WriteString(" | " + strconv.Itoa(totalWins))
	b.WriteString(" | " + strconv.Itoa(totalLosses))
	b.WriteString(" | " + strconv.Itoa(totalDraws))
	b.WriteString(" | " + winRate(totalWins, totalRounds) + " |\n\n")

	// Per-player table (deterministic order via avl iteration).
	b.WriteString("## Players\n\n")
	if players.Size() == 0 {
		b.WriteString("_No games played yet. Be the first!_\n\n")
	} else {
		b.WriteString("| Player | W | L | D | Rounds | Win rate |\n")
		b.WriteString("|---|---|---|---|---|---|\n")
		players.Iterate("", "", func(key string, v interface{}) bool {
			t := v.(*tally)
			b.WriteString("| " + ui.AddrOf(key))
			b.WriteString(" | " + strconv.Itoa(t.wins))
			b.WriteString(" | " + strconv.Itoa(t.losses))
			b.WriteString(" | " + strconv.Itoa(t.draws))
			b.WriteString(" | " + strconv.Itoa(t.plays))
			b.WriteString(" | " + winRate(t.wins, t.plays) + " |\n")
			return false
		})
		b.WriteString("\n")
	}

	// Recent rounds (tail).
	b.WriteString("## Recent rounds\n\n")
	if len(rounds) == 0 {
		b.WriteString("_None yet._\n")
	} else {
		b.WriteString("| Height | Player | Choice | House | Result |\n")
		b.WriteString("|---|---|---|---|---|\n")
		start := len(rounds) - maxRecent
		if start < 0 {
			start = 0
		}
		// Show newest first.
		for i := len(rounds) - 1; i >= start; i-- {
			r := rounds[i]
			b.WriteString("| " + strconv.FormatInt(r.height, 10))
			b.WriteString(" | " + ui.Addr(r.player))
			b.WriteString(" | " + r.player_m.String())
			b.WriteString(" | " + r.house_m.String())
			b.WriteString(" | " + outcomeName(r.outcome) + " |\n")
		}
	}

	return b.String()
}

rps_test.gno

package rps

import (
	"strings"
	"testing"

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

func TestDecide(t *testing.T) {
	// decide: player perspective.
	uassert.Equal(t, outDraw, decide(rps.Rock, rps.Rock), "rock vs rock")
	uassert.Equal(t, outWin, decide(rps.Rock, rps.Scissors), "rock beats scissors")
	uassert.Equal(t, outLose, decide(rps.Rock, rps.Paper), "rock loses to paper")
	uassert.Equal(t, outWin, decide(rps.Paper, rps.Rock), "paper beats rock")
	uassert.Equal(t, outWin, decide(rps.Scissors, rps.Paper), "scissors beats paper")
	uassert.Equal(t, outLose, decide(rps.Scissors, rps.Rock), "scissors loses to rock")

	// houseMove determinism.
	uassert.Equal(t, int(houseMove(10, 0)), int(houseMove(10, 0)), "same inputs -> same move")
	if houseMove(10, 0) == houseMove(10, 1) && houseMove(10, 1) == houseMove(10, 2) {
		t.Error("play count should vary house move across values")
	}
}

func TestPlayRecordsTally(cur realm, t *testing.T) {
	user := testutils.TestAddress("rps-player")
	testing.SetRealm(testing.NewUserRealm(user))

	before := totalRounds
	Play(cross(cur),"rock")
	Play(cross(cur),"paper")
	Play(cross(cur),"scissors")

	uassert.Equal(t, before+3, totalRounds, "global rounds incremented")

	tl := getTally(user.String())
	uassert.True(t, tl != nil, "player tally exists")
	uassert.Equal(t, 3, tl.plays, "player played 3 rounds")
	uassert.Equal(t, tl.wins+tl.losses+tl.draws, tl.plays, "outcomes sum to plays")

	// Render must show the global tally header and the player.
	out := Render("")
	uassert.True(t, strings.Contains(out, "Global tally"), "render has global tally")
	uassert.True(t, strings.Contains(out, "Recent rounds"), "render has recent rounds")

	// Invalid choice aborts (crossing fn -> cross-realm abort).
	uassert.AbortsWithMessage(t, cur, "invalid choice: use rock, paper, or scissors", func() {
		Play(cross(cur),"lizard")
	})
}