Added commands to execute interactively

This commit is contained in:
cdricms
2024-06-29 20:32:40 +02:00
parent 90f2988a14
commit 533322c5dd
4 changed files with 167 additions and 34 deletions

View File

@@ -1,29 +1,91 @@
import Engine
let board = Board(
fen: .init(
fen: "rnbqkb1r/pppppppp/2n5/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"))
// let board: Board = .init()
enum Command: Equatable {
case quit
case noop
case print
case move(from: String, to: String)
case history(command: String? = nil)
case highlightThreatened(color: Color)
init?(rawValue: String) {
let args = rawValue.lowercased().split(separator: " ")
guard !args.isEmpty else {
return nil
}
switch args[0] {
case "quit", "q":
self = .quit
case "noop", "n":
self = .noop
case "print", "p":
self = .print
case "move" where args.count == 3, "m" where args.count == 3:
self = .move(from: String(args[1]), to: String(args[2]))
case "history" where args.count == 2, "h" where args.count == 2:
self = .history(command: String(args[1]))
case "history", "h":
self = .history()
case "highlight" where args.count == 2, "hi" where args.count == 2:
let color: Color =
switch args[1] {
case "w", "white":
.White
case "b", "black":
.Black
default:
.White
}
self = .highlightThreatened(color: color)
default:
return nil
}
}
}
let board: Board = .init()
print(board)
var command: Command = .noop
while command != .quit {
if let line = readLine(), let c = Command(rawValue: line.lowercased()) {
command = c
switch command {
case .print: print(board)
case .noop, .quit: continue
case .move(let from, let to):
do {
try board.move(src: from, dst: to)
} catch {
print(error)
continue
}
case .history(let command):
if let c = command {
if let fmc = Int(c),
fmc > -1 && fmc < board.history.values.count
{
print(board.history.values[fmc])
} else if c == "count" {
print(board.history.values.count)
} else {
print(board.history.values)
}
} else {
print(board.history.values)
}
case .highlightThreatened(let color):
if let ts = board.threatenedSquares[color] {
let color = Board.TerminalColors(fg: .def, bg: .red)
print(ts.count)
print(board.text(with: [color: Array(ts)]))
}
}
}
}
// Execute every time the timer changes
// board.on(.timer) { time in
// }
do {
try board.move(src: "e4", dst: "f6")
} catch {
print(error)
}
do {
try board.move(src: .init(rank: 2, file: 5), dst: .init(rank: 4, file: 5))
} catch {
print(error)
}
print(board)
print(board.fen)
print(board.history.values)
// let square = board.getSquareInfo(on: .init(rank: 2, file: 7))