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

engine.gno

package tavern2048

// engine.gno — pure 2048 board logic for Tavern2048.
//
// No chain calls, no IO: a deterministic, fully unit-tested core that the
// realm functions in tavern2048.gno wrap. Same inputs, same board, always.

const N = 4

const DIR_UP = 0
const DIR_RIGHT = 1
const DIR_DOWN = 2
const DIR_LEFT = 3

// Board is one 4x4 game. Zero is an empty cell.
type Board struct {
	Cells [N][N]int `json:"cells"`
	Score int       `json:"score"`
	Moves int       `json:"moves"`
	Over  bool      `json:"over"`
}

// NewBoard returns a fresh board with the two starting tiles.
func NewBoard() Board {
	var b Board
	b.Cells[1][1] = 2
	b.Cells[0][2] = 2
	return b
}

// NewBoardSeeded returns a fresh board whose two starting tiles are placed
// from seed, so every game starts differently but reproducibly.
func NewBoardSeeded(seed int) Board {
	var b Board
	a := lcg(seed) % (N * N)
	c := lcg(seed+1) % (N*N - 1)
	if c >= a {
		c++
	}
	b.Cells[a/N][a%N] = 2
	v := 2
	if lcg(seed+2)%8 == 0 {
		v = 4
	}
	b.Cells[c/N][c%N] = v
	return b
}

// slideRowLeft collapses a row to the left, merging equal neighbours once.
// Returns the new row and the points added by the merges.
func slideRowLeft(row [N]int) (out [N]int, gained int) {
	// 1. strip zeros
	nz := [N]int{}
	cnt := 0
	for i := 0; i < N; i++ {
		if row[i] != 0 {
			nz[cnt] = row[i]
			cnt++
		}
	}
	// 2. single pass: merge only original adjacent pairs (each tile at most
	//    once per move) — the canonical 2048 rule.
	merged := [N]int{}
	m := 0
	i := 0
	for i < cnt {
		if i+1 < cnt && nz[i] == nz[i+1] {
			merged[m] = nz[i] * 2
			gained += nz[i] * 2
			m++
			i += 2
		} else {
			merged[m] = nz[i]
			m++
			i++
		}
	}
	for j := 0; j < N; j++ {
		out[j] = merged[j]
	}
	return out, gained
}

// applyDir runs a full-board move. It returns the new board, the gained
// score and whether the board changed at all.
func applyDir(b [N][N]int, dir int) (nb [N][N]int, gained int, moved bool) {
	nb = b
	for i := 0; i < N; i++ {
		row := [N]int{}
		for j := 0; j < N; j++ {
			switch dir {
			case DIR_UP:
				row[j] = b[j][i]
			case DIR_DOWN:
				row[j] = b[N-1-j][i]
			case DIR_LEFT:
				row[j] = b[i][j]
			case DIR_RIGHT:
				row[j] = b[i][N-1-j]
			}
		}
		slid, g := slideRowLeft(row)
		gained += g
		for j := 0; j < N; j++ {
			switch dir {
			case DIR_UP:
				nb[j][i] = slid[j]
			case DIR_DOWN:
				nb[N-1-j][i] = slid[j]
			case DIR_LEFT:
				nb[i][j] = slid[j]
			case DIR_RIGHT:
				nb[i][N-1-j] = slid[j]
			}
		}
	}
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if nb[i][j] != b[i][j] {
				moved = true
			}
		}
	}
	return nb, gained, moved
}

// HasMove reports whether any move is still possible.
func HasMove(b [N][N]int) bool {
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if b[i][j] == 0 {
				return true
			}
			if j+1 < N && b[i][j] == b[i][j+1] {
				return true
			}
			if i+1 < N && b[i][j] == b[i+1][j] {
				return true
			}
		}
	}
	return false
}

// lcg advances a deterministic PRNG from a seed; value in [0,1024).
func lcg(seed int) int {
	x := seed*1103515245 + 12345
	x &= 0x7fffffff
	return x % 1024
}

// Itoa is a dependency-free int->string for realm Render.
func Itoa(x int) string {
	if x == 0 {
		return "0"
	}
	neg := x < 0
	if neg {
		x = -x
	}
	var b []byte
	for x > 0 {
		b = append(b, byte('0'+x%10))
		x /= 10
	}
	if neg {
		b = append(b, '-')
	}
	s := ""
	for i := len(b) - 1; i >= 0; i-- {
		s += string(b[i])
	}
	return s
}

// Move applies a direction (0=up,1=right,2=down,3=left) to the board,
// awards merge points and spawns one new tile from the block-height seed.
// spawnSeed makes the spawn reproducible: pass blockheight() on chain.
// Returns the updated board and a human-readable outcome.
func (b *Board) Move(dir int, spawnSeed int) (ok bool, msg string) {
	if b.Over {
		return false, "game over"
	}
	if dir < DIR_UP || dir > DIR_LEFT {
		return false, "invalid dir"
	}
	nb, gained, moved := applyDir(b.Cells, dir)
	if !moved {
		return false, "no change"
	}
	b.Cells = nb
	b.Score += gained
	b.Moves++
	if !HasMove(b.Cells) {
		b.Over = true
		return true, "game over"
	}
	// spawn: 2 with 87.5% chance, 4 with 12.5%, cell picked deterministically
	v := lcg(spawnSeed*7919 + b.Score*2654435761 + b.Moves*97)
	val := 2
	if v%8 == 0 {
		val = 4
	}
	var empty [][2]int
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if b.Cells[i][j] == 0 {
				empty = append(empty, [2]int{i, j})
			}
		}
	}
	if len(empty) > 0 {
		cell := empty[lcg(v+1)%len(empty)]
		b.Cells[cell[0]][cell[1]] = val
	}
	return true, "score " + Itoa(b.Score)
}

engine_test.gno

package tavern2048

import "testing"

func TestSlideRowLeft(t *testing.T) {
	out, g := slideRowLeft([N]int{2, 2, 4, 4})
	if out != [N]int{4, 8, 0, 0} || g != 12 {
		t.Fatalf("got %v g=%d", out, g)
	}
	// [2,2,2,2] -> [4,4,0,0] (each tile merges at most once)
	out, g = slideRowLeft([N]int{2, 2, 2, 2})
	if out != [N]int{4, 4, 0, 0} || g != 8 {
		t.Fatalf("got %v g=%d", out, g)
	}
	// no merge
	out, g = slideRowLeft([N]int{0, 0, 2, 4})
	if out != [N]int{2, 4, 0, 0} || g != 0 {
		t.Fatalf("got %v g=%d", out, g)
	}
	// a just-merged tile must not merge again: [4,2,2,0] -> [4,4,0,0]
	out, g = slideRowLeft([N]int{4, 2, 2, 0})
	if out != [N]int{4, 4, 0, 0} || g != 4 {
		t.Fatalf("got %v g=%d", out, g)
	}
	// 4 must not merge across 2: [4,2,4,0] -> [4,2,4,0]
	out, g = slideRowLeft([N]int{4, 2, 4, 0})
	if out != [N]int{4, 2, 4, 0} || g != 0 {
		t.Fatalf("got %v g=%d", out, g)
	}
}

func TestApplyDirAllDirections(t *testing.T) {
	b := [N][N]int{{2, 0, 0, 0}, {2, 4, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
	nb, g, moved := applyDir(b, DIR_UP)
	if !moved || nb[0][0] != 4 || g != 4 {
		t.Fatalf("up: %v g=%d", nb, g)
	}
	b = [N][N]int{{2, 2, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
	nb, g, moved = applyDir(b, DIR_LEFT)
	if !moved || nb[0][0] != 4 || g != 4 {
		t.Fatalf("left: %v g=%d", nb, g)
	}
	b = [N][N]int{{2, 0, 2, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
	nb, g, moved = applyDir(b, DIR_RIGHT)
	if !moved || nb[0][3] != 4 || g != 4 {
		t.Fatalf("right: %v g=%d", nb, g)
	}
	b = [N][N]int{{0, 2, 0, 0}, {0, 2, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
	nb, g, moved = applyDir(b, DIR_DOWN)
	if !moved || nb[3][1] != 4 || g != 4 {
		t.Fatalf("down: %v g=%d", nb, g)
	}
}

func TestNoChangeDetection(t *testing.T) {
	// full board, no merges: every direction is a no-op
	b := [N][N]int{{2, 4, 8, 16}, {32, 64, 128, 256}, {512, 1024, 2, 4}, {8, 16, 32, 64}}
	for d := 0; d < 4; d++ {
		_, _, moved := applyDir(b, d)
		if moved {
			t.Fatalf("dir %d should be a no-op", d)
		}
	}
	// left moves, up is a no-op for a lone tile in a column
	b = [N][N]int{{0, 2, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
	_, _, moved := applyDir(b, DIR_LEFT)
	if !moved {
		t.Fatal("left should move")
	}
	_, _, moved = applyDir(b, DIR_UP)
	if moved {
		t.Fatal("up should be a no-op")
	}
}

func TestHasMove(t *testing.T) {
	b := [N][N]int{{2, 4, 8, 16}, {32, 64, 128, 256}, {512, 1024, 2, 4}, {8, 16, 32, 64}}
	if HasMove(b) {
		t.Fatal("full board, no merges -> no move")
	}
	b[0][0] = 0
	if !HasMove(b) {
		t.Fatal("a zero cell means a move")
	}
	b = [N][N]int{{2, 2, 8, 16}, {32, 64, 128, 256}, {512, 1024, 4, 8}, {16, 32, 64, 128}}
	if !HasMove(b) {
		t.Fatal("equal neighbours means a move")
	}
}

func TestLcgBounds(t *testing.T) {
	for s := 0; s < 1000; s += 7 {
		v := lcg(s)
		if v < 0 || v >= 1024 {
			t.Fatalf("lcg out of range: %d", v)
		}
	}
}

func TestItoa(t *testing.T) {
	cases := map[int]string{0: "0", 42: "42", 123456: "123456", -7: "-7"}
	for in, want := range cases {
		if got := Itoa(in); got != want {
			t.Fatalf("Itoa(%d)=%s want %s", in, got, want)
		}
	}
}

func isPow2(v int) bool {
	return v >= 2 && (v&(v-1)) == 0
}

func TestGameSim(t *testing.T) {
	b := NewBoard()
	if b.Cells[1][1] != 2 || b.Cells[0][2] != 2 {
		t.Fatalf("start tiles wrong: %v", b)
	}
	moves := 0
	for i := 0; i < 500 && !b.Over; i++ {
		ok, _ := b.Move(i%4, 1000+i)
		if ok {
			moves++
			if b.Score < 0 {
				t.Fatal("negative score")
			}
			for r := 0; r < N; r++ {
				for c := 0; c < N; c++ {
					v := b.Cells[r][c]
					if v != 0 && !isPow2(v) {
						t.Fatalf("bad cell value %d at %d,%d", v, r, c)
					}
				}
			}
		}
	}
	if moves < 20 {
		t.Fatalf("too few moves in sim: %d", moves)
	}
	t.Logf("sim done: moves=%d score=%d over=%v", moves, b.Score, b.Over)
}

func TestSpawnIsReproducible(t *testing.T) {
	a := NewBoard()
	b := NewBoard()
	// same seeds => identical boards
	for i := 0; i < 50; i++ {
		ao, _ := a.Move(i%4, 777+i)
		bo, _ := b.Move(i%4, 777+i)
		if ao != bo {
			t.Fatal("moves diverged unexpectedly")
		}
	}
	if a.Cells != b.Cells || a.Score != b.Score || a.Moves != b.Moves {
		t.Fatal("same seeds must give identical state")
	}
}

func TestNewBoardSeeded(t *testing.T) {
	for s := 0; s < 200; s++ {
		b := NewBoardSeeded(s)
		tiles := 0
		for i := 0; i < N; i++ {
			for j := 0; j < N; j++ {
				if b.Cells[i][j] != 0 {
					tiles++
				}
			}
		}
		if tiles != 2 {
			t.Fatalf("seed %d: want 2 start tiles, got %d", s, tiles)
		}
	}
	if NewBoardSeeded(42).Cells != NewBoardSeeded(42).Cells {
		t.Fatal("same seed must give same start board")
	}
}

gnomod.toml

module = "gno.land/r/g15crxnxd79syggtha6ymfhy8m8a4ytqel58cwkg/tavern2048/v0"
gno = "0.9"

[addpkg]
  creator = "g15crxnxd79syggtha6ymfhy8m8a4ytqel58cwkg"
  height = 1344864
  max_deposit = "8000000ugnot"

tavern2048.gno

package tavern2048

// Tavern2048 — the classic 2048 puzzle, played one signed transaction at a
// time on gno.land.
//
// Every move is a real MsgCall: the board lives in this realm's state, keyed
// by the address that signed the call, so nobody can play (or fake) a game on
// your behalf and there is no server to trust. Tile spawns are derived from
// the block height and the player's address: deterministic and verifiable by
// anyone replaying the chain. Boards are rendered as SVG straight from chain
// state by gnoweb, together with an all-time leaderboard.

import (
	"chain"
	"chain/runtime"
	"encoding/base64"
	"strings"

	"gno.land/p/nt/avl/v0"
)

// realmPath is the gnoweb path of this realm, used for in-page links.
const realmPath = "/r/g15crxnxd79syggtha6ymfhy8m8a4ytqel58cwkg/tavern2048/v0"

// MaxPlayMoves caps how many moves a single Play transaction may apply.
const MaxPlayMoves = 64

// TopN is how many players the leaderboard shows.
const TopN = 10

// Game is one player's current game.
type Game struct {
	Board   Board
	Seed    int   // per-player spawn salt, derived from the address
	Started int64 // block height of NewGame
	Updated int64 // block height of the last applied move
}

var (
	games      = avl.NewTree() // player address -> *Game (current game)
	best       = avl.NewTree() // player address -> int (best score ever)
	totalGames int
	totalMoves int
)

// NewGame starts a fresh board for the signer, replacing any current game.
// The best score ever reached is kept for the leaderboard.
func NewGame(cur realm) string {
	player := cur.Previous().Address().String()
	h := runtime.ChainHeight()
	salt := addrSeed(player)
	g := &Game{
		Board:   NewBoardSeeded(int(h) + salt),
		Seed:    salt,
		Started: h,
		Updated: h,
	}
	games.Set(player, g)
	if !best.Has(player) {
		best.Set(player, 0) // registers the player on the leaderboard
	}
	totalGames++
	chain.Emit("NewGame", "player", player)
	return "new game started: " + realmPath + ":" + player
}

// Move slides the signer's board once: dir is up, down, left or right
// (or u, d, l, r). A move that changes nothing is not counted.
func Move(cur realm, dir string) string {
	player := cur.Previous().Address().String()
	g := mustGame(player)
	d, ok := parseDir(dir)
	if !ok {
		panic("invalid direction " + strings.TrimSpace(dir) + ": use up, down, left or right")
	}
	_, msg := step(player, g, d)
	return msg
}

// Play applies a sequence of moves in a single transaction, e.g. "lldrul"
// (u=up, d=down, l=left, r=right; spaces and commas are ignored). It stops
// early when the game is over. At most MaxPlayMoves moves per call.
func Play(cur realm, moves string) string {
	player := cur.Previous().Address().String()
	g := mustGame(player)
	var dirs []int
	for _, c := range strings.ToLower(moves) {
		switch c {
		case ' ', ',':
			continue
		case 'u':
			dirs = append(dirs, DIR_UP)
		case 'r':
			dirs = append(dirs, DIR_RIGHT)
		case 'd':
			dirs = append(dirs, DIR_DOWN)
		case 'l':
			dirs = append(dirs, DIR_LEFT)
		default:
			panic("invalid move " + string(c) + ": use only u, d, l, r")
		}
	}
	if len(dirs) == 0 {
		panic("no moves given: e.g. lldrul")
	}
	if len(dirs) > MaxPlayMoves {
		panic("too many moves: at most " + Itoa(MaxPlayMoves) + " per call")
	}
	applied := 0
	for _, d := range dirs {
		if g.Board.Over {
			break
		}
		if moved, _ := step(player, g, d); moved {
			applied++
		}
	}
	out := "applied " + Itoa(applied) + "/" + Itoa(len(dirs)) + " moves, score " + Itoa(g.Board.Score)
	if g.Board.Over {
		out += ", game over"
	}
	return out
}

// ScoreOf returns the current score of a player (0 if no game).
func ScoreOf(player address) int {
	v := games.Get(player.String())
	if v == nil {
		return 0
	}
	return v.(*Game).Board.Score
}

// BestOf returns the best score a player ever reached.
func BestOf(player address) int {
	v := best.Get(player.String())
	if v == nil {
		return 0
	}
	return v.(int)
}

func mustGame(player string) *Game {
	v := games.Get(player)
	if v == nil {
		panic("no game yet: call NewGame first")
	}
	return v.(*Game)
}

// step applies one direction and records score, best and events.
func step(player string, g *Game, d int) (bool, string) {
	if g.Board.Over {
		return false, "game over: call NewGame to play again"
	}
	h := runtime.ChainHeight()
	moved, msg := g.Board.Move(d, int(h)+g.Seed)
	if !moved {
		return false, msg
	}
	g.Updated = h
	totalMoves++
	if g.Board.Score > BestOfKey(player) {
		best.Set(player, g.Board.Score)
	}
	chain.Emit("Move", "player", player, "dir", dirName(d), "score", Itoa(g.Board.Score))
	if g.Board.Over {
		chain.Emit("GameOver", "player", player, "score", Itoa(g.Board.Score))
		return true, "game over, final score " + Itoa(g.Board.Score)
	}
	return true, msg
}

// BestOfKey is BestOf for a raw address string.
func BestOfKey(player string) int {
	v := best.Get(player)
	if v == nil {
		return 0
	}
	return v.(int)
}

func parseDir(s string) (int, bool) {
	switch strings.ToLower(strings.TrimSpace(s)) {
	case "up", "u":
		return DIR_UP, true
	case "right", "r":
		return DIR_RIGHT, true
	case "down", "d":
		return DIR_DOWN, true
	case "left", "l":
		return DIR_LEFT, true
	}
	return 0, false
}

func dirName(d int) string {
	switch d {
	case DIR_UP:
		return "up"
	case DIR_RIGHT:
		return "right"
	case DIR_DOWN:
		return "down"
	}
	return "left"
}

// addrSeed folds an address into a small positive salt.
func addrSeed(a string) int {
	s := 7
	for i := 0; i < len(a); i++ {
		s = (s*31 + int(a[i])) & 0xffffff
	}
	return s
}

func maxTile(b Board) int {
	m := 0
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if b.Cells[i][j] > m {
				m = b.Cells[i][j]
			}
		}
	}
	return m
}

func shortAddr(a string) string {
	if len(a) > 14 {
		return a[:7] + "…" + a[len(a)-4:]
	}
	return a
}

// ---- rendering -------------------------------------------------------------

// Render serves the tavern home (path "") or a player's board (path = g1...).
func Render(path string) string {
	path = strings.TrimSpace(path)
	if path == "" {
		return renderHome()
	}
	if !address(path).IsValid() {
		return "# Not found\n\n`" + path + "` is not a player address. [Back to the tavern](" + realmPath + ")\n"
	}
	return renderPlayer(path)
}

func renderHome() string {
	var sb strings.Builder
	sb.WriteString("# 🍺 Tavern2048\n\n")
	sb.WriteString("_The classic 2048 puzzle, played one signed transaction at a time on gno.land._\n\n")
	sb.WriteString("Your board lives in this realm, keyed by the address that signs your moves: no server, no backend, nobody can play on your behalf. ")
	sb.WriteString("New tiles are derived from the block height, so every game is verifiable by replaying the chain.\n\n")
	sb.WriteString("**" + Itoa(best.Size()) + "** players · **" + Itoa(totalGames) + "** games · **" + Itoa(totalMoves) + "** on-chain moves\n\n")

	sb.WriteString("## How to play\n\n")
	sb.WriteString("1. [Start a new game](" + realmPath + "$help&func=NewGame) — signs `NewGame`.\n")
	sb.WriteString("2. Slide the tiles: [⬆ up](" + realmPath + "$help&func=Move&dir=up) · ")
	sb.WriteString("[⬇ down](" + realmPath + "$help&func=Move&dir=down) · ")
	sb.WriteString("[⬅ left](" + realmPath + "$help&func=Move&dir=left) · ")
	sb.WriteString("[➡ right](" + realmPath + "$help&func=Move&dir=right), ")
	sb.WriteString("or chain up to " + Itoa(MaxPlayMoves) + " moves in one transaction with `Play(\"lldrul\")`.\n")
	sb.WriteString("3. Watch your board at `" + realmPath + ":<your address>`.\n\n")
	sb.WriteString("Each link opens the call page: it prints the `gnokey maketx call` command for your address, or sign it with a browser wallet.\n\n")

	sb.WriteString("## 🏆 Leaderboard\n\n")
	sb.WriteString(renderLeaderboard())
	return sb.String()
}

type entry struct {
	player string
	score  int
}

func renderLeaderboard() string {
	var all []entry
	best.Iterate("", "", func(k string, v any) bool {
		all = append(all, entry{k, v.(int)})
		return false
	})
	if len(all) == 0 {
		return "_No scores yet — be the first gnome on the board._\n"
	}
	// selection sort on the top N only (best first, ties by address)
	lim := TopN
	if len(all) < lim {
		lim = len(all)
	}
	for i := 0; i < lim; i++ {
		mx := i
		for j := i + 1; j < len(all); j++ {
			if all[j].score > all[mx].score {
				mx = j
			}
		}
		all[i], all[mx] = all[mx], all[i]
	}
	medals := []string{"🥇", "🥈", "🥉"}
	var sb strings.Builder
	sb.WriteString("| # | player | best score | current game |\n|---|---|---|---|\n")
	for i := 0; i < lim; i++ {
		rank := Itoa(i + 1)
		if i < len(medals) {
			rank = medals[i]
		}
		cur := "—"
		if v := games.Get(all[i].player); v != nil {
			g := v.(*Game)
			cur = Itoa(g.Board.Score)
			if g.Board.Over {
				cur += " (over)"
			}
		}
		sb.WriteString("| " + rank + " | [" + shortAddr(all[i].player) + "](" + realmPath + ":" + all[i].player + ") | " + Itoa(all[i].score) + " | " + cur + " |\n")
	}
	return sb.String()
}

func renderPlayer(player string) string {
	var sb strings.Builder
	sb.WriteString("# 🍺 Tavern2048 — " + shortAddr(player) + "\n\n")
	v := games.Get(player)
	if v == nil {
		sb.WriteString("This gnome has not started a game yet. [Start a new game](" + realmPath + "$help&func=NewGame).\n\n")
		sb.WriteString("[← Back to the tavern](" + realmPath + ")\n")
		return sb.String()
	}
	g := v.(*Game)
	b := g.Board
	sb.WriteString(boardSVG(b) + "\n\n")
	status := "in play"
	if b.Over {
		status = "**game over**"
	}
	sb.WriteString("**Score** " + Itoa(b.Score) + " · **Best** " + Itoa(BestOfKey(player)) + " · **Moves** " + Itoa(b.Moves) + " · **Top tile** " + Itoa(maxTile(b)) + " · " + status + "\n\n")
	sb.WriteString("Started at block " + Itoa(int(g.Started)) + ", last move at block " + Itoa(int(g.Updated)) + ".\n\n")
	if b.Over {
		sb.WriteString("[Start a new game](" + realmPath + "$help&func=NewGame)\n\n")
	} else {
		sb.WriteString("Move: [⬆ up](" + realmPath + "$help&func=Move&dir=up) · ")
		sb.WriteString("[⬇ down](" + realmPath + "$help&func=Move&dir=down) · ")
		sb.WriteString("[⬅ left](" + realmPath + "$help&func=Move&dir=left) · ")
		sb.WriteString("[➡ right](" + realmPath + "$help&func=Move&dir=right)\n\n")
		sb.WriteString("Or play a whole combo in one transaction:\n\n")
		sb.WriteString("<gno-form exec=\"Play\">\n")
		sb.WriteString("<gno-input name=\"moves\" placeholder=\"e.g. lldrul (u/d/l/r)\" />\n")
		sb.WriteString("</gno-form>\n\n")
	}
	sb.WriteString("[← Back to the tavern](" + realmPath + ")\n")
	return sb.String()
}

func tileColors(v int) (bg, fg string) {
	switch v {
	case 0:
		return "#cdc1b4", "#776e65"
	case 2:
		return "#eee4da", "#776e65"
	case 4:
		return "#ede0c8", "#776e65"
	case 8:
		return "#f2b179", "#f9f6f2"
	case 16:
		return "#f59563", "#f9f6f2"
	case 32:
		return "#f67c5f", "#f9f6f2"
	case 64:
		return "#f65e3b", "#f9f6f2"
	case 128:
		return "#edcf72", "#f9f6f2"
	case 256:
		return "#edcc61", "#f9f6f2"
	case 512:
		return "#edc850", "#f9f6f2"
	case 1024:
		return "#edc53f", "#f9f6f2"
	case 2048:
		return "#edc22e", "#f9f6f2"
	}
	return "#3c3a32", "#f9f6f2"
}

// boardSVG draws the board as an inline SVG image (data URI) for gnoweb.
func boardSVG(b Board) string {
	const cell = 100
	const gap = 12
	const size = gap + N*(cell+gap)
	var sb strings.Builder
	sb.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" width="` + Itoa(size) + `" height="` + Itoa(size) + `" viewBox="0 0 ` + Itoa(size) + ` ` + Itoa(size) + `">`)
	sb.WriteString(`<rect width="` + Itoa(size) + `" height="` + Itoa(size) + `" rx="14" fill="#bbada0"/>`)
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			x := gap + j*(cell+gap)
			y := gap + i*(cell+gap)
			v := b.Cells[i][j]
			bg, fg := tileColors(v)
			sb.WriteString(`<rect x="` + Itoa(x) + `" y="` + Itoa(y) + `" width="` + Itoa(cell) + `" height="` + Itoa(cell) + `" rx="8" fill="` + bg + `"/>`)
			if v != 0 {
				txt := Itoa(v)
				fs := 52
				switch {
				case len(txt) >= 5:
					fs = 26
				case len(txt) == 4:
					fs = 34
				case len(txt) == 3:
					fs = 42
				}
				sb.WriteString(`<text x="` + Itoa(x+cell/2) + `" y="` + Itoa(y+cell/2) + `" dy="0.35em" text-anchor="middle" font-family="Arial,Helvetica,sans-serif" font-weight="bold" font-size="` + Itoa(fs) + `" fill="` + fg + `">` + txt + `</text>`)
			}
		}
	}
	sb.WriteString(`</svg>`)
	return "![Tavern2048 board](data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(sb.String())) + ")"
}

tavern2048_test.gno

package tavern2048

import (
	"strings"
	"testing"

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

var (
	alice = testutils.TestAddress("alice")
	bob   = testutils.TestAddress("bob")
)

func resetState() {
	games = avl.NewTree()
	best = avl.NewTree()
	totalGames = 0
	totalMoves = 0
}

func countTiles(b Board) int {
	n := 0
	for i := 0; i < N; i++ {
		for j := 0; j < N; j++ {
			if b.Cells[i][j] != 0 {
				n++
			}
		}
	}
	return n
}

// moveAny tries every direction until one changes the board.
func moveAny(cur realm, g *Game) bool {
	for _, d := range []string{"left", "up", "right", "down"} {
		before := g.Board.Moves
		Move(cross(cur), d)
		if g.Board.Moves > before {
			return true
		}
	}
	return false
}

func TestNewGameAndMove(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(alice))
	NewGame(cross(cur))

	v := games.Get(alice.String())
	if v == nil {
		t.Fatal("alice should have a game keyed by her address")
	}
	g := v.(*Game)
	if countTiles(g.Board) != 2 {
		t.Fatalf("new board must have 2 tiles, got %d", countTiles(g.Board))
	}
	if !moveAny(cur, g) {
		t.Fatal("a fresh board must allow a move")
	}
	if g.Board.Moves != 1 || totalMoves != 1 {
		t.Fatalf("moves=%d total=%d, want 1/1", g.Board.Moves, totalMoves)
	}
	if countTiles(g.Board) < 2 {
		t.Fatal("a move must spawn a tile")
	}
}

func TestPlayersAreIsolated(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(alice))
	NewGame(cross(cur))
	ga := games.Get(alice.String()).(*Game)
	moveAny(cur, ga)

	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "no game yet: call NewGame first", func() {
		Move(cross(cur), "left")
	})
	NewGame(cross(cur))
	if games.Size() != 2 {
		t.Fatalf("want 2 games, got %d", games.Size())
	}
	if ga.Board.Moves != 1 {
		t.Fatal("bob must not touch alice's board")
	}
}

func TestInvalidInput(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(alice))
	NewGame(cross(cur))
	uassert.AbortsWithMessage(t, cur, "invalid direction diagonal: use up, down, left or right", func() {
		Move(cross(cur), "diagonal")
	})
	uassert.AbortsWithMessage(t, cur, "invalid move x: use only u, d, l, r", func() {
		Play(cross(cur), "lrx")
	})
	uassert.AbortsWithMessage(t, cur, "no moves given: e.g. lldrul", func() {
		Play(cross(cur), " , ")
	})
	uassert.AbortsWithMessage(t, cur, "too many moves: at most 64 per call", func() {
		Play(cross(cur), strings.Repeat("l", 65))
	})
}

func TestPlaySequenceAndBest(cur realm, t *testing.T) {
	resetState()
	testing.SetRealm(testing.NewUserRealm(alice))
	NewGame(cross(cur))
	g := games.Get(alice.String()).(*Game)
	for i := 0; i < 20 && !g.Board.Over; i++ {
		testing.SkipHeights(1)
		Play(cross(cur), "ldru ldru ldru ldru")
	}
	if g.Board.Moves < 10 {
		t.Fatalf("expected many moves, got %d", g.Board.Moves)
	}
	if BestOf(alice) != g.Board.Score || ScoreOf(alice) != g.Board.Score {
		t.Fatalf("best=%d score=%d current=%d", BestOf(alice), ScoreOf(alice), g.Board.Score)
	}
	top := g.Board.Score
	// a new game resets the board but keeps the best score
	NewGame(cross(cur))
	if ScoreOf(alice) != 0 || BestOf(alice) != top {
		t.Fatalf("after NewGame: score=%d best=%d want 0/%d", ScoreOf(alice), BestOf(alice), top)
	}
}

func TestRender(cur realm, t *testing.T) {
	resetState()
	home := Render("")
	if !strings.Contains(home, "Tavern2048") || !strings.Contains(home, "No scores yet") {
		t.Fatalf("empty home render wrong:\n%s", home)
	}
	testing.SetRealm(testing.NewUserRealm(alice))
	NewGame(cross(cur))
	g := games.Get(alice.String()).(*Game)
	moveAny(cur, g)

	home = Render("")
	if !strings.Contains(home, "Leaderboard") || !strings.Contains(home, realmPath+":"+alice.String()) {
		t.Fatalf("home must link alice's board:\n%s", home)
	}
	page := Render(alice.String())
	if !strings.Contains(page, "data:image/svg+xml;base64,") {
		t.Fatalf("player page must embed the SVG board:\n%s", page)
	}
	if !strings.Contains(page, "<gno-form exec=\"Play\">") {
		t.Fatal("player page must offer the Play form")
	}
	if !strings.Contains(Render(bob.String()), "has not started a game") {
		t.Fatal("unknown player page wrong")
	}
	if !strings.Contains(Render("nope"), "Not found") {
		t.Fatal("bad path must render Not found")
	}
}