CPG/src/Chess/player.nim

61 lines
1.9 KiB
Nim

import board as chess
import std/strformat
import std/strutils
when isMainModule:
setControlCHook(proc () {.noconv.} = echo ""; quit(0))
const fen = "rnbqkbnr/2p/8/8/8/8/P7/RNBQKBNR w KQkq - 0 1"
var
board = newChessboardFromFEN(fen)
canCastle: tuple[queen, king: bool]
data: string
move: Move
echo "\x1Bc"
while true:
canCastle = board.canCastle()
echo &"{board.pretty()}"
echo &"Turn: {board.getSideToMove()}"
echo &"Moves: {board.getMoveCount()} full, {board.getHalfMoveCount()} half"
echo &"Can castle:\n - King side: {(if canCastle.king: \"yes\" else: \"no\")}\n - Queen side: {(if canCastle.queen: \"yes\" else: \"no\")}"
stdout.write(&"En passant target: ")
if board.getEnPassantTarget() != emptyLocation():
echo board.getEnPassantTarget().locationToAlgebraic()
else:
echo "None"
stdout.write(&"Check: ")
if board.inCheck():
echo &"Yes"
else:
echo "No"
stdout.write("\nMove(s) -> ")
try:
data = readLine(stdin).strip(chars={'\0', ' '})
except IOError:
echo ""
break
if data == "undo":
echo &"\x1BcUndo: {board.undoLastMove()}"
continue
if data == "reset":
echo &"\x1BcBoard reset"
board = newChessboardFromFEN(fen)
continue
for moveChars in data.split(" "):
if len(moveChars) != 4:
echo "\x1BcError: invalid move"
break
try:
move = board.makeMove(moveChars[0..1], moveChars[2..3])
except ValueError:
echo &"\x1BcError: {getCurrentExceptionMsg()}"
if move == emptyMove():
echo &"\x1BcError: move '{moveChars}' is illegal"
break
else:
echo "\x1Bc"