-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
MicroChess.ino
1563 lines (1261 loc) · 51.2 KB
/
MicroChess.ino
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ArduinoChess.ino
*
* the MicroChess project: https://github.com/ripred/MicroChess
*
* version 1.0.0
* written March thru May 2023 - Trent M. Wyatt
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* TODO:
*
* [ ]
* [ ] Add awareness of other Arduino's on the I2C bus acting as slave devices
* and add the ability to parallel process to moves between all available
* CPU's!
* [ ] Change to use true printf, stdin, stdout and stderr so we don't copy the fmt buffer
* [ ] Add tests that prove that the same moves are chosen when alpha-beta
* pruning is enabled that are chosen when it is disabled and running in brute force?
* [ ] Add optional use of I2C serial RAM to create transposition tables for
* moves that have already been searced during this turn.
* [+] Fix problems with:
* [+] King's in check not being detected or reported correctly
* [+] King's not reacting when in check
* [+] Change skip logic to use the same percentage based logic as the mistakes logic
* [+] Fix alpha-beta bug!
* [+] Finish enabling the en-passant pawn move generation.
* [+] Add a function to display times over 1000 ms as minutes, seconds, and ms
* [+] Add flags to the game to indicate whether each side is human or not
* [+] Add the display of the full game time so far to each show() update
* [+] Enhance to pause the game when a newline is received
* [+] Enhance the game to allow moves to be entered by a human via the serial port
* [+] Change make_move(...) to return MIN_VALUE only if the ply level is 0
* so we don't actually choose it. Otherwise consider taking the King
* worth MAX_VALUE.
* [+] Change to have two sets of option_t in the game, one for each player in order to test
* option settings against each other
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
*/
#include <Arduino.h>
#include <math.h>
#include "MicroChess.h"
// #include <Wire.h>
////////////////////////////////////////////////////////////////////////////////////////
// The game board
board_t board;
////////////////////////////////////////////////////////////////////////////////////////
// The currently running game states and flags
game_t game;
// Un-comment the following line to display each move as it is evaluated
// #define SHOW1
////////////////////////////////////////////////////////////////////////////////////////
// Consider a move against the best white move or the best black move
// depending on the color of the piece and set this as the best move
// if it has a higher value (or an equal value when we're using random)
//
// Note: Sanitized stack
void consider_move(piece_gen_t &gen)
{
// Stack Management
// DECLARE ALL LOCAL VARIABLES USED IN THIS CONTEXT HERE AND
// DO NOT MODIFY ANYTHING BEFORE CHECKING THE AVAILABLE STACK
Bool dont_move;
// Check for low stack space
if (check_mem(CONSIDER)) { return; }
dont_move = False;
if (PLAYING != game.state) {
return;
}
// If this is a supplied move that has already been validated then just return:
if (game.supply_valid) {
return;
}
// See if the destination is a king, and if so then don't really make the move
// or evaluate it; Just return MAX or MIN value depending on whose side it is:
if (getType(board.get(gen.move.to)) == King) {
if (gen.whites_turn) {
game.white_king_in_check = True;
gen.move.value = MAX_VALUE;
}
else {
game.black_king_in_check = True;
gen.move.value = MIN_VALUE;
}
show_check();
dont_move = True;
}
// See if the move came from the user or from an opening book:
if (game.book_supplied || game.user_supplied) {
if ((gen.move.from == game.supplied.from) && (gen.move.to == game.supplied.to)) {
game.supply_valid = True;
return;
}
}
// Check for alpha or beta cutoff
if (gen.cutoff) {
#ifdef SHOW1
if (0 == game.ply) {
printf(Debug1, "** ");
}
#endif
dont_move = True;
}
// Recursively generate the move's value
if (!dont_move) {
make_move(gen);
}
if (Pawn == gen.piece) {
// Reward any moves involving a Pawn slightly
gen.move.value += (gen.whites_turn ? +10 : -10);
}
// See if we are in the end game
if (game.piece_count <= END_COUNT) {
if (Pawn == gen.piece) {
// Reward any moves involving a Pawn at this point
gen.move.value += (gen.whites_turn ? +5000 : -5000);
}
else {
// Otherwise make all pieces converge on the opponent's King.
// Get the location of the opponent's King
index_t kingloc = (gen.whites_turn ? game.bking : game.wking);
index_t king_col = kingloc % 8;
index_t king_row = kingloc / 8;
// Get the difference between our destination and the opponent's king
index_t delta_col = abs((gen.move.to % 8) - king_col);
index_t delta_row = abs((gen.move.to / 8) - king_row);
gen.move.value = (14 - (delta_col + delta_row)) +
(gen.whites_turn ? game.black_king_in_check : game.white_king_in_check) * 10;
}
}
if (gen.whites_turn && game.white_king_in_check) {
gen.move.value = MIN_VALUE;
}
if (!gen.whites_turn && game.black_king_in_check) {
gen.move.value = MAX_VALUE;
}
// Penalize the move if it would cause us to lose by move repetition
if (would_repeat(gen.move)) {
gen.move.value = gen.whites_turn ? MIN_VALUE : MAX_VALUE;
}
// See if this move is equal to OR greater than the best move we've seen so far
if (gen.whites_turn) {
if ((gen.move.value == gen.wbest.value) && random(2)) {
gen.wbest = gen.move;
}
else if (gen.move.value > gen.wbest.value) {
gen.wbest = gen.move;
}
}
else {
if ((gen.move.value == gen.bbest.value) && random(2)) {
gen.bbest = gen.move;
}
else if (gen.move.value < gen.bbest.value) {
gen.bbest = gen.move;
}
}
// Debugging output
#ifdef SHOW1
if (0 == game.ply) {
show_move(gen.move, True);
}
#endif
} // consider_move(piece_gen_t &gen)
////////////////////////////////////////////////////////////////////////////////////////
// Move a piece on the board, taking a piece if necessary. Evaluate the value of the
// board after the move. Optionally restore the board back to it's original state after
// evaluating the value of the move.
//
// This is a big and complicated function.
// It performs 5 major steps:
//
// 1) Identify the piece being moved
// 2) Identify any piece being captured and remove it if so
// 3) Place the piece being moved at the destination
// 4) Evaluate the board score after making the move
// 5) If we are just considering the move then put everything back
//
// returns the value of the board after the move was made
//
// Note: Sanitized stack
long make_move(piece_gen_t & gen)
{
// Stack Management
// DECLARE ALL LOCAL VARIABLES USED IN THIS CONTEXT HERE AND
// DO NOT MODIFY ANYTHING BEFORE CHECKING THE AVAILABLE STACK
struct local_t {
uint8_t
op : 6,
book_supplied : 1,
user_supplied : 1, // 8
board_rook : 6,
last_was_pawn_promotion : 1,
last_was_en_passant : 1, // 16
place_piece : 6,
white_king_in_check : 1,
black_king_in_check : 1, // 24
captured_piece : 6,
last_was_castle : 1,
quiescent : 1, // 32
to_col : 3,
supply_valid : 1,
to_row : 3,
oside : 1, // 40
wking : 6,
bking : 6,
white_taken_count : 5,
black_taken_count : 5,
otype : 3; // 65 bits (9 bytes)
} vars;
index_t taken_index, captured, castly_rook, hist_count;
game_t::history_t history[MAX_REPS * 2 - 1];
move_t last_move, wbest, bbest;
int32_t recurse_value;
// Check for low stack space
if (check_mem(MAKE)) { return gen.whites_turn ? MIN_VALUE : MAX_VALUE; }
// Now we can alter local variables! 😎
// The value of the board.
// Default to the worst value for our side.
// i.e: Don't make the move whatever it is
gen.move.value = gen.whites_turn ? MIN_VALUE : MAX_VALUE;
/// Step 1: Identify the piece being moved
vars.to_col = uint8_t(gen.move.to % 8);
vars.to_row = uint8_t(gen.move.to / 8);
vars.op = board.get(gen.move.to);
vars.otype = getType(vars.op);
vars.oside = getSide(vars.op);
// Save the current last 5 moves in the game history
hist_count = game.hist_count;
// Save the current king locations
vars.wking = game.wking;
vars.bking = game.bking;
// Save the current number of taken pieces
vars.white_taken_count = game.white_taken_count;
vars.black_taken_count = game.black_taken_count;
// Save the current last move and move flags
vars.last_was_pawn_promotion = game.last_was_pawn_promotion;
vars.last_was_en_passant = game.last_was_en_passant;
vars.last_was_castle = game.last_was_castle;
last_move = game.last_move;
// Save the user supplied and book supplied flags
vars.book_supplied = game.book_supplied;
vars.user_supplied = game.user_supplied;
vars.supply_valid = game.supply_valid;
if (gen.evaluating) {
memmove(history, game.history, sizeof(history));
game.stats.inc_moves_count();
}
// Save the state of whether or not the kings are in check.
// We do this AFTER we've had a chance to set the 'king-in-check'
// flags above so that this move leaves the flags behind after evaluation
vars.white_king_in_check = game.white_king_in_check;
vars.black_king_in_check = game.black_king_in_check;
/// Step 2: Identify any piece being captured and remove it if so.
//
// * NOTE BELOW *
// Once any changes have been made to the board or game state we MUST NOT return
// without passing through the "if (gen.evaluating) { ... }" restoration logic.
// The game.pieces[] index being captured (if any, -1 if none)
taken_index = -1;
// The board index being captured (if any, -1 if none)
captured = -1;
vars.captured_piece = Empty;
// Check for en-passant capture
if (Pawn == gen.type && isEmpty(vars.otype) && gen.col != vars.to_col) {
game.last_was_en_passant = True;
captured = vars.to_col + gen.row * 8u;
vars.captured_piece = board.get(captured);
}
else {
// See if the destination is not empty and not a piece on our side.
// i.e. an opponent's piece.
if (Empty != vars.otype && gen.side != vars.oside) {
captured = gen.move.to;
vars.captured_piece = board.get(captured);
}
}
// If a piece was taken, make the change on the board and to the game.pieces[] list
if (-1 != captured) {
// Remember the piece index of the piece being taken
taken_index = game.find_piece(captured);
// Change the spot on the board for the taken piece to Empty
board.set(captured, Empty);
// Soft-delete the piece taken in the piece list!
game.pieces[taken_index] = { -1, -1 };
// Add the piece to the list of taken pieces
if (gen.whites_turn) {
game.taken_by_white[game.white_taken_count++].piece = vars.captured_piece;
}
else {
game.taken_by_black[game.black_taken_count++].piece = vars.captured_piece;
}
}
/// Step 3: Place the piece being moved at the destination
// Set the 'moved' flag on the piece that we place on the board
vars.place_piece = setMoved(gen.piece, True);
// Promote a Pawn to a Queen if it reaches the back row
if (Pawn == gen.type && (vars.to_row == (gen.whites_turn ? index_t(0) : index_t(7)))) {
vars.place_piece = setType(vars.place_piece, Queen);
game.last_was_pawn_promotion = True;
}
// Move the piece to the destination on the board
board.set(gen.move.from, Empty);
board.set(gen.move.to, vars.place_piece);
// Update the piece list to reflect the piece's new location
game.pieces[gen.piece_index] = { index_t(vars.to_col), index_t(vars.to_row) };
// Check for castling
castly_rook = -1;
// If the piece being moved is a King
if (King == gen.type) {
// Update this side's king location
((White == gen.side) ? game.wking : game.bking) = gen.move.to;
// Get the horizontal distance the king is
// moving and see if it is a Castling move
if (abs(vars.to_col - (gen.move.from % 8)) > 1) {
// see which side we're castling on
if (2 == abs(vars.to_col - (gen.move.from % 8))) {
// Castle on the King's side
vars.board_rook = 7 + gen.row * 8u;
castly_rook = game.find_piece(vars.board_rook);
board.set(vars.board_rook, setMoved(board.get(vars.board_rook), True));
game.pieces[castly_rook].x = 5;
game.last_was_castle = True;
}
else if (3 == abs(vars.to_col - (gen.move.from % 8))) {
// Castle on the Queen's side
vars.board_rook = 0 + gen.row * 8u;
castly_rook = game.find_piece(vars.board_rook);
board.set(vars.board_rook, setMoved(board.get(vars.board_rook), True));
game.pieces[castly_rook].x = 3;
game.last_was_castle = True;
}
}
}
/// Step 4: Evaluate the board score after making the move
// Get the value of the current board
gen.move.value = evaluate(gen);
// Control the percentage of moves that the engine makes a mistake on
if (0 != game.options.mistakes) {
if (random(100) <= game.options.mistakes) {
gen.move.value -= gen.whites_turn ? +5000 : -5000;
}
}
// set our move as the last move
game.last_move = gen.move;
////////////////////////////////////////////////////////////////////////////////////////
// The move has been made and we have the value for the updated board.
// Recursively look-ahead and accumulatively update the value here.
//
if (gen.evaluating) {
// flag indicating whether we are traversing into quiescent moves
vars.quiescent = ((-1 != captured) && (game.ply < (game.options.max_quiescent_ply)) && (game.ply < game.options.max_max_ply));
if (((game.ply < game.options.maxply) || vars.quiescent)) {
if (!timeout()) {
// Indicate whether we are on a quiescent search or not
if (vars.quiescent) {
show_quiescent_search();
}
else {
direct_write(DEBUG2_PIN, LOW);
}
if ((0 == game.options.randskip) || (random(100) > game.options.randskip)) {
// Explore The Future! (plies)
game.ply++;
game.turn = !game.turn;
if (game.ply > game.stats.move_stats.depth) {
game.stats.move_stats.depth = game.ply;
}
wbest = { -1, -1, game.alpha };
bbest = { -1, -1, game.beta };
reset_turn_flags();
choose_best_moves(wbest, bbest, consider_move);
game.turn = !game.turn;
game.ply--;
if (gen.whites_turn) {
if (-1 != gen.wbest.from && -1 != gen.wbest.to) {
if (game.options.alpha_beta_pruning) {
recurse_value = max(gen.move.value, gen.wbest.value);
gen.move.value = game.options.integrate ? (gen.move.value + recurse_value) : recurse_value;
if (gen.move.value > game.beta) {
gen.cutoff = True;
}
else {
game.alpha = max((long) game.alpha, (long) gen.move.value);
}
}
else {
gen.move.value = game.options.integrate ? (gen.move.value + gen.wbest.value) : gen.wbest.value;
}
}
}
else {
if (-1 != gen.bbest.from && -1 != gen.bbest.to) {
if (game.options.alpha_beta_pruning) {
recurse_value = min(gen.move.value, gen.bbest.value);
gen.move.value = game.options.integrate ? (gen.move.value + recurse_value) : recurse_value;
if (gen.move.value < game.alpha) {
gen.cutoff = True;
}
else {
game.beta = min((long) game.beta, (long) gen.move.value);
}
}
else {
gen.move.value = game.options.integrate ? (gen.move.value + gen.bbest.value) : gen.bbest.value;
}
}
}
// We're finished calling into the future moves, and setting the new alpha and
// beta boundaries. Now make sure this move didn't place our king in check
// if (gen.whites_turn) {
// if (game.white_king_in_check) {
// gen.move.value = MIN_VALUE;
// }
// }
// else {
// if (game.black_king_in_check) {
// gen.move.value = MAX_VALUE;
// }
// }
if (game.ply > 0) {
game.white_king_in_check = vars.white_king_in_check;
game.black_king_in_check = vars.black_king_in_check;
}
}
}
}
} // if (gen.evaluating)
/// Step 5: If we are just considering the move then put everything back
if (gen.evaluating) {
if (-1 == captured) {
board.set(gen.move.to, vars.op);
} else {
// restore the captured board changes and
// set it's "in-check" flag
vars.captured_piece = setCheck(vars.captured_piece, True);
board.set(captured, vars.captured_piece);
// restore the captured piece list changes
game.pieces[taken_index] = { index_t(captured % 8), index_t(captured / 8) };
}
// restore the taken pieces list changes
game.white_taken_count = vars.white_taken_count;
game.black_taken_count = vars.black_taken_count;
// restore the changes made to the moves history
memmove(game.history, history, sizeof(history));
game.hist_count = hist_count;
// restore the moved piece board changes
board.set(gen.move.from, gen.piece);
// restore the moved piece pieces list changes
game.pieces[gen.piece_index] = { index_t(gen.col), index_t(gen.row) };
// restore the last move made
game.last_move = last_move;
// restore the last move flags
game.last_was_en_passant = vars.last_was_en_passant;
game.last_was_castle = vars.last_was_castle;
game.last_was_pawn_promotion = vars.last_was_pawn_promotion;
// game.white_king_in_check = vars.white_king_in_check;
// game.black_king_in_check = vars.black_king_in_check;
game.book_supplied = vars.book_supplied;
game.user_supplied = vars.user_supplied;
game.supply_valid = vars.supply_valid;
// Don't take the move if it leaves us in check
if (gen.whites_turn) {
if (game.white_king_in_check) {
gen.move.value = MIN_VALUE;
}
}
else {
if (game.black_king_in_check) {
gen.move.value = MAX_VALUE;
}
}
// restore the king's locations
game.wking = vars.wking;
game.bking = vars.bking;
// restore any rook moved during a castle move
game.last_was_castle = vars.last_was_castle;
if (-1 != castly_rook) {
if (3 == game.pieces[castly_rook].x) {
game.pieces[castly_rook].x = 0;
}
else {
game.pieces[castly_rook].x = 7;
}
board.set((game.pieces[castly_rook].x + game.pieces[castly_rook].y * 8),
setMoved(board.get((game.pieces[castly_rook].x + game.pieces[castly_rook].y * 8)), False));
}
} // if (gen.evaluating)
return gen.move.value;
} // make_move(piece_gen_t & gen)
////////////////////////////////////////////////////////////////////////////////////////
// Evaluate the identity (score) of the board state.
// Positive scores indicate an advantage for white and
// Negative scores indicate an advantage for black.
// Uses pre-computed material bonus tables for speed.
//
// returns the score/value of the current board
//
// Note: Sanitized stack
long evaluate(piece_gen_t &gen)
{
// Stack Management
// DECLARE ALL LOCAL VARIABLES USED IN THIS CONTEXT HERE AND
// DO NOT MODIFY ANYTHING BEFORE CHECKING THE AVAILABLE STACK
long materialTotal, mobilityTotal, centerTotal, kingTotal, score;
index_t col, row, piece_index, kloc, col_dist, row_dist, proximity;
Piece p, ptype;
Color pside;
// Check for low stack space
if (check_mem(MAKE)) { return 0; }
// Now we can alter local variables! 😎
// Calculate the value of the board:
materialTotal = 0L;
mobilityTotal = 0L;
centerTotal = 0L;
kingTotal = 0L;
score = 0L;
for (piece_index = 0; piece_index < game.piece_count; piece_index++) {
col = game.pieces[piece_index].x;
row = game.pieces[piece_index].y;
if (-1 == col || -1 == row) continue;
p = board.get(col + row * 8);
ptype = getType(p);
pside = getSide(p);
if (Empty == ptype) continue;
// Material Bonus
materialTotal += pgm_read_dword(&game.material_bonus[ptype][pside]) * game.options.materialBonus;
// In-Check Penalty
if (inCheck(p)) {
if (White == ptype) {
materialTotal -= ptype;
}
else {
materialTotal += ptype;
}
}
// Let's not encourage the King to wander to
// the center of the board mmkay?
if (King == ptype) {
continue;
}
// Center Bonus
centerTotal +=
pgm_read_dword(&game.center_bonus[col][ptype][pside]) +
pgm_read_dword(&game.center_bonus[row][ptype][pside]);
// Proximity to opponent's King Bonus
kloc = (White == pside) ? game.bking : game.wking;
col_dist = (col > (kloc % 8)) ? (col - (kloc % 8)) : ((kloc % 8) - col);
row_dist = (row > (kloc / 8)) ? (row - (kloc / 8)) : ((kloc / 8) - row);
proximity = 14 - (col_dist + row_dist);
if (White == pside) {
kingTotal += proximity;
}
else {
kingTotal -= proximity;
}
}
kingTotal *= game.options.kingBonus;
// Mobility Bonus
if (gen.whites_turn) {
mobilityTotal += static_cast<long>(gen.num_wmoves * game.options.mobilityBonus);
}
else {
mobilityTotal -= static_cast<long>(gen.num_bmoves * game.options.mobilityBonus);
}
score = kingTotal + materialTotal + centerTotal + mobilityTotal;
// printf(Debug4,
// "evaluation: %ld = centerTotal: %ld materialTotal: %ld mobilityTotal: %ld\n",
// score, centerTotal, materialTotal, mobilityTotal);
return score;
} // evaluate(...)
////////////////////////////////////////////////////////////////////////////////////////
// Evaluate all of the available moves for both sides.
// The best moves are stored in wbest and bbest.
// The callback is called for each move, implementing the visitor pattern.
//
// This function is the top of the recursive call chain:
//
// choose_best_move(...)
// add_xxxx_moves(...)
// consider_move(...)
// make_move(...)
// choose_best_move(...)
//
// Note: Sanitized stack
void choose_best_moves(move_t &wbest, move_t &bbest, generator_t const callback)
{
// Stack Management
// DECLARE ALL LOCAL VARIABLES USED IN THIS CONTEXT HERE AND
// DO NOT MODIFY ANYTHING BEFORE CHECKING THE AVAILABLE STACK
// Check for low stack space
if (check_mem(CHOOSE)) { return; }
// Now we can alter local variables!
else {
static uint32_t last_led_update;
index_t move_count;
move_t move = { -1, -1, 0 };
piece_gen_t gen(move, wbest, bbest, callback, True);
gen.num_wmoves = 0;
gen.num_bmoves = 0;
// Turn off the 'King in check' LED
direct_write(DEBUG4_PIN, LOW);
// Walk through the game.pieces[] list and evaluate the moves for each one
for (gen.piece_index = 0; gen.piece_index < game.piece_count; gen.piece_index++) {
if (game.supply_valid || (PLAYING != game.state)) {
return;
}
if (check_serial()) {
return;
}
else {
gen.col = game.pieces[gen.piece_index].x;
if (-1 == gen.col) { continue; }
// Construct a move_t object with the starting location
gen.row = game.pieces[gen.piece_index].y;
gen.move.from = gen.col + gen.row * 8u;
gen.move.to = -1;
gen.piece = board.get(gen.move.from);
gen.type = getType(gen.piece);
gen.side = getSide(gen.piece);
gen.whites_turn = gen.side; // same as White == gen.side
gen.move.value = gen.whites_turn ? MIN_VALUE : MAX_VALUE;
if (Empty == gen.type) {
continue;
}
// Periodically update the LED strip display and progress indicator if enabled
if (game.options.live_update
// && (game.ply < game.options.max_max_ply)
// && (game.ply <= game.options.maxply)
) {
if ((millis() - last_led_update) >= 10)
{
last_led_update = millis();
set_led_strip(gen.move.from);
}
}
// Keep track of the location of the Kings
if (King == gen.type) {
(gen.whites_turn ? game.wking : game.bking) = gen.move.from;
}
// Check for move timeout (only if we're at ply level 2 or above,
// this happens internally in the timeout() function)
if (timeout()) {
break;
}
move_count = 0;
// Evaluate the moves for this Piece Type and get the highest value move
switch (gen.type) {
default: printf(Always, "bad type: line %d\n", __LINE__); break;
case Pawn: move_count = add_pawn_moves(gen); break;
case Knight: move_count = add_knight_moves(gen); break;
case Bishop: move_count = add_bishop_moves(gen); break;
case Rook: move_count = add_rook_moves(gen); break;
case Queen: move_count = add_queen_moves(gen); break;
case King:
move_count = add_king_moves(gen);
// if (0 == move_count) {
// if (White == gen.side && game.white_king_in_check) {
// game.state = BLACK_CHECKMATE;
// return;
// }
// if (Black == gen.side && game.black_king_in_check) {
// game.state = WHITE_CHECKMATE;
// return;
// }
// }
break;
}
// Keep track of the total number of moves for this side
(gen.whites_turn ? gen.num_wmoves : gen.num_bmoves) += move_count;
// Check for alpha or beta cuttoff
if (gen.cutoff) {
break;
}
// Check for move timeout if we've finished ply level 1
if (game.timeout1) {
break;
}
}
} // for each piece on both sides
// See if the game is over
if (0 == game.ply) {
// See if we only have the two kings on either side:
if (2 == game.piece_count) {
game.state = STALEMATE;
}
if ((0 == gen.num_wmoves) && (0 == gen.num_bmoves)) {
game.state = STALEMATE;
}
if ((0 == gen.num_wmoves) && game.white_king_in_check) {
game.state = BLACK_CHECKMATE;
}
if ((0 == gen.num_bmoves) && game.black_king_in_check) {
game.state = WHITE_CHECKMATE;
}
}
}
} // choose_best_moves(...)
////////////////////////////////////////////////////////////////////////////////////////
// Set the per-side options. This allows testing feature choices against each other
void set_per_side_options() {
if (game.turn) {
// White's turn
}
else {
// Black's turn
}
}
////////////////////////////////////////////////////////////////////////////////////////
// reset the various move tracking flags
//
// Note: Sanitized stack
void reset_turn_flags()
{
// Stack Management
// DECLARE ALL LOCAL VARIABLES USED IN THIS CONTEXT HERE AND
// DO NOT MODIFY ANYTHING BEFORE CHECKING THE AVAILABLE STACK
index_t index;
// Check for low stack space
if (check_mem(CHOOSE)) { return; }
// Now we can alter local variables! 😎
for (index = 0; index < game.piece_count; index++) {
if (-1 == game.pieces[index].x) { continue; }
board.set( game.pieces[index].x + game.pieces[index].y * 8,
setCheck(board.get(game.pieces[index].x + game.pieces[index].y * 8), False));
}
// reset the king-in-check flags
game.white_king_in_check = False;
game.black_king_in_check = False;
game.last_was_en_passant = False;
game.last_was_castle = False;
game.timeout1 = False;
game.timeout2 = False;
game.last_was_pawn_promotion = False;
game.book_supplied = False;
game.user_supplied = False;
game.supply_valid = False;
set_per_side_options();
} // reset_turn_flags()
////////////////////////////////////////////////////////////////////////////////////////
// Make the next move in the game
void take_turn()
{
// Turn off the LED move indicators
direct_write(DEBUG1_PIN, LOW);
direct_write(DEBUG2_PIN, LOW);
direct_write(DEBUG3_PIN, LOW);
direct_write(DEBUG4_PIN, LOW);
// See if we've hit the move limit and return if so
if (game.move_num >= game.options.move_limit) {
game.state = MOVE_LIMIT;
return;
}
// The best white and black moves
move_t wmove = { -1, -1, MIN_VALUE };
move_t bmove = { -1, -1, MAX_VALUE };
// Reset the flags for this turn
game.stats.start_move_stats();
game.stats.move_stats.depth = 0;
reset_turn_flags();
// Set the alpha and beta edges to the worst case (brute force)
// O(N) based on whose turn it is. Math is so freakin cool..
game.alpha = wmove.value;
game.beta = bmove.value;
Bool const whites_turn = game.turn; // same as (White == game.turn) ? True : False;
move_t move = { -1, -1, whites_turn ? MIN_VALUE : MAX_VALUE };
// See if we have an opening book move
check_book();
if (game.options.shuffle_pieces) {
game.sort_pieces(game.turn);
game.shuffle_pieces(SHUFFLE);
}
// Choose the best moves for both sides
choose_best_moves(wmove, bmove, consider_move);
// Gather the move statistics for this turn
game.stats.stop_move_stats();
printf(Debug1, "\nMove #%d: ", game.move_num + 1);
// If we have a user or a book move that's been validated then use it
if (game.supply_valid) {
(whites_turn ? wmove : bmove) = game.supplied;
game.last_move = game.supplied;
if (game.book_supplied) {
printf(Debug1, "Book: ");
}
if (game.user_supplied) {
printf(Debug1, "User: ");
}
}
move = (whites_turn ? wmove : bmove);
// Display the move that we chose * Before Modifying the Board *
show_move(move);
// Save the number of pieces in the game before we make the move
// in order to see if any pieces were taken
index_t const piece_count = game.piece_count;
// Make the move:
piece_gen_t gen(move, wmove, bmove, consider_move, False);
gen.move = move;
gen.init(board, game);
make_move(gen);
// Set the 'king-in-check' flags
check_kings();
// Check for move repetition
if ((PLAYING == game.state) && add_to_history(gen.move)) {
game.state = whites_turn ? WHITE_3_MOVE_REP : BLACK_3_MOVE_REP;
}
if (game.last_was_en_passant) {
printf(Debug1, " - en passant capture ")
}
if (game.last_was_pawn_promotion) {
printf(Debug1, " - pawn promoted ")
}
if (game.last_was_castle) {
printf(Debug1, " - castling ")
}
printnl(Debug1);