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/g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru/minichess"
gno = "0.9"

[addpkg]
  creator = "g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru"
  height = 727720
  max_deposit = "6000000ugnot"

minichess.gno

// Package minichess is an on-chain chess game (standard 8x8 board).
//
// Two ways to play:
//
//   - Solo: NewSoloGame starts a game against the built-in bot. The bot
//     replies inside the same transaction as your move.
//   - Two players: Challenge creates a game (open to anyone, or for one
//     invited address); AcceptChallenge takes the empty seat.
//
// Moves use coordinate notation: "e2e4", "g1f3", castling as the king's
// move ("e1g1"), en passant as the pawn's move to the target square, and
// promotion as "e7e8" (queen) or "e7e8n" (under-promotion). Visit the realm
// in gnoweb to see the board and click legal moves.
package minichess

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

	mc "gno.land/p/g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru/minichess"
	"gno.land/p/nt/avl/v0"
)

// Mode is how a game is played.
type Mode int

const (
	ModeSolo      Mode = iota // human vs bot
	ModeTwoPlayer             // human vs human
)

func (m Mode) String() string {
	if m == ModeSolo {
		return "vs bot"
	}
	return "two-player"
}

// State is a game's lifecycle stage.
type State int

const (
	StateWaiting State = iota // challenge waiting for an opponent
	StateActive               // being played
	StateWhiteWon
	StateBlackWon
	StateDraw
	StateCancelled // challenge withdrawn before anyone joined
)

func (s State) String() string {
	switch s {
	case StateWaiting:
		return "waiting for opponent"
	case StateActive:
		return "in progress"
	case StateWhiteWon:
		return "white won"
	case StateBlackWon:
		return "black won"
	case StateDraw:
		return "draw"
	case StateCancelled:
		return "cancelled"
	}
	return "unknown"
}

// Finished reports whether the game is over.
func (s State) Finished() bool { return s >= StateWhiteWon }

// Game is one game of minichess.
type Game struct {
	ID        int
	Mode      Mode
	White     address // empty: the bot (solo) or an open seat (waiting)
	Black     address
	Creator   address
	Invitee   address // two-player challenge target; empty = open to all
	BotLevel  int     // solo only
	Pos       mc.Position
	Moves     []string // coordinate notation, in order
	History   []string // board keys since the last capture or pawn move
	Hashes    []uint64 // position hashes since the last capture or pawn move (for the bot)
	State     State
	Reason    string  // how the game ended
	DrawOffer address // player with a pending draw offer
	CreatedAt int64   // block height
	UpdatedAt int64
}

var (
	games       = avl.NewTree() // padded id -> *Game
	openGames   = avl.NewTree() // padded id -> *Game, challenges awaiting an opponent
	playerGames = avl.NewTree() // address -> []int
	nextID      = 1
	realmPath   string // e.g. "/r/g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru/minichess", for links
)

func init() {
	p := unsafe.CurrentRealm().PkgPath()
	realmPath = strings.TrimPrefix(p, "gno.land")
}

// ---------------------------------------------------------------------------
// Public, state-changing functions (crossing).

// NewSoloGame starts a game against the bot.
// color: "white", "black" or "random". level: 1 (easy) to 3 (hard).
// If you play black, the bot makes the first move immediately.
func NewSoloGame(cur realm, color string, level int) int {
	caller := cur.Previous().Address()
	if level < mc.MinLevel || level > mc.MaxLevel {
		panic("level must be between " + strconv.Itoa(mc.MinLevel) + " and " + strconv.Itoa(mc.MaxLevel))
	}
	side := parseColor(color)

	g := newGame(ModeSolo, caller)
	g.BotLevel = level
	g.State = StateActive
	if side == mc.White {
		g.White = caller
	} else {
		g.Black = caller
	}
	saveGame(g)
	addPlayerGame(caller, g.ID)
	chain.Emit("GameCreated", "id", strconv.Itoa(g.ID), "mode", "solo", "player", caller.String())

	if side == mc.Black {
		botMove(g)
	}
	return g.ID
}

// Challenge creates a two-player game. opponent may be empty (anyone can
// accept) or a g1... address (only they can accept). color is the
// challenger's side: "white", "black" or "random".
func Challenge(cur realm, opponent string, color string) int {
	caller := cur.Previous().Address()
	side := parseColor(color)

	var invitee address
	opponent = strings.TrimSpace(opponent)
	if opponent != "" {
		invitee = address(opponent)
		if !invitee.IsValid() {
			panic("invalid opponent address")
		}
		if invitee == caller {
			panic("you cannot challenge yourself")
		}
	}

	g := newGame(ModeTwoPlayer, caller)
	g.Invitee = invitee
	if side == mc.White {
		g.White = caller
	} else {
		g.Black = caller
	}
	saveGame(g)
	openGames.Set(gameKey(g.ID), g)
	addPlayerGame(caller, g.ID)
	if invitee != "" {
		addPlayerGame(invitee, g.ID)
	}
	chain.Emit("ChallengeCreated", "id", strconv.Itoa(g.ID), "creator", caller.String(), "invitee", invitee.String())
	return g.ID
}

// AcceptChallenge takes the open seat in a waiting two-player game.
func AcceptChallenge(cur realm, gameID int) {
	caller := cur.Previous().Address()
	g := mustGetGame(gameID)
	if g.State != StateWaiting {
		panic("game is not waiting for an opponent")
	}
	if caller == g.Creator {
		panic("you cannot accept your own challenge")
	}
	if g.Invitee != "" && caller != g.Invitee {
		panic("this challenge is for another player")
	}
	if g.White == "" {
		g.White = caller
	} else {
		g.Black = caller
	}
	g.State = StateActive
	openGames.Remove(gameKey(g.ID))
	touch(g)
	if g.Invitee == "" {
		addPlayerGame(caller, g.ID)
	}
	chain.Emit("ChallengeAccepted", "id", strconv.Itoa(g.ID), "player", caller.String())
}

// CancelChallenge withdraws a challenge nobody has accepted yet.
func CancelChallenge(cur realm, gameID int) {
	caller := cur.Previous().Address()
	g := mustGetGame(gameID)
	if caller != g.Creator {
		panic("only the creator can cancel this challenge")
	}
	if g.State != StateWaiting {
		panic("only waiting challenges can be cancelled")
	}
	g.State = StateCancelled
	g.Reason = "challenge withdrawn"
	openGames.Remove(gameKey(g.ID))
	touch(g)
	chain.Emit("ChallengeCancelled", "id", strconv.Itoa(g.ID))
}

// Move plays a move, e.g. "e2e4", "e1g1" (castling) or "e7e8q". In a solo game the bot
// answers in the same transaction. Returns a short summary.
func Move(cur realm, gameID int, move string) string {
	caller := cur.Previous().Address()
	g := mustGetGame(gameID)
	if g.State != StateActive {
		panic("game is not in progress (" + g.State.String() + ")")
	}
	if g.playerToMove() != caller {
		if !g.IsPlayer(caller) {
			panic("you are not a player in this game")
		}
		panic("it is not your turn")
	}

	m, err := mc.ParseMove(move)
	if err != nil {
		panic(err.Error())
	}
	lm, ok := g.Pos.FindLegal(m)
	if !ok {
		panic("illegal move: " + m.String())
	}
	g.apply(lm)
	if g.DrawOffer != "" && g.DrawOffer != caller {
		g.DrawOffer = "" // moving instead of accepting declines the offer
	}
	summary := "you played " + lm.String()

	if g.Mode == ModeSolo && g.State == StateActive {
		if bm, ok := botMove(g); ok {
			summary += ", bot played " + bm
		}
	}
	touch(g)
	if g.State.Finished() {
		summary += ". Game over: " + g.State.String() + " (" + g.Reason + ")"
	}
	return summary
}

// Resign ends the game as a loss for the caller.
func Resign(cur realm, gameID int) {
	caller := cur.Previous().Address()
	g := mustGetGame(gameID)
	if g.State != StateActive {
		panic("game is not in progress")
	}
	switch caller {
	case g.White:
		g.finish(StateBlackWon, "white resigned")
	case g.Black:
		g.finish(StateWhiteWon, "black resigned")
	default:
		panic("you are not a player in this game")
	}
	touch(g)
}

// OfferDraw offers a draw in a two-player game. If your opponent has
// already offered one, this accepts it.
func OfferDraw(cur realm, gameID int) {
	caller := cur.Previous().Address()
	g := mustGetGame(gameID)
	g.assertActiveTwoPlayer(caller)
	if g.DrawOffer != "" && g.DrawOffer != caller {
		g.finish(StateDraw, "draw agreed")
	} else {
		g.DrawOffer = caller
		chain.Emit("DrawOffered", "id", strconv.Itoa(g.ID), "by", caller.String())
	}
	touch(g)
}

// AcceptDraw accepts your opponent's pending draw offer.
func AcceptDraw(cur realm, gameID int) {
	caller := cur.Previous().Address()
	g := mustGetGame(gameID)
	g.assertActiveTwoPlayer(caller)
	if g.DrawOffer == "" || g.DrawOffer == caller {
		panic("there is no draw offer from your opponent")
	}
	g.finish(StateDraw, "draw agreed")
	touch(g)
}

// ---------------------------------------------------------------------------
// Read-only helpers (callable with vm/qeval).

// GameFEN returns the current position of a game in FEN notation.
func GameFEN(gameID int) string {
	return mustGetGame(gameID).Pos.FEN()
}

// GameStatus returns a one-line status for a game.
func GameStatus(gameID int) string {
	g := mustGetGame(gameID)
	s := g.State.String()
	if g.State == StateActive {
		s += ", " + g.Pos.Turn.String() + " to move"
	}
	if g.Reason != "" {
		s += " (" + g.Reason + ")"
	}
	return s
}

// LegalMoves returns the legal moves of a game as a space-separated list.
func LegalMoves(gameID int) string {
	g := mustGetGame(gameID)
	if g.State != StateActive {
		return ""
	}
	out := []string{}
	for _, m := range g.Pos.LegalMoves() {
		out = append(out, m.String())
	}
	return strings.Join(out, " ")
}

// ---------------------------------------------------------------------------
// Internals.

func newGame(mode Mode, creator address) *Game {
	h := runtime.ChainHeight()
	g := &Game{
		ID:        nextID,
		Mode:      mode,
		Creator:   creator,
		Pos:       mc.NewGame(),
		State:     StateWaiting,
		CreatedAt: h,
		UpdatedAt: h,
	}
	g.History = []string{g.Pos.BoardKey()}
	g.Hashes = []uint64{g.Pos.Hash()}
	nextID++
	return g
}

func parseColor(color string) mc.Color {
	switch strings.ToLower(strings.TrimSpace(color)) {
	case "white", "w", "":
		return mc.White
	case "black", "b":
		return mc.Black
	case "random", "r":
		// Deterministic but unpredictable enough for picking a side.
		if (runtime.ChainHeight()+int64(nextID))%2 == 0 {
			return mc.White
		}
		return mc.Black
	}
	panic("color must be white, black or random")
}

func gameKey(id int) string {
	s := strconv.Itoa(id)
	for len(s) < 10 {
		s = "0" + s
	}
	return s
}

func saveGame(g *Game) { games.Set(gameKey(g.ID), g) }

func getGame(id int) (*Game, bool) {
	v := games.Get(gameKey(id))
	if v == nil {
		return nil, false
	}
	return v.(*Game), true
}

func mustGetGame(id int) *Game {
	g, ok := getGame(id)
	if !ok {
		panic("game " + strconv.Itoa(id) + " not found")
	}
	return g
}

func addPlayerGame(a address, id int) {
	var ids []int
	if v := playerGames.Get(a.String()); v != nil {
		ids = v.([]int)
	}
	playerGames.Set(a.String(), append(ids, id))
}

func touch(g *Game) { g.UpdatedAt = runtime.ChainHeight() }

// IsPlayer reports whether a is one of the game's human players.
func (g *Game) IsPlayer(a address) bool {
	return a != "" && (a == g.White || a == g.Black)
}

// playerToMove is the address whose turn it is ("" = the bot).
func (g *Game) playerToMove() address {
	if g.Pos.Turn == mc.White {
		return g.White
	}
	return g.Black
}

func (g *Game) assertActiveTwoPlayer(caller address) {
	if g.Mode != ModeTwoPlayer {
		panic("draw offers are only for two-player games; resign to end a bot game")
	}
	if g.State != StateActive {
		panic("game is not in progress")
	}
	if !g.IsPlayer(caller) {
		panic("you are not a player in this game")
	}
}

// apply plays a legal move and updates the game result.
func (g *Game) apply(m mc.Move) {
	irreversible := g.Pos.IsIrreversible(m)
	g.Pos = g.Pos.Play(m)
	g.Moves = append(g.Moves, m.String())
	key := g.Pos.BoardKey()
	h := g.Pos.Hash()
	if irreversible {
		g.History = []string{key}
		g.Hashes = []uint64{h}
	} else {
		g.History = append(g.History, key)
		g.Hashes = append(g.Hashes, h)
	}

	switch g.Pos.Status() {
	case mc.Checkmate:
		if g.Pos.Turn == mc.White {
			g.finish(StateBlackWon, "checkmate")
		} else {
			g.finish(StateWhiteWon, "checkmate")
		}
		return
	case mc.Stalemate:
		g.finish(StateDraw, "stalemate")
		return
	case mc.InsufficientMaterial:
		g.finish(StateDraw, "insufficient material")
		return
	case mc.FiftyMoveDraw:
		g.finish(StateDraw, "50-move rule")
		return
	}
	reps := 0
	for _, k := range g.History {
		if k == key {
			reps++
		}
	}
	if reps >= 3 {
		g.finish(StateDraw, "threefold repetition")
	}
}

func (g *Game) finish(s State, reason string) {
	g.State = s
	g.Reason = reason
	g.DrawOffer = ""
	chain.Emit("GameOver", "id", strconv.Itoa(g.ID), "result", s.String(), "reason", reason)
}

// botMove lets the bot play if it is its turn in an active solo game.
func botMove(g *Game) (string, bool) {
	if g.Mode != ModeSolo || g.State != StateActive || g.playerToMove() != "" {
		return "", false
	}
	seed := g.ID*1009 + len(g.Moves)
	m, ok := mc.BestMoveWithHistory(g.Pos, g.BotLevel, seed, g.Hashes)
	if !ok {
		return "", false
	}
	g.apply(m)
	return m.String(), true
}

minichess_test.gno

package minichess

import (
	"strings"
	"testing"

	mc "gno.land/p/g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru/minichess"
	"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")
	carol = testutils.TestAddress("carol")
)

func reset() {
	games = avl.NewTree()
	openGames = avl.NewTree()
	playerGames = avl.NewTree()
	nextID = 1
}

func TestSoloAsWhite(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := NewSoloGame(cross(cur), "white", 1)
	g := mustGetGame(id)
	uassert.Equal(t, alice.String(), g.White.String())
	uassert.Equal(t, "", g.Black.String())
	uassert.Equal(t, 0, len(g.Moves))

	out := Move(cross(cur), id, "b1c3")
	uassert.True(t, strings.Contains(out, "bot played"), out)
	uassert.Equal(t, 2, len(g.Moves))
	uassert.Equal(t, int(mc.White), int(g.Pos.Turn))
}

func TestSoloAsBlackBotMovesFirst(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := NewSoloGame(cross(cur), "black", 2)
	g := mustGetGame(id)
	uassert.Equal(t, 1, len(g.Moves))
	uassert.Equal(t, int(mc.Black), int(g.Pos.Turn))
}

func TestMoveValidation(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := NewSoloGame(cross(cur), "white", 1)

	uassert.AbortsWithMessage(t, cur, "illegal move: e2e5", func() {
		Move(cross(cur), id, "e2e5")
	})
	uassert.AbortsWithMessage(t, cur, "chess: move must look like e2e4 or e7e8q", func() {
		Move(cross(cur), id, "b2")
	})
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "you are not a player in this game", func() {
		Move(cross(cur), id, "b2b3")
	})
	uassert.AbortsWithMessage(t, cur, "game 99 not found", func() {
		Move(cross(cur), 99, "b2b3")
	})
	uassert.AbortsWithMessage(t, cur, "level must be between 1 and 3", func() {
		NewSoloGame(cross(cur), "white", 4)
	})
}

func TestTwoPlayerCheckmate(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "", "white")
	g := mustGetGame(id)
	uassert.Equal(t, int(StateWaiting), int(g.State))
	uassert.True(t, strings.Contains(Render(""), "func=AcceptChallenge&gameID=1"))

	uassert.AbortsWithMessage(t, cur, "you cannot accept your own challenge", func() {
		AcceptChallenge(cross(cur), id)
	})
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	AcceptChallenge(cross(cur), id)
	uassert.Equal(t, int(StateActive), int(g.State))
	uassert.Equal(t, bob.String(), g.Black.String())
	uassert.True(t, strings.Contains(Render(""), "_None right now._"))

	uassert.AbortsWithMessage(t, cur, "it is not your turn", func() {
		Move(cross(cur), id, "e7e5")
	})

	// Scholar's mate, with castling-free development: 4. Qxf7#.
	seq := []string{"e2e4", "e7e5", "f1c4", "b8c6", "d1h5", "g8f6", "h5f7"}
	for i, m := range seq {
		if i%2 == 0 {
			testing.SetOriginCaller(alice)
			testing.SetRealm(testing.NewUserRealm(alice))
		} else {
			testing.SetOriginCaller(bob)
			testing.SetRealm(testing.NewUserRealm(bob))
		}
		Move(cross(cur), id, m)
	}
	uassert.Equal(t, int(StateWhiteWon), int(g.State))
	uassert.Equal(t, "checkmate", g.Reason)

	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "game is not in progress (white won)", func() {
		Move(cross(cur), id, "e8f7")
	})
}

func TestInviteOnlyAndCancel(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	uassert.AbortsWithMessage(t, cur, "you cannot challenge yourself", func() {
		Challenge(cross(cur), alice.String(), "white")
	})
	uassert.AbortsWithMessage(t, cur, "invalid opponent address", func() {
		Challenge(cross(cur), "not-an-address", "white")
	})
	id := Challenge(cross(cur), bob.String(), "black")

	testing.SetOriginCaller(carol)
	testing.SetRealm(testing.NewUserRealm(carol))
	uassert.AbortsWithMessage(t, cur, "this challenge is for another player", func() {
		AcceptChallenge(cross(cur), id)
	})
	uassert.AbortsWithMessage(t, cur, "only the creator can cancel this challenge", func() {
		CancelChallenge(cross(cur), id)
	})

	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	CancelChallenge(cross(cur), id)
	uassert.Equal(t, int(StateCancelled), int(mustGetGame(id).State))

	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	uassert.AbortsWithMessage(t, cur, "game is not waiting for an opponent", func() {
		AcceptChallenge(cross(cur), id)
	})
}

func TestDrawAndResign(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), bob.String(), "white")
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	AcceptChallenge(cross(cur), id)
	g := mustGetGame(id)

	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	OfferDraw(cross(cur), id)
	uassert.AbortsWithMessage(t, cur, "there is no draw offer from your opponent", func() {
		AcceptDraw(cross(cur), id)
	})
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	AcceptDraw(cross(cur), id)
	uassert.Equal(t, int(StateDraw), int(g.State))

	// New game: offer is declined by moving, then black resigns.
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id2 := Challenge(cross(cur), "", "white")
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	AcceptChallenge(cross(cur), id2)
	g2 := mustGetGame(id2)
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	Move(cross(cur), id2, "b1c3")
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	OfferDraw(cross(cur), id2)
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	Move(cross(cur), id2, "g8f6")
	uassert.Equal(t, "", g2.DrawOffer.String())
	Resign(cross(cur), id2)
	uassert.Equal(t, int(StateWhiteWon), int(g2.State))
}

func TestThreefoldRepetition(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), "", "white")
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	AcceptChallenge(cross(cur), id)
	// Knights hop out and back twice: the start position occurs 3 times.
	moves := []string{"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8"}
	for i, m := range moves {
		if i%2 == 0 {
			testing.SetOriginCaller(alice)
			testing.SetRealm(testing.NewUserRealm(alice))
		} else {
			testing.SetOriginCaller(bob)
			testing.SetRealm(testing.NewUserRealm(bob))
		}
		Move(cross(cur), id, m)
	}
	g := mustGetGame(id)
	uassert.Equal(t, int(StateDraw), int(g.State))
	uassert.Equal(t, "threefold repetition", g.Reason)
}

func TestSpecialMovesInRealm(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := Challenge(cross(cur), bob.String(), "white")
	testing.SetOriginCaller(bob)
	testing.SetRealm(testing.NewUserRealm(bob))
	AcceptChallenge(cross(cur), id)
	g := mustGetGame(id)
	// Castling and en passant through the public API.
	moves := []string{"e2e4", "a7a6", "e4e5", "d7d5", "e5d6", "c7d6", "g1f3", "b8c6", "f1e2", "c8g4", "e1g1"}
	for i, m := range moves {
		if i%2 == 0 {
			testing.SetOriginCaller(alice)
			testing.SetRealm(testing.NewUserRealm(alice))
		} else {
			testing.SetOriginCaller(bob)
			testing.SetRealm(testing.NewUserRealm(bob))
		}
		Move(cross(cur), id, m)
	}
	uassert.Equal(t, int(mc.King), int(g.Pos.PieceAt("g1")))
	uassert.Equal(t, int(mc.Rook), int(g.Pos.PieceAt("f1")))
	uassert.Equal(t, int(mc.Empty), int(g.Pos.PieceAt("d5")))
	uassert.Equal(t, int(StateActive), int(g.State))
}

func TestRender(cur realm, t *testing.T) {
	reset()
	testing.SetOriginCaller(alice)
	testing.SetRealm(testing.NewUserRealm(alice))
	id := NewSoloGame(cross(cur), "white", 1)
	home := Render("")
	uassert.True(t, strings.Contains(home, "# ♟ Mini Chess"))
	uassert.True(t, strings.Contains(home, "$help&func=NewSoloGame&color=white&level=1"))

	page := Render("game/1")
	uassert.True(t, strings.Contains(page, "data:image/svg+xml;base64,"))
	uassert.True(t, strings.Contains(page, "$help&func=Move&gameID=1&move=b1c3"), page)
	uassert.True(t, strings.Contains(page, "White to move"))

	uassert.True(t, strings.Contains(Render("player/"+alice.String()), "#1"))
	uassert.True(t, strings.Contains(Render("rules"), "en passant"))
	uassert.True(t, strings.Contains(Render("game/42"), "does not exist"))
	uassert.Equal(t, mc.StartFEN, GameFEN(id))
	uassert.Equal(t, "in progress, white to move", GameStatus(id))
}

render.gno

package minichess

import (
	"encoding/base64"
	"strconv"
	"strings"

	mc "gno.land/p/g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru/minichess"
)

const listLimit = 10

// Render serves the gnoweb pages:
//
//	""               home: start a game, open challenges, recent games
//	"game/<id>"      a board with clickable legal moves
//	"player/<addr>"  a player's games
//	"rules"          how to enter moves and the draw rules
func Render(path string) string {
	path = strings.Trim(path, "/")
	switch {
	case path == "":
		return renderHome()
	case path == "rules":
		return renderRules()
	case strings.HasPrefix(path, "game/"):
		id, err := strconv.Atoi(strings.TrimPrefix(path, "game/"))
		if err != nil {
			return "# Not found\n\nBad game id."
		}
		g, ok := getGame(id)
		if !ok {
			return "# Not found\n\nGame " + strconv.Itoa(id) + " does not exist."
		}
		return renderGame(g)
	case strings.HasPrefix(path, "player/"):
		return renderPlayer(address(strings.TrimPrefix(path, "player/")))
	}
	return "# Not found\n\n[Back to Mini Chess](" + realmPath + ")"
}

// actionLink builds a gnoweb link that opens a prefilled call form.
func actionLink(label, fn string, args ...string) string {
	url := realmPath + "$help&func=" + fn
	for i := 0; i+1 < len(args); i += 2 {
		url += "&" + args[i] + "=" + args[i+1]
	}
	return "[" + label + "](" + url + ")"
}

func gameLink(id int) string {
	return "[#" + strconv.Itoa(id) + "](" + realmPath + ":game/" + strconv.Itoa(id) + ")"
}

func short(a address) string {
	s := a.String()
	if len(s) > 12 {
		return s[:7] + "…" + s[len(s)-4:]
	}
	return s
}

func playerName(g *Game, a address) string {
	if a == "" {
		if g.Mode == ModeSolo {
			return "🤖 bot (" + mc.Level(g.BotLevel).Name + ")"
		}
		return "_open seat_"
	}
	return "[" + short(a) + "](" + realmPath + ":player/" + a.String() + ")"
}

func renderHome() string {
	var sb strings.Builder
	sb.WriteString("# ♟ Mini Chess\n\n")
	sb.WriteString("Classic 8×8 chess, fully on-chain — play the bot or challenge a friend. ")
	sb.WriteString("[Rules](" + realmPath + ":rules)\n\n")

	sb.WriteString("## Play the bot\n\n")
	sb.WriteString("| Level | Play white | Play black |\n|---|---|---|\n")
	for lvl := mc.MinLevel; lvl <= mc.MaxLevel; lvl++ {
		l := strconv.Itoa(lvl)
		sb.WriteString("| " + mc.Level(lvl).Name + " | " +
			actionLink("Start as white", "NewSoloGame", "color", "white", "level", l) + " | " +
			actionLink("Start as black", "NewSoloGame", "color", "black", "level", l) + " |\n")
	}

	sb.WriteString("\n## Play a friend\n\n")
	sb.WriteString("- " + actionLink("Create an open challenge", "Challenge", "opponent", "", "color", "random") + " — anyone can join\n")
	sb.WriteString("- " + actionLink("Challenge a specific player", "Challenge", "opponent", "g1...", "color", "white") + " — paste their address\n\n")

	sb.WriteString("## Open challenges\n\n")
	open := 0
	openGames.ReverseIterate("", "", func(_ string, v any) bool {
		g := v.(*Game)
		side := "white"
		if g.White == "" {
			side = "black"
		}
		who := "anyone"
		if g.Invitee != "" {
			who = playerName(g, g.Invitee)
		}
		sb.WriteString("- " + gameLink(g.ID) + " by " + playerName(g, g.Creator) +
			" — you play " + side + ", for " + who + " · " +
			actionLink("Accept", "AcceptChallenge", "gameID", strconv.Itoa(g.ID)) + "\n")
		open++
		return open >= listLimit
	})
	if open == 0 {
		sb.WriteString("_None right now._\n")
	}

	sb.WriteString("\n## Recent games\n\n")
	sb.WriteString("| Game | White | Black | Mode | Status |\n|---|---|---|---|---|\n")
	n := 0
	games.ReverseIterate("", "", func(_ string, v any) bool {
		g := v.(*Game)
		if g.State == StateWaiting || g.State == StateCancelled {
			return false
		}
		sb.WriteString("| " + gameLink(g.ID) + " | " + playerName(g, g.White) + " | " +
			playerName(g, g.Black) + " | " + g.Mode.String() + " | " + statusText(g) + " |\n")
		n++
		return n >= listLimit
	})
	if n == 0 {
		sb.WriteString("| — | | | | no games yet |\n")
	}
	return sb.String()
}

func statusText(g *Game) string {
	if g.State == StateActive {
		return g.Pos.Turn.String() + " to move"
	}
	return g.State.String()
}

func renderGame(g *Game) string {
	var sb strings.Builder
	id := strconv.Itoa(g.ID)
	sb.WriteString("# Game #" + id + "\n\n")
	sb.WriteString("⚪ White: " + playerName(g, g.White) + " · ⚫ Black: " + playerName(g, g.Black) + " · " + g.Mode.String() + "\n\n")

	// Status line.
	switch {
	case g.State == StateActive:
		turn := g.Pos.Turn.String()
		line := "**" + strings.ToUpper(turn[:1]) + turn[1:] + " to move**"
		if g.Pos.InCheck() {
			line += " — check!"
		}
		if g.DrawOffer != "" {
			line += " · draw offered by " + playerName(g, g.DrawOffer)
		}
		sb.WriteString(line + "\n\n")
	case g.State == StateWaiting:
		sb.WriteString("**Waiting for an opponent.** " +
			actionLink("Accept challenge", "AcceptChallenge", "gameID", id) + " · " +
			actionLink("Cancel (creator)", "CancelChallenge", "gameID", id) + "\n\n")
	default:
		sb.WriteString("**Game over: " + g.State.String() + "** (" + g.Reason + ")\n\n")
	}

	sb.WriteString(renderBoardSVG(g) + "\n\n")

	if g.State == StateActive {
		sb.WriteString("### Your move\n\n")
		if g.Mode == ModeSolo && g.playerToMove() == "" {
			sb.WriteString("_The bot is thinking…_\n\n")
		} else {
			sb.WriteString(renderMoveLinks(g))
			sb.WriteString("\n" + actionLink("Type a move", "Move", "gameID", id, "move", "") +
				" · " + actionLink("Resign", "Resign", "gameID", id))
			if g.Mode == ModeTwoPlayer {
				sb.WriteString(" · " + actionLink("Offer draw", "OfferDraw", "gameID", id))
				if g.DrawOffer != "" {
					sb.WriteString(" · " + actionLink("Accept draw", "AcceptDraw", "gameID", id))
				}
			}
			sb.WriteString("\n\n")
		}
	}

	sb.WriteString("### Moves\n\n")
	if len(g.Moves) == 0 {
		sb.WriteString("_No moves yet._\n")
	} else {
		for i := 0; i < len(g.Moves); i += 2 {
			sb.WriteString(strconv.Itoa(i/2+1) + ". " + g.Moves[i])
			if i+1 < len(g.Moves) {
				sb.WriteString(" " + g.Moves[i+1])
			}
			sb.WriteString("  \n")
		}
	}
	sb.WriteString("\n`" + g.Pos.FEN() + "`\n\n[← All games](" + realmPath + ")\n")
	return sb.String()
}

var glyphs = [7]string{"", "♟", "♞", "♝", "♜", "♛", "♚"}

// renderMoveLinks lists legal moves grouped by the piece that moves.
func renderMoveLinks(g *Game) string {
	moves := g.Pos.LegalMoves()
	if len(moves) == 0 {
		return ""
	}
	var sb strings.Builder
	id := strconv.Itoa(g.ID)
	// Group by origin square in board order.
	for from := 0; from < mc.NumSquares; from++ {
		var links []string
		for _, m := range moves {
			if m.From == from {
				links = append(links, actionLink(m.String()[2:], "Move", "gameID", id, "move", m.String()))
			}
		}
		if len(links) == 0 {
			continue
		}
		pc := g.Pos.Board[from]
		sb.WriteString("- " + glyphs[pc.Type()] + " **" + mc.SquareName(from) + "** → " + strings.Join(links, " ") + "\n")
	}
	return sb.String()
}

const (
	sqPx   = 56
	margin = 22
)

// renderBoardSVG draws the board as an inline SVG image (white at bottom).
func renderBoardSVG(g *Game) string {
	size := mc.Size*sqPx + margin
	var sb strings.Builder
	sb.WriteString(`<svg xmlns="http://www.w3.org/2000/svg" width="` + strconv.Itoa(size) +
		`" height="` + strconv.Itoa(size) + `" viewBox="0 0 ` + strconv.Itoa(size) + " " + strconv.Itoa(size) +
		`" font-family="DejaVu Sans,Segoe UI Symbol,Noto Sans Symbols2,sans-serif">`)
	sb.WriteString(`<rect width="100%" height="100%" fill="#2b2b2b"/>`)

	from, to := -1, -1
	if n := len(g.Moves); n > 0 {
		if m, err := mc.ParseMove(g.Moves[n-1]); err == nil {
			from, to = m.From, m.To
		}
	}
	checkSq := -1
	if g.State == StateActive || g.Reason == "checkmate" {
		if g.Pos.InCheck() {
			k := mc.King
			if g.Pos.Turn == mc.Black {
				k = -mc.King
			}
			for i := 0; i < mc.NumSquares; i++ {
				if g.Pos.Board[i] == k {
					checkSq = i
				}
			}
		}
	}

	for r := 0; r < mc.Size; r++ {
		for f := 0; f < mc.Size; f++ {
			sq := r*mc.Size + f
			x := margin + f*sqPx
			y := (mc.Size - 1 - r) * sqPx
			fill := "#eeeed2"
			if (r+f)%2 == 0 {
				fill = "#769656"
			}
			if sq == from || sq == to {
				fill = "#f6f669"
				if (r+f)%2 == 0 {
					fill = "#baca2b"
				}
			}
			if sq == checkSq {
				fill = "#e05555"
			}
			sb.WriteString(`<rect x="` + strconv.Itoa(x) + `" y="` + strconv.Itoa(y) + `" width="` +
				strconv.Itoa(sqPx) + `" height="` + strconv.Itoa(sqPx) + `" fill="` + fill + `"/>`)
			pc := g.Pos.Board[sq]
			if pc == mc.Empty {
				continue
			}
			color, stroke := "#111", "#111"
			if pc.Color() == mc.White {
				color, stroke = "#fff", "#222"
			}
			sb.WriteString(`<text x="` + strconv.Itoa(x+sqPx/2) + `" y="` + strconv.Itoa(y+sqPx/2+2) +
				`" font-size="44" text-anchor="middle" dominant-baseline="middle" fill="` + color +
				`" stroke="` + stroke + `" stroke-width="1.2">` + glyphs[pc.Type()] + `</text>`)
		}
	}
	// Coordinates.
	for i := 0; i < mc.Size; i++ {
		sb.WriteString(`<text x="` + strconv.Itoa(margin/2) + `" y="` + strconv.Itoa(i*sqPx+sqPx/2+5) +
			`" font-size="14" text-anchor="middle" fill="#ddd">` + strconv.Itoa(mc.Size-i) + `</text>`)
		sb.WriteString(`<text x="` + strconv.Itoa(margin+i*sqPx+sqPx/2) + `" y="` + strconv.Itoa(mc.Size*sqPx+16) +
			`" font-size="14" text-anchor="middle" fill="#ddd">` + string(rune('a'+i)) + `</text>`)
	}
	sb.WriteString(`</svg>`)
	return "![Board for game " + strconv.Itoa(g.ID) + "](data:image/svg+xml;base64," +
		base64.StdEncoding.EncodeToString([]byte(sb.String())) + ")"
}

func renderPlayer(a address) string {
	var sb strings.Builder
	sb.WriteString("# Player " + short(a) + "\n\n")
	v := playerGames.Get(a.String())
	if v == nil {
		sb.WriteString("_No games yet._\n\n[← All games](" + realmPath + ")\n")
		return sb.String()
	}
	ids := v.([]int)
	wins, losses, draws := 0, 0, 0
	sb.WriteString("| Game | White | Black | Mode | Status |\n|---|---|---|---|---|\n")
	for i := len(ids) - 1; i >= 0; i-- {
		g, ok := getGame(ids[i])
		if !ok {
			continue
		}
		switch {
		case g.State == StateDraw:
			draws++
		case (g.State == StateWhiteWon && g.White == a) || (g.State == StateBlackWon && g.Black == a):
			wins++
		case g.State == StateWhiteWon || g.State == StateBlackWon:
			losses++
		}
		sb.WriteString("| " + gameLink(g.ID) + " | " + playerName(g, g.White) + " | " +
			playerName(g, g.Black) + " | " + g.Mode.String() + " | " + statusText(g) + " |\n")
	}
	sb.WriteString("\n**Record:** " + strconv.Itoa(wins) + " W · " + strconv.Itoa(losses) + " L · " +
		strconv.Itoa(draws) + " D\n\n[← All games](" + realmPath + ")\n")
	return sb.String()
}

func renderRules() string {
	return `# Mini Chess rules

Standard chess on the normal 8×8 board, with all the usual rules:
castling, en passant, the pawn's two-square first move and promotion.

## Entering moves

Moves are written as the from-square followed by the to-square:

| Move | Example |
|---|---|
| Normal move or capture | ` + "`e2e4`, `g1f3`, `f3e5`" + ` |
| Castling (move the king two squares) | ` + "`e1g1`" + ` (king side), ` + "`e1c1`" + ` (queen side) |
| En passant (pawn to the empty target square) | ` + "`e5d6`" + ` |
| Promotion (queen by default) | ` + "`e7e8`" + ` or ` + "`e7e8q`" + `; ` + "`e7e8n`" + ` for a knight, ` + "`b`" + ` bishop, ` + "`r`" + ` rook |

On a game page every legal move is a link, so you rarely need to type one.

## How games end

- **Checkmate** wins.
- **Stalemate**, **threefold repetition**, the **50-move rule** and **insufficient material** (king vs king, or king and one minor piece vs king) are draws and are applied automatically.
- Two-player games can also end by **resignation** or an agreed **draw**. Bot games can be resigned.

## Bot levels

| Level | Searches | Typical gas per reply |
|---|---|---|
| easy | 1 move ahead + captures | ~10–50M |
| medium | 2 moves ahead + captures | ~40–220M |
| hard | 3 moves ahead + captures | ~170–370M |

[← Back](` + realmPath + `)
`
}