-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchess_engine.gleam
More file actions
344 lines (319 loc) · 9.34 KB
/
chess_engine.gleam
File metadata and controls
344 lines (319 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Main chess engine with CLI interface
import gleam/io
import gleam/string
import gleam/list
import gleam/int
import gleam/option.{type Option, None, Some}
@external(erlang, "io", "get_line")
fn get_line(prompt: String) -> String
import types.{
type GameState, type Move, White, Black,
algebraic_to_square, square_to_algebraic,
}
import board.{new_game, display_board, make_move, undo_move, get_piece}
import move_generator.{get_legal_moves, is_in_check}
import fen.{parse_fen, export_fen}
import ai.{find_best_move}
import perft.{perft}
pub type ChessEngine {
ChessEngine(game_state: GameState)
}
pub fn new() -> ChessEngine {
ChessEngine(new_game())
}
pub fn main() {
let engine = new()
io.println(display_board(engine.game_state))
game_loop(engine)
}
fn game_loop(engine: ChessEngine) -> Nil {
let input = get_line("")
let command = string.trim(input)
case command {
"quit" -> Nil
_ -> {
let new_engine = process_command(engine, command)
game_loop(new_engine)
}
}
}
fn process_command(engine: ChessEngine, command: String) -> ChessEngine {
let parts = string.split(command, " ")
case parts {
["move", move_str] -> handle_move(engine, move_str)
["undo"] -> handle_undo(engine)
["new"] -> handle_new(engine)
["ai", depth_str] -> handle_ai(engine, depth_str)
["fen", ..fen_parts] -> handle_fen(engine, string.join(fen_parts, " "))
["export"] -> handle_export(engine)
["eval"] -> handle_eval(engine)
["perft", depth_str] -> handle_perft(engine, depth_str)
["help"] -> handle_help(engine)
_ -> {
io.println("ERROR: Invalid command")
engine
}
}
}
fn handle_move(engine: ChessEngine, move_str: String) -> ChessEngine {
case string.length(move_str) >= 4 {
False -> {
io.println("ERROR: Invalid move format")
engine
}
True -> {
let from_str = string.slice(move_str, 0, 2)
let to_str = string.slice(move_str, 2, 2)
let promotion_str = case string.length(move_str) > 4 {
True -> Some(string.slice(move_str, 4, 1))
False -> None
}
case algebraic_to_square(from_str), algebraic_to_square(to_str) {
Ok(from_square), Ok(to_square) -> {
case get_piece(engine.game_state, from_square) {
None -> {
io.println("ERROR: No piece at source square")
engine
}
Some(piece) -> {
case piece.color == engine.game_state.turn {
False -> {
io.println("ERROR: Wrong color piece")
engine
}
True -> {
let legal_moves =
get_legal_moves(
engine.game_state,
engine.game_state.turn,
)
let matching_move =
find_matching_move(
legal_moves,
from_square,
to_square,
promotion_str,
)
case matching_move {
None -> {
case
is_in_check(
engine.game_state,
engine.game_state.turn,
)
{
True -> io.println("ERROR: King would be in check")
False -> io.println("ERROR: Illegal move")
}
engine
}
Some(chess_move) -> {
let new_state =
make_move(engine.game_state, chess_move)
io.println("OK: " <> move_str)
io.println(display_board(new_state))
check_game_end(new_state)
ChessEngine(new_state)
}
}
}
}
}
}
}
_, _ -> {
io.println("ERROR: Invalid move format")
engine
}
}
}
}
}
fn find_matching_move(
moves: List(Move),
from: Int,
to: Int,
promotion_str: Option(String),
) -> Option(Move) {
list.find(moves, fn(chess_move) {
chess_move.from == from
&& chess_move.to == to
&& is_promotion_match(chess_move.promotion, promotion_str)
})
|> option.from_result
}
fn is_promotion_match(
move_promotion: Option(types.PieceType),
requested: Option(String),
) -> Bool {
case move_promotion, requested {
Some(types.Queen), None -> True
Some(types.Queen), Some("Q") -> True
Some(types.Queen), Some("q") -> True
Some(types.Rook), Some("R") -> True
Some(types.Rook), Some("r") -> True
Some(types.Bishop), Some("B") -> True
Some(types.Bishop), Some("b") -> True
Some(types.Knight), Some("N") -> True
Some(types.Knight), Some("n") -> True
None, None -> True
_, _ -> False
}
}
fn handle_undo(engine: ChessEngine) -> ChessEngine {
case engine.game_state.move_history {
[] -> {
io.println("ERROR: No moves to undo")
engine
}
_ -> {
let new_state = undo_move(engine.game_state)
io.println("Move undone")
io.println(display_board(new_state))
ChessEngine(new_state)
}
}
}
fn handle_new(_engine: ChessEngine) -> ChessEngine {
let new_state = new_game()
io.println("New game started")
io.println(display_board(new_state))
ChessEngine(new_state)
}
fn handle_ai(engine: ChessEngine, depth_str: String) -> ChessEngine {
case int.parse(depth_str) {
Error(_) -> {
io.println("ERROR: AI depth must be 1-5")
engine
}
Ok(depth) -> {
case depth < 1 || depth > 5 {
True -> {
io.println("ERROR: AI depth must be 1-5")
engine
}
False -> {
let result = find_best_move(engine.game_state, depth)
case result.best_move {
None -> {
io.println("ERROR: No legal moves available")
engine
}
Some(chess_move) -> {
let move_str =
square_to_algebraic(chess_move.from)
<> square_to_algebraic(chess_move.to)
<> case chess_move.promotion {
Some(types.Queen) -> "Q"
Some(types.Rook) -> "R"
Some(types.Bishop) -> "B"
Some(types.Knight) -> "N"
_ -> ""
}
let new_state = make_move(engine.game_state, chess_move)
io.println(
"AI: "
<> move_str
<> " (depth="
<> int.to_string(depth)
<> ", eval="
<> int.to_string(result.evaluation)
<> ", time="
<> int.to_string(result.time_ms)
<> "ms)",
)
io.println(display_board(new_state))
check_game_end(new_state)
ChessEngine(new_state)
}
}
}
}
}
}
}
fn handle_fen(engine: ChessEngine, fen_string: String) -> ChessEngine {
case parse_fen(fen_string) {
Error(err) -> {
io.println(err)
engine
}
Ok(new_state) -> {
io.println("Position loaded from FEN")
io.println(display_board(new_state))
ChessEngine(new_state)
}
}
}
fn handle_export(engine: ChessEngine) -> ChessEngine {
let fen = export_fen(engine.game_state)
io.println("FEN: " <> fen)
engine
}
fn handle_eval(engine: ChessEngine) -> ChessEngine {
let result = find_best_move(engine.game_state, 1)
io.println("Position evaluation: " <> int.to_string(result.evaluation))
engine
}
fn handle_perft(engine: ChessEngine, depth_str: String) -> ChessEngine {
case int.parse(depth_str) {
Error(_) -> {
io.println("ERROR: Invalid perft depth")
engine
}
Ok(depth) -> {
case depth < 1 {
True -> {
io.println("ERROR: Invalid perft depth")
engine
}
False -> {
let nodes = perft(engine.game_state, depth)
io.println(
"Perft("
<> int.to_string(depth)
<> "): "
<> int.to_string(nodes)
<> " nodes (0ms)",
)
engine
}
}
}
}
}
fn handle_help(engine: ChessEngine) -> ChessEngine {
io.println("Available commands:")
io.println(
" move <from><to>[promotion] - Make a move (e.g., e2e4, e7e8Q)",
)
io.println(" undo - Undo the last move")
io.println(" new - Start a new game")
io.println(" ai <depth> - Let AI make a move (depth 1-5)")
io.println(" fen <string> - Load position from FEN")
io.println(" export - Export current position as FEN")
io.println(" eval - Evaluate current position")
io.println(" perft <depth> - Run performance test")
io.println(" help - Show this help message")
io.println(" quit - Exit the program")
engine
}
fn check_game_end(game_state: GameState) -> Nil {
let color = game_state.turn
let legal_moves = get_legal_moves(game_state, color)
case list.is_empty(legal_moves) {
False -> Nil
True -> {
case is_in_check(game_state, color) {
True -> {
let winner = case color {
White -> "Black"
Black -> "White"
}
io.println("CHECKMATE: " <> winner <> " wins")
}
False -> io.println("STALEMATE: Draw")
}
}
}
}