CPG/src/Chess/player.nim

61 lines
1.9 KiB
Nim
Raw Normal View History

2023-10-13 11:54:57 +02:00
import board as chess
2023-10-16 22:14:58 +02:00
import std/strformat
import std/strutils
2023-03-18 18:14:30 +01:00
2023-10-16 14:55:43 +02:00
2023-10-16 22:14:58 +02:00
2023-10-17 12:08:07 +02:00
when isMainModule:
setControlCHook(proc () {.noconv.} = echo ""; quit(0))
2023-10-17 22:16:01 +02:00
const fen = "rnbqkbnr/2p/8/8/8/8/P7/RNBQKBNR w KQkq - 0 1"
2023-10-17 12:08:07 +02:00
var
2023-10-17 22:16:01 +02:00
board = newChessboardFromFEN(fen)
canCastle: tuple[queen, king: bool]
2023-10-17 12:08:07 +02:00
data: string
move: Move
echo "\x1Bc"
2023-10-17 12:08:07 +02:00
while true:
2023-10-17 22:16:01 +02:00
canCastle = board.canCastle()
2023-10-17 12:08:07 +02:00
echo &"{board.pretty()}"
echo &"Turn: {board.getSideToMove()}"
echo &"Moves: {board.getMoveCount()} full, {board.getHalfMoveCount()} half"
2023-10-17 22:16:01 +02:00
echo &"Can castle:\n - King side: {(if canCastle.king: \"yes\" else: \"no\")}\n - Queen side: {(if canCastle.queen: \"yes\" else: \"no\")}"
2023-10-17 16:38:43 +02:00
stdout.write(&"En passant target: ")
if board.getEnPassantTarget() != emptyLocation():
echo board.getEnPassantTarget().locationToAlgebraic()
2023-10-17 16:38:43 +02:00
else:
echo "None"
stdout.write(&"Check: ")
2023-10-17 12:08:07 +02:00
if board.inCheck():
2023-10-17 16:38:43 +02:00
echo &"Yes"
else:
echo "No"
2023-10-17 22:16:01 +02:00
stdout.write("\nMove(s) -> ")
2023-10-17 12:08:07 +02:00
try:
data = readLine(stdin).strip(chars={'\0', ' '})
except IOError:
echo ""
break
2023-10-17 15:08:46 +02:00
if data == "undo":
echo &"\x1BcUndo: {board.undoLastMove()}"
2023-10-17 15:08:46 +02:00
continue
2023-10-17 22:16:01 +02:00
if data == "reset":
echo &"\x1BcBoard reset"
board = newChessboardFromFEN(fen)
2023-10-17 12:08:07 +02:00
continue
2023-10-17 22:16:01 +02:00
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"