Playground
board.gno
// Package minichess implements standard chess (8x8) for gno.land realms:
// position representation, FEN, full move legality (castling, en passant,
// promotion), game-end detection and a gas-bounded bot.
//
// The package is pure and stateless: Position is a value type, and every
// method returns a new Position instead of mutating the receiver.
package minichess
import (
"errors"
"strconv"
"strings"
)
const (
Size = 8
NumSquares = Size * Size
)
// Piece is a signed piece code: positive for white, negative for black.
type Piece int8
const (
Empty Piece = 0
Pawn Piece = 1
Knight Piece = 2
Bishop Piece = 3
Rook Piece = 4
Queen Piece = 5
King Piece = 6
)
// Color is the side to move.
type Color int8
const (
White Color = 0
Black Color = 1
)
func (c Color) Other() Color { return 1 - c }
func (c Color) String() string {
if c == White {
return "white"
}
return "black"
}
// Type returns the unsigned piece type.
func (p Piece) Type() Piece {
if p < 0 {
return -p
}
return p
}
// Color returns the colour of a non-empty piece.
func (p Piece) Color() Color {
if p < 0 {
return Black
}
return White
}
func colored(t Piece, c Color) Piece {
if c == Black {
return -t
}
return t
}
// Castling rights bits.
const (
CastleWK = 1 // white king side (e1g1)
CastleWQ = 2 // white queen side (e1c1)
CastleBK = 4 // black king side (e8g8)
CastleBQ = 8 // black queen side (e8c8)
)
// Position is a complete game state.
type Position struct {
Board [NumSquares]Piece // index = rank*8 + file; a1 = 0, h8 = 63
Turn Color
Castling int // CastleWK|CastleWQ|CastleBK|CastleBQ bits
EP int // en passant target square, or -1
Halfmove int // plies since the last capture or pawn move
Fullmove int // starts at 1, incremented after black moves
}
// Move is a move from one square to another, with an optional promotion
// piece type (Knight, Bishop, Rook or Queen). Castling is the king's move
// (e1g1); en passant is the capturing pawn's move to the target square.
type Move struct {
From, To int
Promo Piece
}
// StartFEN is the standard starting position.
const StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
// NewGame returns the starting position.
func NewGame() Position {
p, err := ParseFEN(StartFEN)
if err != nil {
panic(err)
}
return p
}
var pieceChars = " pnbrqk"
func pieceToChar(p Piece) string {
if p == Empty {
return "."
}
ch := string(pieceChars[p.Type()])
if p.Color() == White {
return strings.ToUpper(ch)
}
return ch
}
func charToPiece(ch byte) (Piece, bool) {
lower := ch
white := false
if ch >= 'A' && ch <= 'Z' {
lower = ch - 'A' + 'a'
white = true
}
idx := strings.IndexByte(pieceChars, lower)
if idx <= 0 {
return Empty, false
}
if white {
return Piece(idx), true
}
return -Piece(idx), true
}
// ParseFEN parses standard FEN. The halfmove and fullmove fields are
// optional.
func ParseFEN(s string) (Position, error) {
var p Position
p.EP = -1
fields := strings.Fields(s)
if len(fields) < 2 {
return p, errors.New("chess: FEN needs board and side to move")
}
ranks := strings.Split(fields[0], "/")
if len(ranks) != Size {
return p, errors.New("chess: FEN must have 8 ranks")
}
kings := [2]int{}
for i, row := range ranks {
r := Size - 1 - i
f := 0
for j := 0; j < len(row); j++ {
ch := row[j]
if ch >= '1' && ch <= '8' {
f += int(ch - '0')
continue
}
pc, ok := charToPiece(ch)
if !ok {
return p, errors.New("chess: bad FEN piece " + string(ch))
}
if f >= Size {
return p, errors.New("chess: FEN rank too long")
}
if pc == King {
kings[0]++
} else if pc == -King {
kings[1]++
}
p.Board[r*Size+f] = pc
f++
}
if f != Size {
return p, errors.New("chess: FEN rank has wrong length")
}
}
if kings[0] != 1 || kings[1] != 1 {
return p, errors.New("chess: FEN needs exactly one king per side")
}
switch fields[1] {
case "w":
p.Turn = White
case "b":
p.Turn = Black
default:
return p, errors.New("chess: FEN side must be w or b")
}
if len(fields) > 2 && fields[2] != "-" {
for _, c := range fields[2] {
switch c {
case 'K':
p.Castling |= CastleWK
case 'Q':
p.Castling |= CastleWQ
case 'k':
p.Castling |= CastleBK
case 'q':
p.Castling |= CastleBQ
default:
return p, errors.New("chess: bad FEN castling field")
}
}
}
if len(fields) > 3 && fields[3] != "-" {
sq, ok := ParseSquare(fields[3])
if !ok {
return p, errors.New("chess: bad FEN en passant square")
}
p.EP = sq
}
p.Fullmove = 1
if len(fields) > 4 {
n, err := strconv.Atoi(fields[4])
if err != nil || n < 0 {
return p, errors.New("chess: bad halfmove clock")
}
p.Halfmove = n
}
if len(fields) > 5 {
n, err := strconv.Atoi(fields[5])
if err != nil || n < 1 {
return p, errors.New("chess: bad fullmove number")
}
p.Fullmove = n
}
return p, nil
}
func (p Position) placement() string {
var sb strings.Builder
for r := Size - 1; r >= 0; r-- {
empty := 0
for f := 0; f < Size; f++ {
pc := p.Board[r*Size+f]
if pc == Empty {
empty++
continue
}
if empty > 0 {
sb.WriteString(strconv.Itoa(empty))
empty = 0
}
sb.WriteString(pieceToChar(pc))
}
if empty > 0 {
sb.WriteString(strconv.Itoa(empty))
}
if r > 0 {
sb.WriteString("/")
}
}
return sb.String()
}
func (p Position) castlingString() string {
s := ""
if p.Castling&CastleWK != 0 {
s += "K"
}
if p.Castling&CastleWQ != 0 {
s += "Q"
}
if p.Castling&CastleBK != 0 {
s += "k"
}
if p.Castling&CastleBQ != 0 {
s += "q"
}
if s == "" {
return "-"
}
return s
}
func (p Position) side() string {
if p.Turn == White {
return "w"
}
return "b"
}
// FEN returns the full FEN string of the position.
func (p Position) FEN() string {
ep := "-"
if p.EP >= 0 {
ep = SquareName(p.EP)
}
return p.placement() + " " + p.side() + " " + p.castlingString() + " " + ep +
" " + strconv.Itoa(p.Halfmove) + " " + strconv.Itoa(p.Fullmove)
}
// BoardKey identifies the position for threefold repetition: placement,
// side to move, castling rights and an en passant square only when an en
// passant capture is actually available.
func (p Position) BoardKey() string {
ep := "-"
if p.EP >= 0 && p.epCapturePossible() {
ep = SquareName(p.EP)
}
return p.placement() + " " + p.side() + " " + p.castlingString() + " " + ep
}
func (p Position) epCapturePossible() bool {
e := newEngine(&p)
for _, m := range e.legal() {
if (m>>6)&63 == p.EP && e.b[m&63].Type() == Pawn {
return true
}
}
return false
}
// PieceAt returns the piece on a square given by name, e.g. "e4".
func (p Position) PieceAt(square string) Piece {
sq, ok := ParseSquare(square)
if !ok {
return Empty
}
return p.Board[sq]
}
// SquareName converts an index to algebraic notation ("a1".."h8").
func SquareName(sq int) string {
return string(rune('a'+sq%Size)) + string(rune('1'+sq/Size))
}
// ParseSquare converts algebraic notation to an index.
func ParseSquare(s string) (int, bool) {
if len(s) != 2 {
return 0, false
}
f := int(s[0]) - 'a'
r := int(s[1]) - '1'
if f < 0 || f >= Size || r < 0 || r >= Size {
return 0, false
}
return r*Size + f, true
}
// String returns the move in coordinate notation, e.g. "e2e4" or "e7e8q".
func (m Move) String() string {
s := SquareName(m.From) + SquareName(m.To)
if m.Promo != Empty {
s += string(pieceChars[m.Promo.Type()])
}
return s
}
// ParseMove parses coordinate notation: "e2e4", "e1g1" or "e7e8n".
// It does not check legality; use Position.FindLegal for that.
func ParseMove(s string) (Move, error) {
s = strings.ToLower(strings.TrimSpace(s))
var m Move
if len(s) != 4 && len(s) != 5 {
return m, errors.New("chess: move must look like e2e4 or e7e8q")
}
from, ok1 := ParseSquare(s[0:2])
to, ok2 := ParseSquare(s[2:4])
if !ok1 || !ok2 {
return m, errors.New("chess: bad square in move " + s)
}
m.From, m.To = from, to
if len(s) == 5 {
switch s[4] {
case 'n':
m.Promo = Knight
case 'b':
m.Promo = Bishop
case 'r':
m.Promo = Rook
case 'q':
m.Promo = Queen
default:
return m, errors.New("chess: promotion must be q, r, b or n")
}
}
return m, nil
}
bot.gno
package minichess
// The bot is an iterative-deepening negamax search with alpha-beta pruning,
// a check extension and a capped quiescence search. Every level has a hard
// node budget, so the gas a bot reply costs is bounded no matter how
// complicated the position is. It is fully deterministic: the same
// position, level and seed always produce the same move.
const (
MinLevel = 1
MaxLevel = 3
mateScore = 100000
infScore = 1000000
maxPly = 12
)
// LevelInfo describes the search limits of a bot level.
type LevelInfo struct {
Name string
MaxDepth int // full-width plies searched before quiescence
QDepth int // capture plies searched after MaxDepth
Budget int // maximum nodes visited per move (bounds the gas cost)
}
var levels = [MaxLevel + 1]LevelInfo{
{},
{Name: "easy", MaxDepth: 1, QDepth: 2, Budget: 200},
{Name: "medium", MaxDepth: 2, QDepth: 3, Budget: 900},
{Name: "hard", MaxDepth: 3, QDepth: 3, Budget: 1500},
}
// Level returns the limits for a level, clamped to [MinLevel, MaxLevel].
func Level(level int) LevelInfo {
if level < MinLevel {
level = MinLevel
}
if level > MaxLevel {
level = MaxLevel
}
return levels[level]
}
// Evaluate scores the position in centipawns from the side to move's view.
func (p Position) Evaluate() int {
return newEngine(&p).eval()
}
func (e *engine) eval() int {
if e.turn == Black {
return -e.score
}
return e.score
}
// BestMove returns the bot's choice for the side to move. seed breaks ties
// between equally scored moves so games don't all look identical; pass
// something like gameID*1000+ply. ok is false if there are no legal moves.
func BestMove(p Position, level int, seed int) (Move, bool) {
best, _, ok := searchWith(p, Level(level), seed, nil)
return best, ok
}
// BestMoveWithHistory is BestMove for a game in progress: history holds
// the Hash of earlier positions (since the last capture or pawn move).
// Moves that repeat one of them are scored as a draw, so the bot avoids
// repetition when it is ahead and steers toward it when it is behind.
func BestMoveWithHistory(p Position, level int, seed int, history []uint64) (Move, bool) {
best, _, ok := searchWith(p, Level(level), seed, history)
return best, ok
}
// Hash returns a 64-bit hash of the position (for repetition tracking).
func (p Position) Hash() uint64 {
return newEngine(&p).hash()
}
// search is BestMove plus the number of nodes visited (for tests).
func search(p Position, level int, seed int) (Move, int, bool) {
return searchWith(p, Level(level), seed, nil)
}
func searchWith(p Position, info LevelInfo, seed int, history []uint64) (Move, int, bool) {
e := newEngine(&p)
order := e.legal()
if len(order) == 0 {
return Move{}, 0, false
}
if len(order) == 1 {
return decode(order[0]), 0, true
}
e.budget = info.Budget
e.qdepth = info.QDepth
if seed < 0 {
seed = -seed
}
var chosen []int
for depth := 1; depth <= info.MaxDepth; depth++ {
bestScore := -infScore
var ties []int
for _, m := range order {
// Window (bestScore-1, inf): equal-best moves get exact scores,
// worse moves fail low at <= bestScore-1.
alpha := -infScore
if bestScore > -infScore {
alpha = bestScore - 1
}
u := e.make(m)
score := 0 // a repeated position counts as a draw
if len(history) == 0 || !containsU64(history, e.hash()) {
score = -e.negamax(depth-1, -infScore, -alpha, 1, e.givesCheck(m, u))
}
e.unmake(m, u)
if e.aborted {
break
}
if score > bestScore {
bestScore = score
ties = []int{m}
} else if score == bestScore {
ties = append(ties, m)
}
}
if e.aborted {
// Moves are searched best-first, so any move that finished at
// this depth is at least as reliable as the previous result.
if len(ties) > 0 {
chosen = ties
}
break
}
chosen = ties
if bestScore >= mateScore-maxPly || depth == info.MaxDepth {
break // forced mate found, or done
}
// Search the current best moves first in the next iteration.
next := make([]int, 0, len(order))
next = append(next, ties...)
for _, m := range order {
if !containsInt(ties, m) {
next = append(next, m)
}
}
order = next
}
if len(chosen) == 0 {
chosen = order[:1] // budget ran out before depth 1 finished
}
return decode(chosen[seed%len(chosen)]), e.nodes, true
}
func containsU64(list []uint64, x uint64) bool {
for _, y := range list {
if y == x {
return true
}
}
return false
}
func containsInt(list []int, x int) bool {
for _, y := range list {
if y == x {
return true
}
}
return false
}
// captureKey ranks a capture: most valuable victim first, then least
// valuable attacker (MVV-LVA). Promotions count as winning a queen.
func (e *engine) captureKey(m int) int {
v := pieceValue[e.b[(m>>6)&63].Type()]*16 - int(e.b[m&63].Type())
if m >= 4096 {
v += pieceValue[Queen] * 16
}
return v
}
// orderCaptures sorts captures by captureKey, best first.
func (e *engine) orderCaptures(caps []int, n int) {
for i := 1; i < n; i++ {
m := caps[i]
v := e.captureKey(m)
j := i - 1
for j >= 0 && e.captureKey(caps[j]) < v {
caps[j+1] = caps[j]
j--
}
caps[j+1] = m
}
}
// killersFirst moves this ply's killer moves to the front of the quiets.
func (e *engine) killersFirst(pb *plyBuf, ply int) {
if ply > maxPly {
return
}
front := 0
for k := 0; k < 2; k++ {
km := e.killers[ply][k]
if km == 0 {
continue
}
for j := front; j < pb.nq; j++ {
if pb.quiets[j] == km {
pb.quiets[j], pb.quiets[front] = pb.quiets[front], km
front++
break
}
}
}
}
func (e *engine) addKiller(ply, m int) {
if e.killers[ply][0] != m {
e.killers[ply][1] = e.killers[ply][0]
e.killers[ply][0] = m
}
}
// negamax assumes the position is legal; inCheck says whether the side to
// move is in check (computed cheaply by the parent via givesCheck).
func (e *engine) negamax(depth, alpha, beta, ply int, inCheck bool) int {
e.nodes++
if e.nodes > e.budget {
e.aborted = true
return 0
}
if e.half >= 100 {
return 0
}
if depth <= 0 {
if !inCheck || ply >= maxPly {
return e.quiesce(alpha, beta, ply, 0, inCheck)
}
depth = 1 // check extension: never stop the search in check
}
pb := e.buf(ply)
e.gen(pb, false)
if pb.nc > 1 {
e.orderCaptures(pb.caps, pb.nc)
}
e.killersFirst(pb, ply)
best := -infScore
nc, n := pb.nc, pb.nc+pb.nq
for i := 0; i < n; i++ {
m := 0
if i < nc {
m = pb.caps[i]
} else {
m = pb.quiets[i-nc]
}
u := e.make(m)
if !e.moveIsLegal(m, u, inCheck) {
e.unmake(m, u)
continue
}
score := -e.negamax(depth-1, -beta, -alpha, ply+1, e.givesCheck(m, u))
e.unmake(m, u)
if e.aborted {
return 0
}
if score > best {
best = score
if score > alpha {
alpha = score
if alpha >= beta {
if i >= nc && ply <= maxPly {
e.addKiller(ply, m)
}
return best
}
}
}
}
if best == -infScore { // no legal moves
if inCheck {
return -mateScore + ply
}
return 0 // stalemate
}
return best
}
func (e *engine) quiesce(alpha, beta, ply, qdepth int, inCheck bool) int {
e.nodes++
if e.nodes > e.budget {
e.aborted = true
return 0
}
if inCheck && ply < maxPly {
// Standing pat is not an option in check: search all evasions.
return e.negamax(1, alpha, beta, ply, true)
}
stand := e.eval()
if stand >= beta || qdepth >= e.qdepth {
return stand
}
if stand+1000 <= alpha {
return alpha // delta pruning: even winning a queen can't help
}
if stand > alpha {
alpha = stand
}
pb := e.buf(ply)
e.gen(pb, true)
if pb.nc > 1 {
e.orderCaptures(pb.caps, pb.nc)
}
them := 1 - e.turn
for i := 0; i < pb.nc; i++ {
m := pb.caps[i]
// Skip losing captures: a more valuable piece taking a defended,
// less valuable one (e.g. queen takes a guarded pawn).
to := (m >> 6) & 63
if m < 4096 && pieceValue[e.b[m&63].Type()] > pieceValue[e.b[to].Type()] && e.attacked(to, them) {
continue
}
u := e.make(m)
if !e.moveIsLegal(m, u, inCheck) {
e.unmake(m, u)
continue
}
score := -e.quiesce(-beta, -alpha, ply+1, qdepth+1, e.givesCheck(m, u))
e.unmake(m, u)
if e.aborted {
return 0
}
if score >= beta {
return score
}
if score > alpha {
alpha = score
}
}
return alpha
}
engine.gno
package minichess
// engine is the mutable, allocation-light core used by move generation and
// the bot. GnoVM charges gas per operation (roughly 1k gas per loop
// iteration, ~4k per append), so the engine uses precomputed tables, piece
// lists (only occupied squares are visited), integer-encoded moves written
// into reused buffers, in-place make/unmake and an incrementally updated
// evaluation.
// Encoded move: from | to<<6 | promo<<12.
func enc(from, to int, promo Piece) int { return from | to<<6 | int(promo)<<12 }
func decode(m int) Move {
return Move{From: m & 63, To: (m >> 6) & 63, Promo: Piece(m >> 12)}
}
func (m Move) encode() int { return enc(m.From, m.To, m.Promo) }
const bufSize = 256 // more than the maximum number of pseudo-legal moves
// Lookup tables. A deployed package pays a storage deposit for everything
// it persists, so target-square lists are stored as strings (one byte per
// square): compact on-chain, and ranging over them costs about the same
// gas as ranging over a slice.
var (
knightT [NumSquares]string
kingT [NumSquares]string
rays [NumSquares * 8]string // [sq*8+dir]; dirs 0-3 orthogonal, 4-7 diagonal
pawnAtk [2 * NumSquares]string // [c*64+sq]: squares a pawn of colour c on sq attacks
psqt [13][NumSquares]int // [piece+6][sq], signed (white +)
// geo[a*64+b] flags: geoLine (shared rank/file/diagonal), geoKnight,
// geoKing (adjacent).
geo string
)
const (
geoLine byte = 1
geoKnight byte = 2
geoKing byte = 4
)
var pieceValue = [7]int{0, 100, 320, 330, 500, 900, 0}
func inside(r, f int) bool { return r >= 0 && r < Size && f >= 0 && f < Size }
// init fills the lookup tables. Pure packages are immutable after init, so
// the tables are built once here and only read afterwards.
func init() {
dirs8 := [8][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}
knightD := [8][2]int{{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}
// Piece-square tables ("simplified evaluation function"), written
// from white's point of view with rank 8 first.
pst := [7][64]int{
{},
{ // pawn
0, 0, 0, 0, 0, 0, 0, 0,
50, 50, 50, 50, 50, 50, 50, 50,
10, 10, 20, 30, 30, 20, 10, 10,
5, 5, 10, 25, 25, 10, 5, 5,
0, 0, 0, 20, 20, 0, 0, 0,
5, -5, -10, 0, 0, -10, -5, 5,
5, 10, 10, -20, -20, 10, 10, 5,
0, 0, 0, 0, 0, 0, 0, 0,
},
{ // knight
-50, -40, -30, -30, -30, -30, -40, -50,
-40, -20, 0, 0, 0, 0, -20, -40,
-30, 0, 10, 15, 15, 10, 0, -30,
-30, 5, 15, 20, 20, 15, 5, -30,
-30, 0, 15, 20, 20, 15, 0, -30,
-30, 5, 10, 15, 15, 10, 5, -30,
-40, -20, 0, 5, 5, 0, -20, -40,
-50, -40, -30, -30, -30, -30, -40, -50,
},
{ // bishop
-20, -10, -10, -10, -10, -10, -10, -20,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, 0, 5, 10, 10, 5, 0, -10,
-10, 5, 5, 10, 10, 5, 5, -10,
-10, 0, 10, 10, 10, 10, 0, -10,
-10, 10, 10, 10, 10, 10, 10, -10,
-10, 5, 0, 0, 0, 0, 5, -10,
-20, -10, -10, -10, -10, -10, -10, -20,
},
{ // rook
0, 0, 0, 0, 0, 0, 0, 0,
5, 10, 10, 10, 10, 10, 10, 5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
-5, 0, 0, 0, 0, 0, 0, -5,
0, 0, 0, 5, 5, 0, 0, 0,
},
{ // queen
-20, -10, -10, -5, -5, -10, -10, -20,
-10, 0, 0, 0, 0, 0, 0, -10,
-10, 0, 5, 5, 5, 5, 0, -10,
-5, 0, 5, 5, 5, 5, 0, -5,
0, 0, 5, 5, 5, 5, 0, -5,
-10, 5, 5, 5, 5, 5, 0, -10,
-10, 0, 5, 0, 0, 0, 0, -10,
-20, -10, -10, -5, -5, -10, -10, -20,
},
{ // king (middlegame)
-30, -40, -40, -50, -50, -40, -40, -30,
-30, -40, -40, -50, -50, -40, -40, -30,
-30, -40, -40, -50, -50, -40, -40, -30,
-30, -40, -40, -50, -50, -40, -40, -30,
-20, -30, -30, -40, -40, -30, -30, -20,
-10, -20, -20, -20, -20, -20, -20, -10,
20, 20, 0, 0, 0, 0, 20, 20,
20, 30, 10, 0, 0, 10, 30, 20,
},
}
sqs := func(list []int) string {
b := make([]byte, len(list))
for i, v := range list {
b[i] = byte(v)
}
return string(b)
}
for sq := 0; sq < NumSquares; sq++ {
r, f := sq/Size, sq%Size
var kn, kg []int
for _, d := range knightD {
if inside(r+d[0], f+d[1]) {
kn = append(kn, (r+d[0])*Size+f+d[1])
}
}
for i, d := range dirs8 {
if inside(r+d[0], f+d[1]) {
kg = append(kg, (r+d[0])*Size+f+d[1])
}
var ray []int
nr, nf := r+d[0], f+d[1]
for inside(nr, nf) {
ray = append(ray, nr*Size+nf)
nr += d[0]
nf += d[1]
}
rays[sq*8+i] = sqs(ray)
}
knightT[sq] = sqs(kn)
kingT[sq] = sqs(kg)
for c := 0; c < 2; c++ {
nr := r + 1
if c == 1 {
nr = r - 1
}
var pa []int
for _, df := range [2]int{-1, 1} {
if inside(nr, f+df) {
pa = append(pa, nr*Size+f+df)
}
}
pawnAtk[c*NumSquares+sq] = sqs(pa)
}
for t := 1; t <= 6; t++ {
v := pieceValue[t] + pst[t][(Size-1-r)*Size+f]
psqt[6+t][sq] = v
psqt[6-t][(Size-1-r)*Size+f] = -v
}
}
g8 := make([]byte, NumSquares*NumSquares)
for a := 0; a < NumSquares; a++ {
for b := 0; b < NumSquares; b++ {
if a == b {
continue
}
dr, df := a/Size-b/Size, a%Size-b%Size
var g byte
if dr == 0 || df == 0 || dr == df || dr == -df {
g |= geoLine
}
if dr*df == 2 || dr*df == -2 {
g |= geoKnight
}
if dr >= -1 && dr <= 1 && df >= -1 && df <= 1 {
g |= geoKing
}
g8[a*NumSquares+b] = g
}
}
geo = string(g8)
}
// castleKeep returns the castling rights that survive a move touching sq.
func castleKeep(sq int) int {
switch sq {
case 0:
return ^CastleWQ
case 4:
return ^(CastleWK | CastleWQ)
case 7:
return ^CastleWK
case 56:
return ^CastleBQ
case 60:
return ^(CastleBK | CastleBQ)
case 63:
return ^CastleBK
}
return ^0
}
type undo struct {
moved Piece
captured Piece
capSq int
capIdx int
castle int
ep int
half int
score int
special int // 0 normal, 1 en passant, 2 castling
}
// plyBuf holds the moves generated at one search ply.
type plyBuf struct {
caps []int
quiets []int
nc, nq int
}
func newPlyBuf() *plyBuf {
return &plyBuf{caps: make([]int, bufSize), quiets: make([]int, bufSize)}
}
type engine struct {
b [NumSquares]Piece
turn Color
castle int
ep int
half int
kings [2]int
score int // white-perspective evaluation, updated incrementally
// Piece lists: squares of each side's pieces, and each occupied
// square's index in its list.
plist [2][16]int
pcount [2]int
pidx [NumSquares]int
nodes int
budget int
qdepth int
aborted bool
bufs []*plyBuf
killers [maxPly + 2][2]int // quiet moves that caused a cutoff, per ply
}
func newEngine(p *Position) *engine {
e := &engine{b: p.Board, turn: p.Turn, castle: p.Castling, ep: p.EP, half: p.Halfmove}
for sq := 0; sq < NumSquares; sq++ {
pc := e.b[sq]
if pc == Empty {
continue
}
e.score += psqt[pc+6][sq]
c := 0
if pc < 0 {
c = 1
}
if pc.Type() == King {
e.kings[c] = sq
}
if e.pcount[c] < 16 {
e.pidx[sq] = e.pcount[c]
e.plist[c][e.pcount[c]] = sq
e.pcount[c]++
}
}
return e
}
func (e *engine) buf(ply int) *plyBuf {
for len(e.bufs) <= ply {
e.bufs = append(e.bufs, newPlyBuf())
}
return e.bufs[ply]
}
// attacked reports whether sq is attacked by colour by.
func (e *engine) attacked(sq int, by Color) bool {
sign := Piece(1)
if by == Black {
sign = -1
}
b := &e.b
// A pawn of colour `by` attacks sq if it sits on a square that a pawn
// of the other colour on sq would attack.
pw := sign * Pawn
for _, ch := range pawnAtk[int(1-by)*NumSquares+sq] {
if b[int(ch)] == pw {
return true
}
}
kn := sign * Knight
for _, ch := range knightT[sq] {
if b[int(ch)] == kn {
return true
}
}
kg := sign * King
for _, ch := range kingT[sq] {
if b[int(ch)] == kg {
return true
}
}
q := sign * Queen
slider := sign * Rook
for d := 0; d < 8; d++ {
if d == 4 {
slider = sign * Bishop
}
for _, ch := range rays[sq*8+d] {
pc := b[int(ch)]
if pc != Empty {
if pc == slider || pc == q {
return true
}
break
}
}
}
return false
}
func (e *engine) inCheck() bool {
return e.attacked(e.kings[e.turn], 1-e.turn)
}
// gen fills pb with pseudo-legal moves: captures and queen promotions in
// pb.caps, everything else in pb.quiets (skipped when capsOnly).
func (e *engine) gen(pb *plyBuf, capsOnly bool) {
caps, quiets := pb.caps, pb.quiets
nc, nq := 0, 0
b := &e.b
us := e.turn
sign := Piece(1)
fwd, startRank, promoRank := Size, 1, Size-1
if us == Black {
sign, fwd, startRank, promoRank = -1, -Size, Size-2, 0
}
list := &e.plist[us]
for i := 0; i < e.pcount[us]; i++ {
sq := list[i]
pc := b[sq] * sign
switch pc {
case Pawn:
to := sq + fwd
promo := to/Size == promoRank
if b[to] == Empty {
if promo {
caps[nc] = enc(sq, to, Queen)
nc++
if !capsOnly {
quiets[nq] = enc(sq, to, Knight)
quiets[nq+1] = enc(sq, to, Rook)
quiets[nq+2] = enc(sq, to, Bishop)
nq += 3
}
} else if !capsOnly {
quiets[nq] = sq | to<<6
nq++
if sq/Size == startRank && b[to+fwd] == Empty {
quiets[nq] = sq | (to+fwd)<<6
nq++
}
}
}
for _, ch := range pawnAtk[int(us)*NumSquares+sq] {
t := int(ch)
if b[t]*sign < 0 {
if promo {
caps[nc] = enc(sq, t, Queen)
nc++
if !capsOnly {
quiets[nq] = enc(sq, t, Knight)
quiets[nq+1] = enc(sq, t, Rook)
quiets[nq+2] = enc(sq, t, Bishop)
nq += 3
}
} else {
caps[nc] = sq | t<<6
nc++
}
} else if t == e.ep {
caps[nc] = sq | t<<6
nc++
}
}
case Knight, King:
targets := knightT[sq]
if pc == King {
targets = kingT[sq]
}
for _, ch := range targets {
t := int(ch)
v := b[t]
if v == Empty {
if !capsOnly {
quiets[nq] = sq | t<<6
nq++
}
} else if v*sign < 0 {
caps[nc] = sq | t<<6
nc++
}
}
default: // sliders
lo, hi := 0, 8
if pc == Rook {
hi = 4
} else if pc == Bishop {
lo = 4
}
for d := lo; d < hi; d++ {
for _, ch := range rays[sq*8+d] {
t := int(ch)
v := b[t]
if v == Empty {
if !capsOnly {
quiets[nq] = sq | t<<6
nq++
}
continue
}
if v*sign < 0 {
caps[nc] = sq | t<<6
nc++
}
break
}
}
}
}
if !capsOnly && e.castle != 0 {
nq = e.genCastles(quiets, nq)
}
pb.nc, pb.nq = nc, nq
}
// genCastles adds castling moves. The king may not castle out of, through
// or into check, and the squares between king and rook must be empty.
func (e *engine) genCastles(quiets []int, nq int) int {
b := &e.b
them := 1 - e.turn
base, rook, kRight, qRight := 0, Rook, CastleWK, CastleWQ
if e.turn == Black {
base, rook, kRight, qRight = 56, -Rook, CastleBK, CastleBQ
}
k := base + 4
if e.castle&kRight != 0 && b[base+5] == Empty && b[base+6] == Empty && b[base+7] == rook &&
!e.attacked(k, them) && !e.attacked(k+1, them) && !e.attacked(k+2, them) {
quiets[nq] = k | (k+2)<<6
nq++
}
if e.castle&qRight != 0 && b[base+3] == Empty && b[base+2] == Empty && b[base+1] == Empty &&
b[base] == rook && !e.attacked(k, them) && !e.attacked(k-1, them) && !e.attacked(k-2, them) {
quiets[nq] = k | (k-2)<<6
nq++
}
return nq
}
// movePiece updates the board and piece list for a piece moving from->to.
func (e *engine) movePiece(c Color, from, to int) {
i := e.pidx[from]
e.plist[c][i] = to
e.pidx[to] = i
e.b[to] = e.b[from]
e.b[from] = Empty
}
// removePiece takes the piece on sq out of colour c's list; returns its
// former index so restorePiece can undo it exactly.
func (e *engine) removePiece(c Color, sq int) int {
i := e.pidx[sq]
n := e.pcount[c] - 1
last := e.plist[c][n]
e.plist[c][i] = last
e.pidx[last] = i
e.pcount[c] = n
return i
}
func (e *engine) restorePiece(c Color, sq, i int) {
n := e.pcount[c]
moved := e.plist[c][i]
e.plist[c][n] = moved
e.pidx[moved] = n
e.plist[c][i] = sq
e.pidx[sq] = i
e.pcount[c] = n + 1
}
func (e *engine) make(m int) undo {
from, to := m&63, (m>>6)&63
us, them := e.turn, 1-e.turn
pc := e.b[from]
pt := pc.Type()
u := undo{moved: pc, capSq: to, castle: e.castle, ep: e.ep, half: e.half, score: e.score}
capt := e.b[to]
if pt == Pawn && to == e.ep && capt == Empty && (from&7) != (to&7) {
// En passant: the captured pawn is behind the target square.
u.special = 1
if us == White {
u.capSq = to - Size
} else {
u.capSq = to + Size
}
capt = e.b[u.capSq]
}
u.captured = capt
if capt != Empty {
u.capIdx = e.removePiece(them, u.capSq)
e.score -= psqt[capt+6][u.capSq]
e.b[u.capSq] = Empty
}
e.movePiece(us, from, to)
np := pc
if m >= 4096 {
np = Piece(m >> 12)
if pc < 0 {
np = -np
}
e.b[to] = np
}
e.score += psqt[np+6][to] - psqt[pc+6][from]
if pt == King {
e.kings[us] = to
if to-from == 2 || from-to == 2 {
u.special = 2
rf, rt := from+3, from+1
if to < from {
rf, rt = from-4, from-1
}
rk := e.b[rf]
e.movePiece(us, rf, rt)
e.score += psqt[rk+6][rt] - psqt[rk+6][rf]
}
}
if e.castle != 0 {
e.castle &= castleKeep(from) & castleKeep(to)
}
e.ep = -1
if pt == Pawn && (to-from == 16 || from-to == 16) {
e.ep = (from + to) / 2
}
if pt == Pawn || capt != Empty {
e.half = 0
} else {
e.half++
}
e.turn = them
return u
}
func (e *engine) unmake(m int, u undo) {
from, to := m&63, (m>>6)&63
them := e.turn
us := 1 - them
e.turn = us
if u.special == 2 {
rf, rt := from+3, from+1
if to < from {
rf, rt = from-4, from-1
}
e.movePiece(us, rt, rf)
}
e.movePiece(us, to, from)
e.b[from] = u.moved
if u.moved == King || u.moved == -King {
e.kings[us] = from
}
if u.captured != Empty {
e.b[u.capSq] = u.captured
e.restorePiece(them, u.capSq, u.capIdx)
}
e.castle, e.ep, e.half, e.score = u.castle, u.ep, u.half, u.score
}
// moveIsLegal is called right after make(m) (so e.turn is the opponent).
// wasInCheck says whether the mover was in check before m. A normal
// non-king move from a square not lined up with its own king cannot
// expose that king, so the attack test is skipped.
func (e *engine) moveIsLegal(m int, u undo, wasInCheck bool) bool {
k := e.kings[1-e.turn]
if !wasInCheck && u.special == 0 && u.moved != King && u.moved != -King &&
geo[k*NumSquares+m&63]&geoLine == 0 {
return true
}
return !e.attacked(k, e.turn)
}
// givesCheck is called right after make(m): does the side to move now
// stand in check? Cheap geometric filters avoid most attack tests.
func (e *engine) givesCheck(m int, u undo) bool {
ek := e.kings[e.turn]
from, to := m&63, (m>>6)&63
g := ek * NumSquares
maybe := u.special != 0 || geo[g+from]&geoLine != 0 // castling, e.p., discovery
if !maybe {
switch e.b[to].Type() {
case Knight:
maybe = geo[g+to]&geoKnight != 0
case Pawn:
maybe = geo[g+to]&geoKing != 0
case King:
default:
maybe = geo[g+to]&geoLine != 0
}
}
return maybe && e.attacked(ek, 1-e.turn)
}
// legal returns the legal moves (captures first) as encoded ints.
func (e *engine) legal() []int {
pb := newPlyBuf()
e.gen(pb, false)
out := make([]int, 0, pb.nc+pb.nq)
for i := 0; i < pb.nc+pb.nq; i++ {
m := 0
if i < pb.nc {
m = pb.caps[i]
} else {
m = pb.quiets[i-pb.nc]
}
u := e.make(m)
if !e.attacked(e.kings[1-e.turn], e.turn) {
out = append(out, m)
}
e.unmake(m, u)
}
return out
}
// mix is a splitmix64-style mixer used to build position hashes.
func mix(x uint64) uint64 {
x += 0x9e3779b97f4a7c15
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9
x = (x ^ (x >> 27)) * 0x94d049bb133111eb
return x ^ (x >> 31)
}
// hash is a Zobrist-style hash of the position (pieces, side to move,
// castling rights, en passant square), used to detect repetitions.
func (e *engine) hash() uint64 {
var h uint64
for c := 0; c < 2; c++ {
for i := 0; i < e.pcount[c]; i++ {
sq := e.plist[c][i]
h ^= mix(uint64(int(e.b[sq]+6)*NumSquares + sq))
}
}
return h ^ mix(uint64(1000+int(e.turn)+2*e.castle+32*(e.ep+1)))
}
// position converts the engine state back to a Position.
func (e *engine) position(fullmove int) Position {
return Position{Board: e.b, Turn: e.turn, Castling: e.castle, EP: e.ep, Halfmove: e.half, Fullmove: fullmove}
}
fastpath_test.gno
package minichess
import "testing"
// fastPerft walks the tree the way the search does (in-place make/unmake
// with the cheap legality and check filters) and cross-checks the filters
// against full attack tests at every node.
func fastPerft(t *testing.T, e *engine, depth, ply int, inCheck bool) int {
if depth == 0 {
return 1
}
pb := e.buf(ply)
e.gen(pb, false)
n := 0
for i := 0; i < pb.nc+pb.nq; i++ {
m := 0
if i < pb.nc {
m = pb.caps[i]
} else {
m = pb.quiets[i-pb.nc]
}
u := e.make(m)
fast := e.moveIsLegal(m, u, inCheck)
full := !e.attacked(e.kings[1-e.turn], e.turn)
if fast != full {
t.Fatalf("moveIsLegal mismatch for %s", decode(m))
}
if full {
gc := e.givesCheck(m, u)
if gc != e.inCheck() {
t.Fatalf("givesCheck mismatch for %s", decode(m))
}
n += fastPerft(t, e, depth-1, ply+1, gc)
}
e.unmake(m, u)
}
return n
}
func TestFastPathPerft(t *testing.T) {
cases := []struct {
fen string
depth int
want int
}{
{"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", 2, 2039},
{"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", 3, 2812},
{"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1", 3, 9467},
{"rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", 2, 1486},
}
for _, c := range cases {
p := mustFEN(t, c.fen)
e := newEngine(&p)
before := p.FEN()
if got := fastPerft(t, e, c.depth, 0, e.inCheck()); got != c.want {
t.Fatalf("%s: got %d want %d", c.fen, got, c.want)
}
if after := e.position(p.Fullmove).FEN(); after != before {
t.Fatalf("make/unmake did not restore: %s vs %s", after, before)
}
}
}
gnomod.toml
module = "gno.land/p/g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru/minichess" gno = "0.9" [addpkg] creator = "g1um2pwwnx3gn8p3ryfdert8mhpu4u4up49sc9ru" height = 727716 max_deposit = "15000000ugnot"
minichess_test.gno
package minichess
import "testing"
func perft(p Position, depth int) int {
if depth == 0 {
return 1
}
if depth == 1 {
return len(p.LegalMoves())
}
n := 0
for _, m := range p.LegalMoves() {
n += perft(p.Play(m), depth-1)
}
return n
}
func mustFEN(t *testing.T, fen string) Position {
t.Helper()
p, err := ParseFEN(fen)
if err != nil {
t.Fatalf("ParseFEN(%q): %v", fen, err)
}
return p
}
func mustMove(t *testing.T, s string) Move {
t.Helper()
m, err := ParseMove(s)
if err != nil {
t.Fatalf("ParseMove(%q): %v", s, err)
}
return m
}
func isLegal(t *testing.T, p Position, s string) bool {
t.Helper()
_, ok := p.FindLegal(mustMove(t, s))
return ok
}
func TestStartPosition(t *testing.T) {
p := NewGame()
if got := p.FEN(); got != StartFEN {
t.Fatalf("FEN round trip: got %q", got)
}
if p.PieceAt("e1") != King || p.PieceAt("d8") != -Queen {
t.Fatalf("pieces misplaced")
}
}
// Perft values cross-checked against python-chess. These positions cover
// castling, en passant, promotions, pins and discovered checks.
func TestPerft(t *testing.T) {
cases := []struct {
fen string
want []int
}{
{StartFEN, []int{20, 400, 8902}},
{"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", []int{48, 2039}},
{"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", []int{14, 191, 2812}},
{"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1", []int{6, 264, 9467}},
{"rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", []int{44, 1486}},
}
for _, c := range cases {
p := mustFEN(t, c.fen)
for d, w := range c.want {
if got := perft(p, d+1); got != w {
t.Fatalf("%s: perft(%d) = %d, want %d", c.fen, d+1, got, w)
}
}
}
}
func TestParseMove(t *testing.T) {
m := mustMove(t, "E7E8N")
if m.Promo != Knight || m.String() != "e7e8n" {
t.Fatalf("got %v", m)
}
for _, bad := range []string{"", "e2", "i1i2", "a1a9", "e7e8k", "e2e4qq"} {
if _, err := ParseMove(bad); err == nil {
t.Fatalf("ParseMove(%q) should fail", bad)
}
}
}
func TestStartMoves(t *testing.T) {
p := NewGame()
for _, s := range []string{"e2e4", "e2e3", "g1f3", "b1a3"} {
if !isLegal(t, p, s) {
t.Fatalf("%s should be legal", s)
}
}
for _, s := range []string{"e2e5", "e1e2", "e1g1", "d1d3", "e7e5"} {
if isLegal(t, p, s) {
t.Fatalf("%s should be illegal", s)
}
}
n := p.Play(mustMove(t, "e2e4"))
if n.FEN() != "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" {
t.Fatalf("after e2e4: %s", n.FEN())
}
}
func TestCastling(t *testing.T) {
p := mustFEN(t, "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")
n := p.Play(mustMove(t, "e1g1"))
if n.PieceAt("g1") != King || n.PieceAt("f1") != Rook || n.PieceAt("h1") != Empty {
t.Fatalf("king-side castle wrong: %s", n.FEN())
}
if n.Castling != CastleBK|CastleBQ {
t.Fatalf("white rights should be gone: %s", n.FEN())
}
n = p.Play(mustMove(t, "e1c1"))
if n.PieceAt("c1") != King || n.PieceAt("d1") != Rook || n.PieceAt("a1") != Empty {
t.Fatalf("queen-side castle wrong: %s", n.FEN())
}
// f1 attacked by the rook on f8: cannot castle through it.
p = mustFEN(t, "r3kr2/8/8/8/8/8/8/R3K2R w KQq - 0 1")
if isLegal(t, p, "e1g1") || !isLegal(t, p, "e1c1") {
t.Fatalf("castling through check")
}
// In check: no castling at all.
p = mustFEN(t, "4r1k1/8/8/8/8/8/8/R3K2R w KQ - 0 1")
if isLegal(t, p, "e1g1") || isLegal(t, p, "e1c1") {
t.Fatalf("castling out of check")
}
// Moving a rook loses that side's right.
p = mustFEN(t, "r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")
n = p.Play(mustMove(t, "h1h2"))
if n.Castling != CastleWQ|CastleBK|CastleBQ {
t.Fatalf("rook move rights: %s", n.FEN())
}
}
func TestEnPassant(t *testing.T) {
p := mustFEN(t, "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1")
if !isLegal(t, p, "e5d6") {
t.Fatalf("e5d6 en passant should be legal")
}
n := p.Play(mustMove(t, "e5d6"))
if n.PieceAt("d5") != Empty || n.PieceAt("d6") != Pawn {
t.Fatalf("en passant wrong: %s", n.FEN())
}
// Without the e.p. square the capture is not available.
p = mustFEN(t, "4k3/8/8/3pP3/8/8/8/4K3 w - - 0 1")
if isLegal(t, p, "e5d6") {
t.Fatalf("e5d6 should be illegal without e.p. right")
}
}
func TestPromotion(t *testing.T) {
p := mustFEN(t, "8/P6k/8/8/8/8/8/4K3 w - - 0 1")
lm, ok := p.FindLegal(mustMove(t, "a7a8"))
if !ok || lm.Promo != Queen || p.Play(lm).PieceAt("a8") != Queen {
t.Fatalf("a7a8 should promote to a queen")
}
lm, ok = p.FindLegal(mustMove(t, "a7a8n"))
if !ok || p.Play(lm).PieceAt("a8") != Knight {
t.Fatalf("under-promotion to knight failed")
}
}
func TestGameEnd(t *testing.T) {
// Fool's mate.
if s := mustFEN(t, "rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3").Status(); s != Checkmate {
t.Fatalf("expected checkmate, got %s", s)
}
if s := mustFEN(t, "7k/5Q2/6K1/8/8/8/8/8 b - - 0 1").Status(); s != Stalemate {
t.Fatalf("expected stalemate, got %s", s)
}
if s := mustFEN(t, "7k/8/8/8/8/8/8/2B1K3 w - - 0 1").Status(); s != InsufficientMaterial {
t.Fatalf("K+B vs K should be a draw, got %s", s)
}
if s := mustFEN(t, "7k/8/8/8/8/8/8/R3K3 w - - 0 1").Status(); s != Ongoing {
t.Fatalf("K+R vs K is not a draw, got %s", s)
}
if s := mustFEN(t, "7k/8/8/8/8/8/8/R3K3 w - - 100 80").Status(); s != FiftyMoveDraw {
t.Fatalf("expected 50-move draw, got %s", s)
}
if NewGame().Status() != Ongoing {
t.Fatalf("start should be ongoing")
}
}
func TestBotFindsMateInOne(t *testing.T) {
p := mustFEN(t, "6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1") // Ra8#
for level := MinLevel; level <= MaxLevel; level++ {
m, ok := BestMove(p, level, 0)
if !ok || p.Play(m).Status() != Checkmate {
t.Fatalf("level %d played %s, not mate", level, m)
}
}
}
func TestBotTakesHangingQueen(t *testing.T) {
p := mustFEN(t, "4k3/8/8/3q4/4P3/8/8/4K3 w - - 0 1")
for level := MinLevel; level <= MaxLevel; level++ {
m, _ := BestMove(p, level, 0)
if m.String() != "e4d5" {
t.Fatalf("level %d played %s, want e4d5", level, m)
}
}
}
// The node budget is what bounds a bot reply's gas cost on-chain.
func TestBotRespectsNodeBudget(t *testing.T) {
positions := []string{StartFEN, "r1bqkb1r/pppp1ppp/2n2n2/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R w KQkq - 4 4"}
for _, fen := range positions {
p := mustFEN(t, fen)
for level := MinLevel; level <= MaxLevel; level++ {
m, nodes, ok := search(p, level, 0)
if !ok {
t.Fatalf("no move for %s", fen)
}
if _, legal := p.FindLegal(m); !legal {
t.Fatalf("level %d played illegal %s", level, m)
}
if nodes > Level(level).Budget+1 {
t.Fatalf("level %d used %d nodes, budget %d", level, nodes, Level(level).Budget)
}
}
}
}
func TestBotIsDeterministic(t *testing.T) {
p := NewGame()
a, _ := BestMove(p, 2, 42)
b, _ := BestMove(p, 2, 42)
if a != b {
t.Fatalf("same inputs gave %s and %s", a, b)
}
}
func TestBotPlaysLegalGame(t *testing.T) {
p := NewGame()
for ply := 0; ply < 40 && p.Status() == Ongoing; ply++ {
m, ok := BestMove(p, 1, ply)
if !ok {
t.Fatalf("no move in ongoing position %s", p.FEN())
}
if _, legal := p.FindLegal(m); !legal {
t.Fatalf("bot played illegal %s in %s", m, p.FEN())
}
p = p.Play(m)
}
}
movegen.gno
package minichess
func lastRank(c Color) int {
if c == White {
return Size - 1
}
return 0
}
// Attacked reports whether square sq is attacked by any piece of colour by.
func (p Position) Attacked(sq int, by Color) bool {
return newEngine(&p).attacked(sq, by)
}
// InCheck reports whether the side to move is in check.
func (p Position) InCheck() bool {
return newEngine(&p).inCheck()
}
// LegalMoves returns all legal moves for the side to move.
func (p Position) LegalMoves() []Move {
enc := newEngine(&p).legal()
out := make([]Move, len(enc))
for i, m := range enc {
out[i] = decode(m)
}
return out
}
// Play applies a move without validating it and returns the new position.
// Callers must only pass moves obtained from LegalMoves or FindLegal.
func (p Position) Play(m Move) Position {
e := newEngine(&p)
e.make(m.encode())
full := p.Fullmove
if p.Turn == Black {
full++
}
return e.position(full)
}
// IsIrreversible reports whether m is a capture or pawn move (resets the
// repetition history and the 50-move counter).
func (p Position) IsIrreversible(m Move) bool {
return p.Board[m.From].Type() == Pawn || p.Board[m.To] != Empty
}
// FindLegal matches m against the legal moves. A promotion move given
// without a piece defaults to a queen. Returns false if m is illegal.
func (p Position) FindLegal(m Move) (Move, bool) {
if m.Promo == Empty {
pc := p.Board[m.From]
if pc.Type() == Pawn && pc.Color() == p.Turn && m.To/Size == lastRank(p.Turn) {
m.Promo = Queen
}
}
want := m.encode()
for _, lm := range newEngine(&p).legal() {
if lm == want {
return m, true
}
}
return m, false
}
// Status describes whether the game is still going and how it ended.
type Status int
const (
Ongoing Status = iota
Checkmate
Stalemate
FiftyMoveDraw
InsufficientMaterial
)
func (s Status) String() string {
switch s {
case Ongoing:
return "ongoing"
case Checkmate:
return "checkmate"
case Stalemate:
return "stalemate"
case FiftyMoveDraw:
return "50-move rule"
case InsufficientMaterial:
return "insufficient material"
}
return "unknown"
}
// Status computes the game status from the position alone. Threefold
// repetition needs move history and is handled by the caller.
func (p Position) Status() Status {
e := newEngine(&p)
if len(e.legal()) == 0 {
if e.inCheck() {
return Checkmate
}
return Stalemate
}
if p.insufficientMaterial() {
return InsufficientMaterial
}
if p.Halfmove >= 100 {
return FiftyMoveDraw
}
return Ongoing
}
// insufficientMaterial: only kings, or kings plus a single minor piece.
func (p Position) insufficientMaterial() bool {
minors := 0
for _, pc := range p.Board {
switch pc.Type() {
case Pawn, Rook, Queen:
return false
case Knight, Bishop:
minors++
}
}
return minors <= 1
}