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/nym-moultest123/x/daily/memory/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186408
  max_deposit = "6000000ugnot"

memory.gno

// Package memory implements "Memory Match", a concentration game on a
// 4x4 grid of 8 emoji pairs. The board is shuffled deterministically from
// the current block height (no on-chain RNG exists), so a NewGame started at
// a given height always produces the same layout.
package memory

import (
	"strconv"
	"strings"

	"chain"
	"chain/runtime"
)

const gridSize = 16 // 4x4
const numPairs = 8

// faces are the 8 distinct emoji; each appears exactly twice on the board.
var faces = [numPairs]string{"🐢", "🐱", "🦊", "🐸", "🐡", "🐼", "🦁", "🐧"}

// tile holds the face index (0..7) for a cell and whether it is matched.
type tile struct {
	face    int
	matched bool
}

// board is the full game state. It is a package-level singleton so the realm
// persists a single shared game.
var board = struct {
	tiles   [gridSize]tile
	flipped []int // indices currently face-up but not yet resolved (0, 1 or 2)
	moves   int   // number of completed two-tile attempts
	pairs   int   // matched pairs so far
	height  int64 // block height the current game was seeded from
	started bool
}{}

// shuffle produces a deterministic permutation of the 16 tile faces from a
// 64-bit seed. It fills a slice with two of each face index then applies a
// Fisher-Yates shuffle driven by a simple LCG β€” fully deterministic, no RNG.
func shuffle(seed int64) [gridSize]tile {
	vals := make([]int, 0, gridSize)
	for i := 0; i < numPairs; i++ {
		vals = append(vals, i, i)
	}
	// LCG (Numerical Recipes constants); force unsigned-style math via uint64.
	state := uint64(seed)*6364136223846793005 + 1442695040888963407
	for i := len(vals) - 1; i > 0; i-- {
		state = state*6364136223846793005 + 1442695040888963407
		j := int(state % uint64(i+1))
		vals[i], vals[j] = vals[j], vals[i]
	}
	var out [gridSize]tile
	for i := 0; i < gridSize; i++ {
		out[i] = tile{face: vals[i], matched: false}
	}
	return out
}

func ensureStarted() {
	if !board.started {
		reset(runtime.ChainHeight())
	}
}

func reset(height int64) {
	board.tiles = shuffle(height)
	board.flipped = nil
	board.moves = 0
	board.pairs = 0
	board.height = height
	board.started = true
}

// NewGame reshuffles the board using the current block height as the seed.
func NewGame(cur realm) {
	reset(runtime.ChainHeight())
	chain.Emit("NewGame", "height", strconv.FormatInt(board.height, 10))
}

// Flip reveals the tile at index (0..15).
//
// Rules:
//   - If two tiles are already showing from a previous unmatched attempt,
//     this Flip first clears them (they turn back to hidden), then reveals
//     the requested tile as the first of a new attempt.
//   - Revealing the second tile of an attempt completes a move: matching
//     faces stay face-up (matched); a mismatch leaves both showing until the
//     next Flip clears them.
//   - Flipping an already-matched or already-showing tile is rejected.
func Flip(cur realm, index int) {
	ensureStarted()

	if index < 0 || index >= gridSize {
		panic("index out of range")
	}
	if board.tiles[index].matched {
		panic("tile already matched")
	}

	// A completed unmatched attempt (2 face-up, non-matching) is cleared
	// before the next reveal.
	if len(board.flipped) == 2 {
		board.flipped = nil
	}

	for _, f := range board.flipped {
		if f == index {
			panic("tile already flipped")
		}
	}

	board.flipped = append(board.flipped, index)

	if len(board.flipped) != 2 {
		chain.Emit("Flip", "index", strconv.Itoa(index))
		return
	}

	// Second tile of the attempt: resolve.
	board.moves++
	a, b := board.flipped[0], board.flipped[1]
	if board.tiles[a].face == board.tiles[b].face {
		board.tiles[a].matched = true
		board.tiles[b].matched = true
		board.pairs++
		board.flipped = nil
		chain.Emit("Match", "index", strconv.Itoa(index), "pairs", strconv.Itoa(board.pairs))
	} else {
		// leave both showing; next Flip clears them
		chain.Emit("Miss", "index", strconv.Itoa(index))
	}
}

func solved() bool {
	return board.pairs == numPairs
}

// cellFace returns the emoji to display for a cell given the current state.
func cellFace(i int) string {
	if board.tiles[i].matched {
		return faces[board.tiles[i].face]
	}
	for _, f := range board.flipped {
		if f == i {
			return faces[board.tiles[i].face]
		}
	}
	return "❓"
}

// Render draws the board as Markdown: a 4x4 grid, move count and solved state.
func Render(path string) string {
	ensureStarted()

	var sb strings.Builder
	sb.WriteString("# 🧠 Memory Match\n\n")
	sb.WriteString("Match all 8 emoji pairs on the 4x4 grid.\n\n")

	sb.WriteString("| | | | |\n")
	sb.WriteString("|:-:|:-:|:-:|:-:|\n")
	for row := 0; row < 4; row++ {
		sb.WriteString("|")
		for col := 0; col < 4; col++ {
			sb.WriteString(" " + cellFace(row*4+col) + " |")
		}
		sb.WriteString("\n")
	}

	sb.WriteString("\n")
	sb.WriteString("- Moves: **" + strconv.Itoa(board.moves) + "**\n")
	sb.WriteString("- Pairs matched: **" + strconv.Itoa(board.pairs) + " / " + strconv.Itoa(numPairs) + "**\n")
	sb.WriteString("- Seed height: **" + strconv.FormatInt(board.height, 10) + "**\n\n")

	if solved() {
		sb.WriteString("πŸŽ‰ **Solved in " + strconv.Itoa(board.moves) + " moves!** Call `NewGame` to play again.\n")
	} else {
		sb.WriteString("Call `Flip(index)` with a cell index 0–15. `NewGame()` reshuffles.\n")
	}

	return sb.String()
}

memory_test.gno

package memory

import (
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

// findPairIndices returns two grid indices holding the same face, plus a third
// index whose face differs from that pair β€” using the current board layout.
func findPairIndices() (int, int, int) {
	// Map first-seen index per face.
	first := map[int]int{}
	var pa, pb int = -1, -1
	for i := 0; i < gridSize; i++ {
		f := board.tiles[i].face
		if j, ok := first[f]; ok {
			pa, pb = j, i
			break
		}
		first[f] = i
	}
	// Find an index outside the matched pair with a different face.
	other := -1
	for i := 0; i < gridSize; i++ {
		if i != pa && i != pb && board.tiles[i].face != board.tiles[pa].face {
			other = i
			break
		}
	}
	return pa, pb, other
}

func TestFlipMatchAndMiss(cur realm, t *testing.T) {
	addr := testutils.TestAddress("player")
	testing.SetRealm(testing.NewUserRealm(addr))

	NewGame(cross(cur))

	pa, pb, other := findPairIndices()
	uassert.True(t, pa >= 0 && pb >= 0 && other >= 0, "expected valid indices")

	// Flip a matching pair -> both matched, pairs increments.
	Flip(cross(cur), pa)
	Flip(cross(cur), pb)
	uassert.True(t, board.tiles[pa].matched, "first tile should be matched")
	uassert.True(t, board.tiles[pb].matched, "second tile should be matched")
	uassert.Equal(t, 1, board.pairs)
	uassert.Equal(t, 1, board.moves)

	// Flip a mismatched pair (pa is matched; pick two unmatched non-equal).
	// Reuse `other` and find a partner with a different face, both unmatched.
	partner := -1
	for i := 0; i < gridSize; i++ {
		if i != other && !board.tiles[i].matched && board.tiles[i].face != board.tiles[other].face {
			partner = i
			break
		}
	}
	uassert.True(t, partner >= 0, "expected a mismatched partner")

	Flip(cross(cur), other)
	Flip(cross(cur), partner)
	uassert.Equal(t, 2, board.moves)
	uassert.Equal(t, 1, board.pairs) // no new match
	// Both still showing (not matched) until next flip clears them.
	uassert.False(t, board.tiles[other].matched, "mismatched tile not matched")
	uassert.Equal(t, 2, len(board.flipped))

	// Next flip clears the two mismatched tiles first.
	// Find any still-unmatched, not-currently-flipped index.
	next := -1
	for i := 0; i < gridSize; i++ {
		if i == other || i == partner {
			continue
		}
		if !board.tiles[i].matched {
			next = i
			break
		}
	}
	uassert.True(t, next >= 0, "expected an unflipped unmatched tile")
	Flip(cross(cur), next)
	uassert.Equal(t, 1, len(board.flipped), "previous mismatch cleared, one showing")
}

func TestDeterministicShuffleAndRender(cur realm, t *testing.T) {
	// Same seed -> identical layout.
	a := shuffle(42)
	b := shuffle(42)
	for i := 0; i < gridSize; i++ {
		uassert.Equal(t, a[i].face, b[i].face)
	}

	// Different seed -> at least one differing cell (extremely likely).
	c := shuffle(43)
	diff := false
	for i := 0; i < gridSize; i++ {
		if a[i].face != c[i].face {
			diff = true
			break
		}
	}
	uassert.True(t, diff, "different seeds should differ")

	// Each face appears exactly twice.
	counts := map[int]int{}
	for i := 0; i < gridSize; i++ {
		counts[a[i].face]++
	}
	for f := 0; f < numPairs; f++ {
		uassert.Equal(t, 2, counts[f])
	}

	// Render on a fresh game shows hidden tiles and zero progress.
	addr := testutils.TestAddress("viewer")
	testing.SetRealm(testing.NewUserRealm(addr))
	NewGame(cross(cur))
	out := Render("")
	uassert.True(t, len(out) > 0, "render non-empty")
	uassert.True(t, containsSub(out, "Memory Match"), "has title")
	uassert.True(t, containsSub(out, "❓"), "shows hidden tiles")
	uassert.True(t, containsSub(out, "0 / 8"), "zero pairs matched")
}

func containsSub(s, sub string) bool {
	for i := 0; i+len(sub) <= len(s); i++ {
		if s[i:i+len(sub)] == sub {
			return true
		}
	}
	return false
}

render_example_test.gno

package memory

// ExampleRender pins the realm's Render output as a testable example.
func ExampleRender() {
	print(Render(""))
	// Output:
	// # 🧠 Memory Match
	//
	// Match all 8 emoji pairs on the 4x4 grid.
	//
	// | | | | |
	// |:-:|:-:|:-:|:-:|
	// | ❓ | ❓ | ❓ | ❓ |
	// | ❓ | ❓ | ❓ | ❓ |
	// | ❓ | ❓ | ❓ | ❓ |
	// | ❓ | ❓ | ❓ | ❓ |
	//
	// - Moves: **0**
	// - Pairs matched: **0 / 8**
	// - Seed height: **123**
	//
	// Call `Flip(index)` with a cell index 0–15. `NewGame()` reshuffles.
}