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.

tavern2048.gno

12.17 Kb · 419 lines
  1package tavern2048
  2
  3// Tavern2048 — the classic 2048 puzzle, played one signed transaction at a
  4// time on gno.land.
  5//
  6// Every move is a real MsgCall: the board lives in this realm's state, keyed
  7// by the address that signed the call, so nobody can play (or fake) a game on
  8// your behalf and there is no server to trust. Tile spawns are derived from
  9// the block height and the player's address: deterministic and verifiable by
 10// anyone replaying the chain. Boards are rendered as SVG straight from chain
 11// state by gnoweb, together with an all-time leaderboard.
 12
 13import (
 14	"chain"
 15	"chain/runtime"
 16	"encoding/base64"
 17	"strings"
 18
 19	"gno.land/p/nt/avl/v0"
 20)
 21
 22// realmPath is the gnoweb path of this realm, used for in-page links.
 23const realmPath = "/r/g15crxnxd79syggtha6ymfhy8m8a4ytqel58cwkg/tavern2048/v0"
 24
 25// MaxPlayMoves caps how many moves a single Play transaction may apply.
 26const MaxPlayMoves = 64
 27
 28// TopN is how many players the leaderboard shows.
 29const TopN = 10
 30
 31// Game is one player's current game.
 32type Game struct {
 33	Board   Board
 34	Seed    int   // per-player spawn salt, derived from the address
 35	Started int64 // block height of NewGame
 36	Updated int64 // block height of the last applied move
 37}
 38
 39var (
 40	games      = avl.NewTree() // player address -> *Game (current game)
 41	best       = avl.NewTree() // player address -> int (best score ever)
 42	totalGames int
 43	totalMoves int
 44)
 45
 46// NewGame starts a fresh board for the signer, replacing any current game.
 47// The best score ever reached is kept for the leaderboard.
 48func NewGame(cur realm) string {
 49	player := cur.Previous().Address().String()
 50	h := runtime.ChainHeight()
 51	salt := addrSeed(player)
 52	g := &Game{
 53		Board:   NewBoardSeeded(int(h) + salt),
 54		Seed:    salt,
 55		Started: h,
 56		Updated: h,
 57	}
 58	games.Set(player, g)
 59	if !best.Has(player) {
 60		best.Set(player, 0) // registers the player on the leaderboard
 61	}
 62	totalGames++
 63	chain.Emit("NewGame", "player", player)
 64	return "new game started: " + realmPath + ":" + player
 65}
 66
 67// Move slides the signer's board once: dir is up, down, left or right
 68// (or u, d, l, r). A move that changes nothing is not counted.
 69func Move(cur realm, dir string) string {
 70	player := cur.Previous().Address().String()
 71	g := mustGame(player)
 72	d, ok := parseDir(dir)
 73	if !ok {
 74		panic("invalid direction " + strings.TrimSpace(dir) + ": use up, down, left or right")
 75	}
 76	_, msg := step(player, g, d)
 77	return msg
 78}
 79
 80// Play applies a sequence of moves in a single transaction, e.g. "lldrul"
 81// (u=up, d=down, l=left, r=right; spaces and commas are ignored). It stops
 82// early when the game is over. At most MaxPlayMoves moves per call.
 83func Play(cur realm, moves string) string {
 84	player := cur.Previous().Address().String()
 85	g := mustGame(player)
 86	var dirs []int
 87	for _, c := range strings.ToLower(moves) {
 88		switch c {
 89		case ' ', ',':
 90			continue
 91		case 'u':
 92			dirs = append(dirs, DIR_UP)
 93		case 'r':
 94			dirs = append(dirs, DIR_RIGHT)
 95		case 'd':
 96			dirs = append(dirs, DIR_DOWN)
 97		case 'l':
 98			dirs = append(dirs, DIR_LEFT)
 99		default:
100			panic("invalid move " + string(c) + ": use only u, d, l, r")
101		}
102	}
103	if len(dirs) == 0 {
104		panic("no moves given: e.g. lldrul")
105	}
106	if len(dirs) > MaxPlayMoves {
107		panic("too many moves: at most " + Itoa(MaxPlayMoves) + " per call")
108	}
109	applied := 0
110	for _, d := range dirs {
111		if g.Board.Over {
112			break
113		}
114		if moved, _ := step(player, g, d); moved {
115			applied++
116		}
117	}
118	out := "applied " + Itoa(applied) + "/" + Itoa(len(dirs)) + " moves, score " + Itoa(g.Board.Score)
119	if g.Board.Over {
120		out += ", game over"
121	}
122	return out
123}
124
125// ScoreOf returns the current score of a player (0 if no game).
126func ScoreOf(player address) int {
127	v := games.Get(player.String())
128	if v == nil {
129		return 0
130	}
131	return v.(*Game).Board.Score
132}
133
134// BestOf returns the best score a player ever reached.
135func BestOf(player address) int {
136	v := best.Get(player.String())
137	if v == nil {
138		return 0
139	}
140	return v.(int)
141}
142
143func mustGame(player string) *Game {
144	v := games.Get(player)
145	if v == nil {
146		panic("no game yet: call NewGame first")
147	}
148	return v.(*Game)
149}
150
151// step applies one direction and records score, best and events.
152func step(player string, g *Game, d int) (bool, string) {
153	if g.Board.Over {
154		return false, "game over: call NewGame to play again"
155	}
156	h := runtime.ChainHeight()
157	moved, msg := g.Board.Move(d, int(h)+g.Seed)
158	if !moved {
159		return false, msg
160	}
161	g.Updated = h
162	totalMoves++
163	if g.Board.Score > BestOfKey(player) {
164		best.Set(player, g.Board.Score)
165	}
166	chain.Emit("Move", "player", player, "dir", dirName(d), "score", Itoa(g.Board.Score))
167	if g.Board.Over {
168		chain.Emit("GameOver", "player", player, "score", Itoa(g.Board.Score))
169		return true, "game over, final score " + Itoa(g.Board.Score)
170	}
171	return true, msg
172}
173
174// BestOfKey is BestOf for a raw address string.
175func BestOfKey(player string) int {
176	v := best.Get(player)
177	if v == nil {
178		return 0
179	}
180	return v.(int)
181}
182
183func parseDir(s string) (int, bool) {
184	switch strings.ToLower(strings.TrimSpace(s)) {
185	case "up", "u":
186		return DIR_UP, true
187	case "right", "r":
188		return DIR_RIGHT, true
189	case "down", "d":
190		return DIR_DOWN, true
191	case "left", "l":
192		return DIR_LEFT, true
193	}
194	return 0, false
195}
196
197func dirName(d int) string {
198	switch d {
199	case DIR_UP:
200		return "up"
201	case DIR_RIGHT:
202		return "right"
203	case DIR_DOWN:
204		return "down"
205	}
206	return "left"
207}
208
209// addrSeed folds an address into a small positive salt.
210func addrSeed(a string) int {
211	s := 7
212	for i := 0; i < len(a); i++ {
213		s = (s*31 + int(a[i])) & 0xffffff
214	}
215	return s
216}
217
218func maxTile(b Board) int {
219	m := 0
220	for i := 0; i < N; i++ {
221		for j := 0; j < N; j++ {
222			if b.Cells[i][j] > m {
223				m = b.Cells[i][j]
224			}
225		}
226	}
227	return m
228}
229
230func shortAddr(a string) string {
231	if len(a) > 14 {
232		return a[:7] + "…" + a[len(a)-4:]
233	}
234	return a
235}
236
237// ---- rendering -------------------------------------------------------------
238
239// Render serves the tavern home (path "") or a player's board (path = g1...).
240func Render(path string) string {
241	path = strings.TrimSpace(path)
242	if path == "" {
243		return renderHome()
244	}
245	if !address(path).IsValid() {
246		return "# Not found\n\n`" + path + "` is not a player address. [Back to the tavern](" + realmPath + ")\n"
247	}
248	return renderPlayer(path)
249}
250
251func renderHome() string {
252	var sb strings.Builder
253	sb.WriteString("# 🍺 Tavern2048\n\n")
254	sb.WriteString("_The classic 2048 puzzle, played one signed transaction at a time on gno.land._\n\n")
255	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. ")
256	sb.WriteString("New tiles are derived from the block height, so every game is verifiable by replaying the chain.\n\n")
257	sb.WriteString("**" + Itoa(best.Size()) + "** players · **" + Itoa(totalGames) + "** games · **" + Itoa(totalMoves) + "** on-chain moves\n\n")
258
259	sb.WriteString("## How to play\n\n")
260	sb.WriteString("1. [Start a new game](" + realmPath + "$help&func=NewGame) — signs `NewGame`.\n")
261	sb.WriteString("2. Slide the tiles: [⬆ up](" + realmPath + "$help&func=Move&dir=up) · ")
262	sb.WriteString("[⬇ down](" + realmPath + "$help&func=Move&dir=down) · ")
263	sb.WriteString("[⬅ left](" + realmPath + "$help&func=Move&dir=left) · ")
264	sb.WriteString("[➡ right](" + realmPath + "$help&func=Move&dir=right), ")
265	sb.WriteString("or chain up to " + Itoa(MaxPlayMoves) + " moves in one transaction with `Play(\"lldrul\")`.\n")
266	sb.WriteString("3. Watch your board at `" + realmPath + ":<your address>`.\n\n")
267	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")
268
269	sb.WriteString("## 🏆 Leaderboard\n\n")
270	sb.WriteString(renderLeaderboard())
271	return sb.String()
272}
273
274type entry struct {
275	player string
276	score  int
277}
278
279func renderLeaderboard() string {
280	var all []entry
281	best.Iterate("", "", func(k string, v any) bool {
282		all = append(all, entry{k, v.(int)})
283		return false
284	})
285	if len(all) == 0 {
286		return "_No scores yet — be the first gnome on the board._\n"
287	}
288	// selection sort on the top N only (best first, ties by address)
289	lim := TopN
290	if len(all) < lim {
291		lim = len(all)
292	}
293	for i := 0; i < lim; i++ {
294		mx := i
295		for j := i + 1; j < len(all); j++ {
296			if all[j].score > all[mx].score {
297				mx = j
298			}
299		}
300		all[i], all[mx] = all[mx], all[i]
301	}
302	medals := []string{"🥇", "🥈", "🥉"}
303	var sb strings.Builder
304	sb.WriteString("| # | player | best score | current game |\n|---|---|---|---|\n")
305	for i := 0; i < lim; i++ {
306		rank := Itoa(i + 1)
307		if i < len(medals) {
308			rank = medals[i]
309		}
310		cur := "—"
311		if v := games.Get(all[i].player); v != nil {
312			g := v.(*Game)
313			cur = Itoa(g.Board.Score)
314			if g.Board.Over {
315				cur += " (over)"
316			}
317		}
318		sb.WriteString("| " + rank + " | [" + shortAddr(all[i].player) + "](" + realmPath + ":" + all[i].player + ") | " + Itoa(all[i].score) + " | " + cur + " |\n")
319	}
320	return sb.String()
321}
322
323func renderPlayer(player string) string {
324	var sb strings.Builder
325	sb.WriteString("# 🍺 Tavern2048 — " + shortAddr(player) + "\n\n")
326	v := games.Get(player)
327	if v == nil {
328		sb.WriteString("This gnome has not started a game yet. [Start a new game](" + realmPath + "$help&func=NewGame).\n\n")
329		sb.WriteString("[← Back to the tavern](" + realmPath + ")\n")
330		return sb.String()
331	}
332	g := v.(*Game)
333	b := g.Board
334	sb.WriteString(boardSVG(b) + "\n\n")
335	status := "in play"
336	if b.Over {
337		status = "**game over**"
338	}
339	sb.WriteString("**Score** " + Itoa(b.Score) + " · **Best** " + Itoa(BestOfKey(player)) + " · **Moves** " + Itoa(b.Moves) + " · **Top tile** " + Itoa(maxTile(b)) + " · " + status + "\n\n")
340	sb.WriteString("Started at block " + Itoa(int(g.Started)) + ", last move at block " + Itoa(int(g.Updated)) + ".\n\n")
341	if b.Over {
342		sb.WriteString("[Start a new game](" + realmPath + "$help&func=NewGame)\n\n")
343	} else {
344		sb.WriteString("Move: [⬆ up](" + realmPath + "$help&func=Move&dir=up) · ")
345		sb.WriteString("[⬇ down](" + realmPath + "$help&func=Move&dir=down) · ")
346		sb.WriteString("[⬅ left](" + realmPath + "$help&func=Move&dir=left) · ")
347		sb.WriteString("[➡ right](" + realmPath + "$help&func=Move&dir=right)\n\n")
348		sb.WriteString("Or play a whole combo in one transaction:\n\n")
349		sb.WriteString("<gno-form exec=\"Play\">\n")
350		sb.WriteString("<gno-input name=\"moves\" placeholder=\"e.g. lldrul (u/d/l/r)\" />\n")
351		sb.WriteString("</gno-form>\n\n")
352	}
353	sb.WriteString("[← Back to the tavern](" + realmPath + ")\n")
354	return sb.String()
355}
356
357func tileColors(v int) (bg, fg string) {
358	switch v {
359	case 0:
360		return "#cdc1b4", "#776e65"
361	case 2:
362		return "#eee4da", "#776e65"
363	case 4:
364		return "#ede0c8", "#776e65"
365	case 8:
366		return "#f2b179", "#f9f6f2"
367	case 16:
368		return "#f59563", "#f9f6f2"
369	case 32:
370		return "#f67c5f", "#f9f6f2"
371	case 64:
372		return "#f65e3b", "#f9f6f2"
373	case 128:
374		return "#edcf72", "#f9f6f2"
375	case 256:
376		return "#edcc61", "#f9f6f2"
377	case 512:
378		return "#edc850", "#f9f6f2"
379	case 1024:
380		return "#edc53f", "#f9f6f2"
381	case 2048:
382		return "#edc22e", "#f9f6f2"
383	}
384	return "#3c3a32", "#f9f6f2"
385}
386
387// boardSVG draws the board as an inline SVG image (data URI) for gnoweb.
388func boardSVG(b Board) string {
389	const cell = 100
390	const gap = 12
391	const size = gap + N*(cell+gap)
392	var sb strings.Builder
393	sb.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" width="` + Itoa(size) + `" height="` + Itoa(size) + `" viewBox="0 0 ` + Itoa(size) + ` ` + Itoa(size) + `">`)
394	sb.WriteString(`<rect width="` + Itoa(size) + `" height="` + Itoa(size) + `" rx="14" fill="#bbada0"/>`)
395	for i := 0; i < N; i++ {
396		for j := 0; j < N; j++ {
397			x := gap + j*(cell+gap)
398			y := gap + i*(cell+gap)
399			v := b.Cells[i][j]
400			bg, fg := tileColors(v)
401			sb.WriteString(`<rect x="` + Itoa(x) + `" y="` + Itoa(y) + `" width="` + Itoa(cell) + `" height="` + Itoa(cell) + `" rx="8" fill="` + bg + `"/>`)
402			if v != 0 {
403				txt := Itoa(v)
404				fs := 52
405				switch {
406				case len(txt) >= 5:
407					fs = 26
408				case len(txt) == 4:
409					fs = 34
410				case len(txt) == 3:
411					fs = 42
412				}
413				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>`)
414			}
415		}
416	}
417	sb.WriteString(`</svg>`)
418	return "![Tavern2048 board](data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString([]byte(sb.String())) + ")"
419}