Files
swift-chess/Sources/exe/main.swift

110 lines
2.5 KiB
Swift

import Engine
enum Command: Equatable {
case quit
case noop
case print
case move(from: String, to: String)
case history(command: String? = nil)
case highlightThreatened(color: Color)
case highlightPositions(of: Square.Position)
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:
nil
}
if let c = color {
self = .highlightThreatened(color: c)
return
}
if let position = try? Square.Position(with: String(args[1])) {
self = .highlightPositions(of: position)
return
}
return nil
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)]))
}
case .highlightPositions(let pos):
if let square = board.getSquareInfo(on: pos),
let piece =
square.piece
{
let color = Board.TerminalColors(fg: .def, bg: .green)
print(board.text(with: [color: piece.legalPositions]))
}
}
}
}
// Execute every time the timer changes
// board.on(.timer) { time in
// }