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/p/g1g7dna0gp4nec5rza4q25htj0cjgswrxefp37ep/chess"
gno = "0.9"

[addpkg]
  creator = "g1g7dna0gp4nec5rza4q25htj0cjgswrxefp37ep"
  height = 53996
  max_deposit = "100000000ugnot"

rules.gno

package chess

import (
	"errors"
)

// IsPathClear checks if all squares between from and to (exclusive) are empty
func IsPathClear(board Board, fromRow, fromCol, toRow, toCol int) bool {
	dRow := toRow - fromRow
	dCol := toCol - fromCol

	stepRow := 0
	if dRow > 0 {
		stepRow = 1
	} else if dRow < 0 {
		stepRow = -1
	}

	stepCol := 0
	if dCol > 0 {
		stepCol = 1
	} else if dCol < 0 {
		stepCol = -1
	}

	currRow := fromRow + stepRow
	currCol := fromCol + stepCol

	for currRow != toRow || currCol != toCol {
		if board[currRow][currCol] != "." {
			return false
		}
		currRow += stepRow
		currCol += stepCol
	}
	return true
}

// IsOpponentOrEmpty checks if destination square is empty or has an opponent piece
func IsOpponentOrEmpty(board Board, toRow, toCol int, isWhite bool) bool {
	dest := board[toRow][toCol]
	if dest == "." {
		return true
	}
	destIsWhite := IsWhitePiece(dest)
	return isWhite != destIsWhite
}

// IsKingInCheck checks if the king of the specified color is under attack
func IsKingInCheck(board Board, isWhite bool) bool {
	kingRow := -1
	kingCol := -1
	kingChar := "k"
	if isWhite {
		kingChar = "K"
	}

	for r := 0; r < 8; r++ {
		for c := 0; c < 8; c++ {
			if board[r][c] == kingChar {
				kingRow = r
				kingCol = c
				break
			}
		}
		if kingRow != -1 {
			break
		}
	}

	if kingRow == -1 {
		return false
	}

	for r := 0; r < 8; r++ {
		for c := 0; c < 8; c++ {
			piece := board[r][c]
			if piece == "." {
				continue
			}
			pieceIsWhite := IsWhitePiece(piece)
			if pieceIsWhite == isWhite {
				continue
			}

			canAttack := false
			switch piece {
			case "P", "p":
				dRow := kingRow - r
				dCol := kingCol - c
				if pieceIsWhite {
					canAttack = (dRow == -1 && (dCol == 1 || dCol == -1))
				} else {
					canAttack = (dRow == 1 && (dCol == 1 || dCol == -1))
				}
			case "N", "n":
				canAttack = IsValidKnightMove(r, c, kingRow, kingCol)
			case "B", "b":
				canAttack = IsValidBishopMove(board, r, c, kingRow, kingCol)
			case "R", "r":
				canAttack = IsValidRookMove(board, r, c, kingRow, kingCol)
			case "Q", "q":
				canAttack = IsValidQueenMove(board, r, c, kingRow, kingCol)
			case "K", "k":
				dRow := Abs(kingRow - r)
				dCol := Abs(kingCol - c)
				canAttack = (dRow <= 1 && dCol <= 1)
			}

			if canAttack {
				return true
			}
		}
	}
	return false
}

// HasAnyLegalMoves checks if the current player has at least one legal move
func HasAnyLegalMoves(board Board, isWhite bool, rights CastlingRights, enPassantCol int) bool {
	for r := 0; r < 8; r++ {
		for c := 0; c < 8; c++ {
			piece := board[r][c]
			if piece == "." {
				continue
			}
			pieceIsWhite := IsWhitePiece(piece)
			if pieceIsWhite != isWhite {
				continue
			}

			for tr := 0; tr < 8; tr++ {
				for tc := 0; tc < 8; tc++ {
					if IsValidMove(board, r, c, tr, tc, isWhite, rights, enPassantCol) {
						// Simulate move to check if king remains in check
						origDest := board[tr][tc]
						board[tr][tc] = piece
						board[r][c] = "."

						inCheck := IsKingInCheck(board, isWhite)

						board[r][c] = piece
						board[tr][tc] = origDest

						if !inCheck {
							return true
						}
					}
				}
			}
		}
	}
	return false
}

// IsValidPawnMove validates pawn movements including double step and en passant
func IsValidPawnMove(board Board, fromRow, fromCol, toRow, toCol int, isWhite bool, enPassantCol int) bool {
	dRow := toRow - fromRow
	dCol := toCol - fromCol

	if isWhite {
		if dRow == -1 && dCol == 0 {
			return board[toRow][toCol] == "."
		}
		if fromRow == 6 && dRow == -2 && dCol == 0 {
			return board[5][fromCol] == "." && board[4][fromCol] == "."
		}
		if dRow == -1 && (dCol == 1 || dCol == -1) {
			dest := board[toRow][toCol]
			if dest == "." {
				// En Passant capture (must be from row 3 targeting enPassantCol)
				return fromRow == 3 && toCol == enPassantCol
			}
			return !IsWhitePiece(dest)
		}
	} else {
		if dRow == 1 && dCol == 0 {
			return board[toRow][toCol] == "."
		}
		if fromRow == 1 && dRow == 2 && dCol == 0 {
			return board[2][fromCol] == "." && board[3][fromCol] == "."
		}
		if dRow == 1 && (dCol == 1 || dCol == -1) {
			dest := board[toRow][toCol]
			if dest == "." {
				// En Passant capture (must be from row 4 targeting enPassantCol)
				return fromRow == 4 && toCol == enPassantCol
			}
			return IsWhitePiece(dest)
		}
	}
	return false
}

// IsValidKnightMove validates knight L-shaped moves
func IsValidKnightMove(fromRow, fromCol, toRow, toCol int) bool {
	dRow := Abs(toRow - fromRow)
	dCol := Abs(toCol - fromCol)
	return (dRow == 1 && dCol == 2) || (dRow == 2 && dCol == 1)
}

// IsValidBishopMove validates bishop diagonal moves
func IsValidBishopMove(board Board, fromRow, fromCol, toRow, toCol int) bool {
	dRow := Abs(toRow - fromRow)
	dCol := Abs(toCol - fromCol)
	if dRow != dCol {
		return false
	}
	return IsPathClear(board, fromRow, fromCol, toRow, toCol)
}

// IsValidRookMove validates rook straight line moves
func IsValidRookMove(board Board, fromRow, fromCol, toRow, toCol int) bool {
	if fromRow != toRow && fromCol != toCol {
		return false
	}
	return IsPathClear(board, fromRow, fromCol, toRow, toCol)
}

// IsValidQueenMove validates queen diagonal or straight moves
func IsValidQueenMove(board Board, fromRow, fromCol, toRow, toCol int) bool {
	dRow := Abs(toRow - fromRow)
	dCol := Abs(toCol - fromCol)

	isDiagonal := (dRow == dCol)
	isStraight := (fromRow == toRow || fromCol == toCol)

	if !isDiagonal && !isStraight {
		return false
	}
	return IsPathClear(board, fromRow, fromCol, toRow, toCol)
}

// IsValidKingMove validates king standard 1-square moves and castling (O-O and O-O-O)
func IsValidKingMove(board Board, fromRow, fromCol, toRow, toCol int, isWhite bool, rights CastlingRights) bool {
	dRow := Abs(toRow - fromRow)
	dCol := Abs(toCol - fromCol)

	if dRow <= 1 && dCol <= 1 {
		return true
	}

	// Castling
	if dRow == 0 && dCol == 2 {
		if isWhite {
			if rights.WhiteKingMoved {
				return false
			}
			// Kingside Castling (Short O-O)
			if toCol == 6 {
				if rights.WhiteRightRookMoved || board[7][7] != "R" {
					return false
				}
				if board[7][5] != "." || board[7][6] != "." {
					return false
				}
				if IsKingInCheck(board, true) {
					return false
				}
				// Verify intermediate square 7, 5 is not in check
				board[7][4] = "."
				board[7][5] = "K"
				inCheckStep := IsKingInCheck(board, true)
				board[7][5] = "."
				board[7][4] = "K"
				if inCheckStep {
					return false
				}
				return true
			}
			// Queenside Castling (Long O-O-O)
			if toCol == 2 {
				if rights.WhiteLeftRookMoved || board[7][0] != "R" {
					return false
				}
				if board[7][1] != "." || board[7][2] != "." || board[7][3] != "." {
					return false
				}
				if IsKingInCheck(board, true) {
					return false
				}
				// Verify intermediate square 7, 3 is not in check
				board[7][4] = "."
				board[7][3] = "K"
				inCheckStep := IsKingInCheck(board, true)
				board[7][3] = "."
				board[7][4] = "K"
				if inCheckStep {
					return false
				}
				return true
			}
		} else {
			if rights.BlackKingMoved {
				return false
			}
			// Kingside Castling (Short o-o)
			if toCol == 6 {
				if rights.BlackRightRookMoved || board[0][7] != "r" {
					return false
				}
				if board[0][5] != "." || board[0][6] != "." {
					return false
				}
				if IsKingInCheck(board, false) {
					return false
				}
				// Verify intermediate square 0, 5 is not in check
				board[0][4] = "."
				board[0][5] = "k"
				inCheckStep := IsKingInCheck(board, false)
				board[0][5] = "."
				board[0][4] = "k"
				if inCheckStep {
					return false
				}
				return true
			}
			// Queenside Castling (Long o-o-o)
			if toCol == 2 {
				if rights.BlackLeftRookMoved || board[0][0] != "r" {
					return false
				}
				if board[0][1] != "." || board[0][2] != "." || board[0][3] != "." {
					return false
				}
				if IsKingInCheck(board, false) {
					return false
				}
				// Verify intermediate square 0, 3 is not in check
				board[0][4] = "."
				board[0][3] = "k"
				inCheckStep := IsKingInCheck(board, false)
				board[0][3] = "."
				board[0][4] = "k"
				if inCheckStep {
					return false
				}
				return true
			}
		}
	}
	return false
}

// IsValidMove checks if a move from (fromRow, fromCol) to (toRow, toCol) is valid
func IsValidMove(board Board, fromRow, fromCol, toRow, toCol int, isWhiteTurn bool, rights CastlingRights, enPassantCol int) bool {
	piece := board[fromRow][fromCol]
	if piece == "." {
		return false
	}

	isWhite := IsWhitePiece(piece)
	if isWhite != isWhiteTurn {
		return false
	}

	if !IsOpponentOrEmpty(board, toRow, toCol, isWhite) {
		return false
	}

	switch piece {
	case "P", "p":
		return IsValidPawnMove(board, fromRow, fromCol, toRow, toCol, isWhite, enPassantCol)
	case "N", "n":
		return IsValidKnightMove(fromRow, fromCol, toRow, toCol)
	case "B", "b":
		return IsValidBishopMove(board, fromRow, fromCol, toRow, toCol)
	case "R", "r":
		return IsValidRookMove(board, fromRow, fromCol, toRow, toCol)
	case "Q", "q":
		return IsValidQueenMove(board, fromRow, fromCol, toRow, toCol)
	case "K", "k":
		return IsValidKingMove(board, fromRow, fromCol, toRow, toCol, isWhite, rights)
	}

	return false
}

// NormalizePromotionPiece validates and normalizes the promotion piece symbol
func NormalizePromotionPiece(promo string, isWhite bool) (string, error) {
	switch promo {
	case "Q", "q", "":
		if isWhite {
			return "Q", nil
		}
		return "q", nil
	case "R", "r":
		if isWhite {
			return "R", nil
		}
		return "r", nil
	case "B", "b":
		if isWhite {
			return "B", nil
		}
		return "b", nil
	case "N", "n":
		if isWhite {
			return "N", nil
		}
		return "n", nil
	default:
		return "", errors.New("pilihan promosi tidak valid: gunakan Q (Queen), R (Rook), B (Bishop), atau N (Knight)")
	}
}

func splitWords(s string) []string {
	var words []string
	var cur []byte
	for i := 0; i < len(s); i++ {
		c := s[i]
		if c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ',' {
			if len(cur) > 0 {
				words = append(words, string(cur))
				cur = nil
			}
		} else {
			cur = append(cur, c)
		}
	}
	if len(cur) > 0 {
		words = append(words, string(cur))
	}
	return words
}

// ParseUCIMove parses a standard UCI move string (e.g. "e2e4", "e7e8q")
func ParseUCIMove(uci string) (fromRow, fromCol, toRow, toCol int, promoPiece string, err error) {
	if len(uci) < 4 || len(uci) > 5 {
		return 0, 0, 0, 0, "", errors.New("format langkah UCI harus 4 atau 5 karakter (contoh: e2e4 atau e7e8q)")
	}

	fromFile := uci[0]
	fromRank := uci[1]
	toFile := uci[2]
	toRank := uci[3]

	if fromFile < 'a' || fromFile > 'h' || toFile < 'a' || toFile > 'h' ||
		fromRank < '1' || fromRank > '8' || toRank < '1' || toRank > '8' {
		return 0, 0, 0, 0, "", errors.New("koordinat UCI tidak valid: " + uci)
	}

	fromCol = int(fromFile - 'a')
	fromRow = 8 - int(fromRank - '0')
	toCol = int(toFile - 'a')
	toRow = 8 - int(toRank - '0')

	if len(uci) == 5 {
		promoPiece = string(uci[4])
	}

	return fromRow, fromCol, toRow, toCol, promoPiece, nil
}

// ApplyMove applies a move to the board after validating it, updating castling rights and en passant.
func ApplyMove(board Board, fromRow, fromCol, toRow, toCol int, promoPiece string, isWhiteTurn bool, rights *CastlingRights, enPassantCol *int) (Board, error) {
	if fromRow < 0 || fromRow > 7 || fromCol < 0 || fromCol > 7 ||
		toRow < 0 || toRow > 7 || toCol < 0 || toCol > 7 {
		return board, errors.New("koordinat di luar papan")
	}

	piece := board[fromRow][fromCol]
	if piece == "." {
		return board, errors.New("tidak ada bidak di posisi asal")
	}

	isWhite := IsWhitePiece(piece)
	if isWhite != isWhiteTurn {
		return board, errors.New("bukan giliran warna bidak ini")
	}

	if !IsValidMove(board, fromRow, fromCol, toRow, toCol, isWhiteTurn, *rights, *enPassantCol) {
		return board, errors.New("langkah catur tidak valid")
	}

	isPromotion := (piece == "P" && toRow == 0) || (piece == "p" && toRow == 7)
	finalPiece := piece
	if isPromotion {
		promoted, err := NormalizePromotionPiece(promoPiece, isWhite)
		if err != nil {
			return board, err
		}
		finalPiece = promoted
	}

	isCastling := (piece == "K" || piece == "k") && Abs(toCol-fromCol) == 2
	isEnPassant := (piece == "P" || piece == "p") && toCol == *enPassantCol && fromCol != toCol && board[toRow][toCol] == "."

	// Verify move does not leave own king in check
	origDest := board[toRow][toCol]
	board[toRow][toCol] = piece
	board[fromRow][fromCol] = "."

	var epRow int
	var epPiece string
	if isEnPassant {
		if isWhite {
			epRow = 3
		} else {
			epRow = 4
		}
		epPiece = board[epRow][toCol]
		board[epRow][toCol] = "."
	}

	inCheck := IsKingInCheck(board, isWhite)

	board[fromRow][fromCol] = piece
	board[toRow][toCol] = origDest
	if isEnPassant {
		board[epRow][toCol] = epPiece
	}

	if inCheck {
		return board, errors.New("langkah ilegal: Raja terkena skak")
	}

	// Execute move
	board[toRow][toCol] = finalPiece
	board[fromRow][fromCol] = "."

	if isEnPassant {
		if isWhite {
			board[3][toCol] = "."
		} else {
			board[4][toCol] = "."
		}
	}

	if isCastling {
		if isWhite {
			if toCol == 6 {
				board[7][5] = "R"
				board[7][7] = "."
			} else if toCol == 2 {
				board[7][3] = "R"
				board[7][0] = "."
			}
		} else {
			if toCol == 6 {
				board[0][5] = "r"
				board[0][7] = "."
			} else if toCol == 2 {
				board[0][3] = "r"
				board[0][0] = "."
			}
		}
	}

	// Update castling rights
	if piece == "K" {
		rights.WhiteKingMoved = true
	} else if piece == "k" {
		rights.BlackKingMoved = true
	} else if piece == "R" {
		if fromRow == 7 && fromCol == 0 {
			rights.WhiteLeftRookMoved = true
		} else if fromRow == 7 && fromCol == 7 {
			rights.WhiteRightRookMoved = true
		}
	} else if piece == "r" {
		if fromRow == 0 && fromCol == 0 {
			rights.BlackLeftRookMoved = true
		} else if fromRow == 0 && fromCol == 7 {
			rights.BlackRightRookMoved = true
		}
	}

	// Update en passant
	if (piece == "P" || piece == "p") && Abs(toRow-fromRow) == 2 {
		*enPassantCol = fromCol
	} else {
		*enPassantCol = -1
	}

	return board, nil
}

// ReplayUCI replays the entire sequence of chess moves from the beginning using UCI notation.
// Returns status ("PLAYING", "WHITE_WON", "BLACK_WON", "DRAW").
func ReplayUCI(movesUCI string) (Board, bool, string, error) {
	board := NewInitialBoard()
	var rights CastlingRights
	enPassantCol := -1
	isWhiteTurn := true

	moves := splitWords(movesUCI)
	if len(moves) == 0 {
		return board, isWhiteTurn, "PLAYING", nil
	}

	for _, uci := range moves {
		fromRow, fromCol, toRow, toCol, promoPiece, err := ParseUCIMove(uci)
		if err != nil {
			return board, isWhiteTurn, "PLAYING", errors.New("langkah " + uci + " tidak valid: " + err.Error())
		}

		newBoard, err := ApplyMove(board, fromRow, fromCol, toRow, toCol, promoPiece, isWhiteTurn, &rights, &enPassantCol)
		if err != nil {
			return board, isWhiteTurn, "PLAYING", errors.New("langkah " + uci + " ilegal: " + err.Error())
		}
		board = newBoard

		// Flip turn
		isWhiteTurn = !isWhiteTurn

		// Check if the current player is checkmated or stalemated
		if !HasAnyLegalMoves(board, isWhiteTurn, rights, enPassantCol) {
			if IsKingInCheck(board, isWhiteTurn) {
				if isWhiteTurn {
					// White's turn with no legal moves and in check -> Black wins
					return board, isWhiteTurn, "BLACK_WON", nil
				}
				// Black's turn with no legal moves and in check -> White wins
				return board, isWhiteTurn, "WHITE_WON", nil
			}
			// Stalemate -> Draw
			return board, isWhiteTurn, "DRAW", nil
		}
	}

	return board, isWhiteTurn, "PLAYING", nil
}

rules_test.gno

package chess

import (
	"testing"
)

func TestNewInitialBoard(t *testing.T) {
	b := NewInitialBoard()

	// Check White Backrank
	if b[7][4] != "K" || b[7][3] != "Q" {
		t.Fatalf("unexpected white backrank: %v", b[7])
	}
	// Check Black Backrank
	if b[0][4] != "k" || b[0][3] != "q" {
		t.Fatalf("unexpected black backrank: %v", b[0])
	}
	// Check Pawns
	for c := 0; c < 8; c++ {
		if b[6][c] != "P" {
			t.Fatalf("expected white pawn at (6,%d), got %s", c, b[6][c])
		}
		if b[1][c] != "p" {
			t.Fatalf("expected black pawn at (1,%d), got %s", c, b[1][c])
		}
	}
}

func TestPieceMoveValidations(t *testing.T) {
	b := NewInitialBoard()
	var rights CastlingRights

	// 1. Pawn e2-e4 (from 6,4 to 4,4) is valid
	if !IsValidMove(b, 6, 4, 4, 4, true, rights, -1) {
		t.Fatal("e2-e4 pawn move should be valid")
	}

	// 2. Knight b1-c3 (from 7,1 to 5,2) is valid
	if !IsValidMove(b, 7, 1, 5, 2, true, rights, -1) {
		t.Fatal("knight b1-c3 move should be valid")
	}

	// 3. Bishop c1-e3 should be blocked initially by pawns
	if IsValidMove(b, 7, 2, 5, 4, true, rights, -1) {
		t.Fatal("bishop cannot jump over pawns")
	}
}

func TestPromotionNormalization(t *testing.T) {
	// White default promotion
	p, err := NormalizePromotionPiece("", true)
	if err != nil || p != "Q" {
		t.Fatalf("expected 'Q', got %s, err: %v", p, err)
	}

	// Black knight promotion
	p, err = NormalizePromotionPiece("n", false)
	if err != nil || p != "n" {
		t.Fatalf("expected 'n', got %s, err: %v", p, err)
	}

	// Invalid piece
	_, err = NormalizePromotionPiece("K", true)
	if err == nil {
		t.Fatal("expected error for invalid promotion to King")
	}
}

func TestReplayUCI(t *testing.T) {
	// 1. Scholar's Mate -> White checkmates Black
	scholarsMate := "e2e4 e7e5 d1h5 b8c6 f1c4 g8f6 h5f7"
	_, _, status, err := ReplayUCI(scholarsMate)
	if err != nil {
		t.Fatalf("unexpected error replaying scholar's mate: %v", err)
	}
	if status != "WHITE_WON" {
		t.Fatalf("expected status WHITE_WON, got %s", status)
	}

	// 2. Fool's Mate -> Black checkmates White in 2 moves
	foolsMate := "f2f3 e7e5 g2g4 d8h4"
	_, _, status, err = ReplayUCI(foolsMate)
	if err != nil {
		t.Fatalf("unexpected error replaying fool's mate: %v", err)
	}
	if status != "BLACK_WON" {
		t.Fatalf("expected status BLACK_WON, got %s", status)
	}

	// 3. Ongoing game -> status PLAYING
	ongoing := "e2e4 e7e5 g1f3"
	_, _, status, err = ReplayUCI(ongoing)
	if err != nil {
		t.Fatalf("unexpected error replaying ongoing game: %v", err)
	}
	if status != "PLAYING" {
		t.Fatalf("expected status PLAYING, got %s", status)
	}

	// 4. Illegal move -> returns error
	illegal := "e2e5"
	_, _, _, err = ReplayUCI(illegal)
	if err == nil {
		t.Fatal("expected error for illegal move e2e5")
	}
}

types.gno

package chess

// Board represents an 8x8 chess board matrix
type Board [8][8]string

// CastlingRights tracks whether king or rooks have moved
type CastlingRights struct {
	WhiteKingMoved      bool
	WhiteLeftRookMoved  bool
	WhiteRightRookMoved bool
	BlackKingMoved      bool
	BlackLeftRookMoved  bool
	BlackRightRookMoved bool
}

// NewInitialBoard returns the standard starting position for a chess game
func NewInitialBoard() Board {
	var b Board

	// Row 0 & 1: Black pieces (lowercase)
	b[0] = [8]string{"r", "n", "b", "q", "k", "b", "n", "r"}
	b[1] = [8]string{"p", "p", "p", "p", "p", "p", "p", "p"}

	// Row 2 to 5: Empty squares
	for i := 2; i < 6; i++ {
		b[i] = [8]string{".", ".", ".", ".", ".", ".", ".", "."}
	}

	// Row 6 & 7: White pieces (uppercase)
	b[6] = [8]string{"P", "P", "P", "P", "P", "P", "P", "P"}
	b[7] = [8]string{"R", "N", "B", "Q", "K", "B", "N", "R"}

	return b
}

// GetPieceEmoji converts a piece character string to a unicode chess emoji
func GetPieceEmoji(p string) string {
	switch p {
	// White pieces
	case "R": return "♖"
	case "N": return "♘"
	case "B": return "♗"
	case "Q": return "♕"
	case "K": return "♔"
	case "P": return "♙"
	// Black pieces
	case "r": return "♜"
	case "n": return "♞"
	case "b": return "♝"
	case "q": return "♛"
	case "k": return "♚"
	case "p": return "♟"
	default: return " " // Empty square
	}
}

// IsWhitePiece returns true if the piece belongs to White
func IsWhitePiece(p string) bool {
	return p >= "A" && p <= "Z"
}

// IsBlackPiece returns true if the piece belongs to Black
func IsBlackPiece(p string) bool {
	return p >= "a" && p <= "z"
}

// Abs returns the absolute value of an integer
func Abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}