/
GarboChess.cs
2299 lines (1967 loc) · 61.9 KB
/
GarboChess.cs
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
///////////////////////////////////////////////////////////////////////////////
//
// GarboChess.cs
//
//
// © 2008 Microsoft Corporation. All Rights Reserved.
//
// This file is licensed as part of the Silverlight 1.1 SDK, for details look here: http://go.microsoft.com/fwlink/?LinkID=111970&clcid=0x409
//
///////////////////////////////////////////////////////////////////////////////
namespace GarboChess
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
public static class SquareHelper
{
public static int MakeSquare(int row, int column)
{
return (row << 4) | column;
}
public static int GetRow(int square)
{
return (square >> 4);
}
public static int GetColumn(int square)
{
return (square & 0x7);
}
}
public class Pieces
{
public const byte Black = 0;
public const byte White = 8;
public const byte Empty = 0;
public const byte Pawn = 1;
public const byte Knight = 2;
public const byte Bishop = 3;
public const byte Rook = 4;
public const byte Queen = 5;
public const byte King = 6;
public static readonly int[] BishopDeltas = new int[] { -15, -17, 15, 17 };
public static readonly int[] KnightDeltas = new int[] { 31, 33, 14, -14, -31, -33, 18, -18 };
public static readonly int[] RookDeltas = new int[] { -1, +1, -16, +16 };
public static readonly int[] QueenDeltas = new int[] { -1, +1, -15, +15, -17, +17, -16, +16 };
}
public class MoveHelper
{
public const ushort EnPassent = (2 << 12);
public const ushort CastleKing = (4 << 12);
public const ushort CastleQueen = (5 << 12);
public const ushort PromoteKnight = (7 << 12);
public const ushort PromoteBishop = (8 << 12);
public const ushort PromoteRook = (9 << 12);
public const ushort PromoteQueen = (10 << 12);
public const ushort MoveFlags = 0xF000;
public const ushort Invalid = 0xFFFF;
public static int From(ushort move)
{
return (move & 0x7) | ((move << 1) & 0x70);
}
public static int To(ushort move)
{
return ((move >> 6) & 0x7) | ((move >> 5) & 0x70);
}
public static byte Captured(Position position, ushort move)
{
return position.Board[MoveHelper.To(move)];
}
public static ushort GenMove(int from, int to, int flags)
{
int move = ((from & 0x7) | (from & 0x70) >> 1);
move |= (((to & 0x7) | (to & 0x70) >> 1)) << 6;
return (ushort)(move | flags);
}
public static ushort GetMoveFromUCIString(Position position, string uciString)
{
byte start = (byte)((7 - (uciString[1] - '1')) * 0x10 + (uciString[0] - 'a'));
byte end = (byte)((7 - (uciString[3] - '1')) * 0x10 + (uciString[2] - 'a'));
ushort flags = 0;
if (uciString.Length == 5)
{
char c = char.ToLower(uciString[4]);
switch (c)
{
case 'q': flags = MoveHelper.PromoteQueen; break;
case 'n': flags = MoveHelper.PromoteKnight; break;
case 'b': flags = MoveHelper.PromoteBishop; break;
case 'r': flags = MoveHelper.PromoteRook; break;
}
}
foreach (ushort move in position.GenerateValidMoves())
{
if (MoveHelper.From(move) == start &&
MoveHelper.To(move) == end &&
(move & flags) == flags)
{
return move;
}
}
throw new Exception("Didn't find a valid move");
}
public static string GetUCIString(ushort move)
{
string result = "";
int from = MoveHelper.From(move);
int to = MoveHelper.To(move);
result += MoveHelper.CoordToString(from);
result += MoveHelper.CoordToString(to);
result += MoveHelper.PromotionString(move);
return result;
}
public static string GetICCFString(ushort move)
{
int from = MoveHelper.From(move);
int to = MoveHelper.To(move);
from = ((from & 0xF) + 1) * 10 + 7 - ((from & 0xF0) >> 4) + 1;
to = ((to & 0xF) + 1) * 10 + 7 - ((to & 0xF0) >> 4) + 1;
System.Text.StringBuilder result = new System.Text.StringBuilder();
result.AppendFormat("{0}{1}", from, to);
switch (move & MoveFlags)
{
case PromoteBishop:
result.Append("3");
break;
case PromoteKnight:
result.Append("4");
break;
case PromoteQueen:
result.Append("1");
break;
case PromoteRook:
result.Append("2");
break;
}
return result.ToString();
}
public static string GetNiceString(Position position, ushort move)
{
string result = "";
if ((move & MoveHelper.CastleKing) == MoveHelper.CastleKing)
{
result = "O-O";
}
else if ((move & MoveHelper.CastleQueen) == MoveHelper.CastleQueen)
{
result = "O-O-O";
}
else
{
int from = MoveHelper.From(move);
int to = MoveHelper.To(move);
int piece = position.Board[from] & 0x7;
result += " NBRQK "[piece];
result = result.Trim();
Dictionary<int, bool> rows = new Dictionary<int, bool>(), cols = new Dictionary<int, bool>();
foreach (ushort candidate in position.GenerateValidMoves())
{
int cFrom = MoveHelper.From(candidate);
if (MoveHelper.To(candidate) == to &&
(position.Board[cFrom] & 0x7) == (position.Board[from] & 0x7))
{
rows[cFrom & 0xF] = true;
cols[cFrom >> 4] = true;
}
}
bool usedDisambig = false;
if (cols.Keys.Count > 1)
{
if (cols.Keys.Count > 2)
{
// Full notation
usedDisambig = true;
result += MoveHelper.CoordToString(from);
}
else
{
usedDisambig = true;
result += MoveHelper.CoordToString(from)[0];
}
}
else if (rows.Keys.Count > 1)
{
if (rows.Keys.Count > 2)
{
// Full notation
usedDisambig = true;
result += MoveHelper.CoordToString(from);
}
else
{
usedDisambig = true;
result += MoveHelper.CoordToString(from)[1];
}
}
byte captured = MoveHelper.Captured(position, move);
if (captured != Pieces.Empty)
{
if (piece == Pieces.Pawn && !usedDisambig)
{
result += MoveHelper.CoordToString(from)[0];
}
result += "x";
}
result += MoveHelper.CoordToString(to);
result += MoveHelper.PromotionString(move);
}
position.MakeMove(move);
if (position.InCheck) result += "+";
position.UnmakeMove(move);
return result;
}
private static string CoordToString(int coord)
{
string result = "" + (char)('a' + (coord & 0xF));
result += (char)('1' + (7 - (coord >> 4)));
return result;
}
private static string PromotionString(ushort move)
{
switch (move & 0xF000)
{
case MoveHelper.PromoteKnight: return "N";
case MoveHelper.PromoteBishop: return "B";
case MoveHelper.PromoteRook: return "R";
case MoveHelper.PromoteQueen: return "Q";
}
return "";
}
}
public class Searcher
{
public struct HashEntry
{
public const byte HashEntryAlpha = 1;
public const byte HashEntryBeta = 2;
public const byte HashEntryExact = 3;
public ulong hashLock;
public int value;
public ushort move;
private byte depth; // Top two bits of depth are the flags
public byte moveCount;
public HashEntry(ulong hashLock, int value, byte depth, ushort move, byte flags, byte moveCount)
{
Debug.Assert(depth < 64);
Debug.Assert(flags == HashEntryAlpha || flags == HashEntryBeta || flags == HashEntryExact);
this.hashLock = hashLock;
this.value = value;
this.move = move;
this.depth = (byte)(depth | (flags << 6));
this.moveCount = moveCount;
Debug.Assert(this.Depth == depth);
Debug.Assert(this.Flags == flags);
}
public int Depth
{
get { return this.depth & 0x3F; }
}
public int Flags
{
get { return this.depth >> 6; }
}
}
private Position position;
private HashEntry[] hashTable;
private byte hashMoveCount;
private int hashSize;
private ulong hashMask;
private int[][] historyTable;
private ushort[][] moveStack;
private int[][] moveScores;
private int nodeCount;
private int qNodeCount;
private int eval;
private int currentDepth;
private List<ushort> pv;
private bool searchIsValid;
private DateTime startTime;
private int allottedTime = -1;
private int maxPly = 45;
private ushort bestMove;
public Searcher(Position position)
{
this.position = position;
this.hashSize = 1 << 20;
this.hashMask = (ulong)(this.hashSize - 1);
this.hashTable = new HashEntry[this.hashSize];
this.hashMoveCount = 0;
this.historyTable = new int[32][];
for (int i = 0; i < 32; i++)
{
historyTable[i] = new int[128];
}
this.moveStack = new ushort[100][];
this.moveScores = new int[100][];
for (int i = 0; i < this.moveStack.Length; i++)
{
this.moveStack[i] = new ushort[250];
this.moveScores[i] = new int[250];
}
}
public event EventHandler PlyCompleted;
public Position Position
{
get { return this.position; }
}
public int MaxPly
{
get { return this.maxPly; }
set { this.maxPly = value; }
}
public int AllottedTime
{
get { return this.allottedTime; }
set { this.allottedTime = value; }
}
public int NodeCount
{
get { return this.nodeCount; }
}
public int QNodeCount
{
get { return this.qNodeCount; }
}
public int Eval
{
get { return this.eval; }
}
public int CurrentDepth
{
get { return this.currentDepth; }
}
public List<ushort> PV
{
get { return this.pv; }
}
private void PVFromHash(int ply)
{
if (ply == 0) return;
HashEntry hashEntry;
if (this.ProbeHash(out hashEntry))
{
ushort move = hashEntry.move;
if (move == MoveHelper.Invalid) return;
this.pv.Add(move);
this.position.MakeMove(move);
this.PVFromHash(ply - 1);
this.position.UnmakeMove(move);
}
}
public ushort Search()
{
this.bestMove = MoveHelper.Invalid;
int alpha = Evaluation.MinEval;
int beta = Evaluation.MaxEval;
this.nodeCount = 0;
this.qNodeCount = 0;
this.hashMoveCount++;
this.searchIsValid = true;
this.startTime = DateTime.Now;
ushort realBestMove = MoveHelper.Invalid;
for (this.currentDepth = 1; this.currentDepth <= this.maxPly; )
{
Position original = (Position)this.position.Clone();
int value = this.AlphaBeta(this.currentDepth, 0, alpha, beta, true);
if (original.CompareTo(this.position) != 0)
{
throw new Exception("Positions did not compare equal: " + original.CompareTo(this.position));
}
if (!this.searchIsValid)
{
break;
}
if ((value <= alpha || value >= beta) && alpha != Evaluation.MinEval)
{
alpha = Evaluation.MinEval;
beta = Evaluation.MaxEval;
continue;
}
realBestMove = this.bestMove;
this.eval = value;
HashEntry hashEntry;
if (this.ProbeHash(out hashEntry))
{
this.pv = new List<ushort>();
this.PVFromHash(this.currentDepth + 4);
if (this.PlyCompleted != null) this.PlyCompleted(this, EventArgs.Empty);
}
if (value >= Evaluation.MaxEval - 100)
{
break;
}
alpha = value - 250;
beta = value + 250;
this.currentDepth++;
}
this.bestMove = realBestMove;
if (this.bestMove == MoveHelper.Invalid)
{
throw new Exception("Invalid move returned from main search");
}
this.currentDepth--;
return bestMove;
}
private int ScoreMove(ushort move)
{
int score = 0;
int from = MoveHelper.From(move);
int to = MoveHelper.To(move);
byte piece = position.Board[from];
byte captured = position.Board[to];
if (captured != Pieces.Empty)
{
int victim = Evaluation.MaterialTable[captured & 0x7];
int attacker = Evaluation.MaterialTable[piece & 0x7];
if (victim > attacker) score += 5000;
score += victim - attacker / 10;
}
score += this.historyTable[piece >> 3][to];
return score;
}
private int QSearch(int depthSearched, int alpha, int beta)
{
int eval = Evaluation.Evaluate(this.position);
this.qNodeCount++;
if (eval >= beta)
return beta;
if (eval > alpha)
alpha = eval;
ushort[] moves = this.moveStack[depthSearched];
int[] scores = this.moveScores[depthSearched];
int moveCount;
this.position.GenerateAllCaptures(moves, scores, out moveCount);
for (int i = 0; i < moveCount; i++)
{
for (int j = i + 1; j < moveCount; j++)
{
if (scores[j] > scores[i])
{
ushort tmp = moves[i];
moves[i] = moves[j];
moves[j] = tmp;
int stmp = scores[i];
scores[i] = scores[j];
scores[j] = stmp;
}
}
Debug.Assert(MoveHelper.Captured(this.position, moves[i]) != Pieces.Empty ||
MoveHelper.To(moves[i]) == this.position.EpSquare);
if (!this.position.MakeMove(moves[i]))
{
continue;
}
int value;
value = -this.QSearch(depthSearched + 1, -beta, -alpha);
this.position.UnmakeMove(moves[i]);
if (value > eval)
{
if (value >= beta)
return value;
if (value > alpha)
alpha = value;
eval = value;
}
}
return eval;
}
private void StoreHash(int value, byte flags, byte ply, ushort bestMove)
{
HashEntry hashEntry = new HashEntry(this.position.HashKey, value, ply, bestMove, flags, this.hashMoveCount);
uint index = (uint)(this.position.HashKey & this.hashMask) & (~3U);
int besti = -1;
for (int i = 0; i < 4; i++)
{
HashEntry tmp = this.hashTable[index + i];
if (tmp.Depth + tmp.moveCount <= (int)ply + this.hashMoveCount)
{
besti = i;
break;
}
}
if (besti != -1)
{
this.hashTable[index + besti] = hashEntry;
}
}
public bool ProbeHash(out HashEntry hashEntry)
{
uint index = (uint)(this.position.HashKey & this.hashMask) & (~3U);
int i = 0;
do
{
hashEntry = this.hashTable[index + i];
if (hashEntry.hashLock == this.position.HashKey)
{
return true;
}
}
while (++i < 4);
return false;
}
private int AlphaBeta(int ply, int depthSearched, int alpha, int beta, bool allowNull)
{
if (!this.searchIsValid)
{
return alpha;
}
if ((this.nodeCount & 2047) == 2047)
{
TimeSpan time = DateTime.Now - this.startTime;
if (this.allottedTime != -1 && time.TotalMilliseconds > this.allottedTime)
{
this.searchIsValid = false;
return alpha;
}
}
this.nodeCount++;
byte repititionCount = this.position.GetSeenPositionCount(this.position.HashKey);
if (repititionCount >= 2 && depthSearched > 0)
{
// Draw by repititions!
return 0;
}
ushort hashMove = MoveHelper.Invalid;
byte hashFlag = HashEntry.HashEntryAlpha;
HashEntry hashNode;
if (this.ProbeHash(out hashNode))
{
hashMove = hashNode.move;
if (hashNode.Depth >= ply &&
// Don't return a hash score if we've repeated this node at all
repititionCount == 0 &&
// Don't return a hash score from the root ply
depthSearched != 0)
{
if (hashNode.Flags == HashEntry.HashEntryExact)
return this.AdjustMateValue(hashNode.value);
else if (hashNode.Flags == HashEntry.HashEntryAlpha && hashNode.value <= alpha)
return this.AdjustMateValue(hashNode.value);
else if (hashNode.Flags == HashEntry.HashEntryBeta && hashNode.value >= beta)
return this.AdjustMateValue(hashNode.value);
}
}
if (ply <= 0 && !position.InCheck)
{
int value = this.QSearch(depthSearched, alpha, beta);
this.StoreHash(value, value <= alpha ? HashEntry.HashEntryAlpha : (value >= beta ? HashEntry.HashEntryBeta : HashEntry.HashEntryExact), 0, hashMove);
return value;
}
// Don't null move if in check, or we are at the root
if (!position.InCheck &&
ply >= 2 &&
beta != Evaluation.MaxEval &&
allowNull &&
position.MyMaterial > 6000)
{
// Try null move
int r = 1;
if (ply >= 4) r = 2;
else if (ply >= 7) r = 3;
position.MakeNullMove();
int value = -this.AlphaBeta(ply - r - 1, depthSearched + 1, -beta, -beta + 1, false);
position.UnmakeNullMove();
if (!this.searchIsValid)
{
return alpha;
}
if (value >= beta)
{
this.StoreHash(value, HashEntry.HashEntryBeta, (byte)ply, hashMove);
return value;
}
}
if (ply >= 4 && hashMove == MoveHelper.Invalid)
{
// Internal iterative deepening to prime the hash table
this.AlphaBeta(ply / 2, depthSearched + 1, alpha, beta, true);
if (!this.searchIsValid)
{
return alpha;
}
if (this.ProbeHash(out hashNode))
{
hashMove = hashNode.move;
}
}
ushort[] moves = this.moveStack[depthSearched];
int[] scores = this.moveScores[depthSearched];
int moveCount = 1;
bool moveMade = false;
int bestScore = Evaluation.MinEval;
int state = hashMove == MoveHelper.Invalid ? 1 : 0;
while (state < 2)
{
switch (state)
{
case 0:
moves[0] = hashMove;
break;
case 1:
this.position.GenerateAllMoves(moves, out moveCount);
// Move ordering
for (int i = 0; i < moveCount; i++)
{
int score = this.ScoreMove(moves[i]);
if (hashMove == moves[i])
{
score -= 10000000;
}
scores[i] = score;
}
break;
case 2:
moveCount = 0;
break;
}
for (int i = 0; i < moveCount; i++)
{
for (int j = i + 1; j < moveCount; j++)
{
if (scores[j] > scores[i])
{
ushort tmp = moves[i];
moves[i] = moves[j];
moves[j] = tmp;
int stmp = scores[i];
scores[i] = scores[j];
scores[j] = stmp;
}
}
int plyToSearch = ply - 1;
// bool isCapture = MoveHelper.Captured(this.position, moves[i]) != Pieces.Empty;
if (!this.position.MakeMove(moves[i]))
{
continue;
}
if (position.InCheck)
{
// Check extensions
plyToSearch++;
}
else
{
// Futility pruning
/* if (!isCapture)
{
if ((plyToSearch == 0 && -this.position.BaseEval + 4000 < alpha) ||
(plyToSearch == 1 && -this.position.BaseEval + 6000 < alpha))
{
this.position.UnmakeMove(moves[i]);
continue;
}
}*/
}
int value;
if (bestScore == Evaluation.MinEval)
{
value = -this.AlphaBeta(plyToSearch, depthSearched + 1, -beta, -alpha, true);
}
else
{
value = -this.AlphaBeta(plyToSearch, depthSearched + 1, -alpha - 1, -alpha, true);
if (value > alpha && value < beta)
{
value = -this.AlphaBeta(plyToSearch, depthSearched + 1, -beta, -alpha, true);
}
}
value = this.AdjustMateValue(value);
moveMade = true;
this.position.UnmakeMove(moves[i]);
if (!this.searchIsValid)
{
return alpha;
}
if (value > bestScore)
{
if (depthSearched == 0)
{
this.bestMove = moves[i];
}
int from = MoveHelper.From(moves[i]);
int to = MoveHelper.To(moves[i]);
byte piece = position.Board[from];
if (value >= beta)
{
this.historyTable[piece >> 3][to] += ply * 3 + 3;
this.StoreHash(value, HashEntry.HashEntryBeta, (byte)ply, moves[i]);
return value;
}
if (value > alpha)
{
alpha = value;
hashFlag = HashEntry.HashEntryExact;
this.historyTable[piece >> 3][to] += ply;
}
bestScore = value;
hashMove = moves[i];
}
}
state++;
}
if (!moveMade)
{
// If we have no valid moves it's either stalemate or checkmate
if (position.InCheck)
// Checkmate.
return Evaluation.MinEval;
else
// Stalemate
return 0;
}
this.StoreHash(bestScore, hashFlag, (byte)ply, hashMove);
return bestScore;
}
private int AdjustMateValue(int value)
{
if (value > Evaluation.MaxEval - 100)
{
return value - 1;
}
else if (value < Evaluation.MinEval + 100)
{
return value + 1;
}
return value;
}
}
public class Position : IComparable<Position>
{
private struct VectorDeltaEntry
{
public int delta;
public byte[] pieceMask;
}
private static VectorDeltaEntry[] VectorDelta = new VectorDeltaEntry[256];
private static ulong[][] zobrist;
private static ulong[] zobristEpSquare = new ulong[128];
private static ulong[] zobristCastleRights = new ulong[16];
private static ulong zobristBlack;
private static byte[] castleRightsMask = new byte[128]
{
7, 15, 15, 15, 3, 15, 15, 11, /**/ 0,0,0,0,0,0,0,0,
15, 15, 15, 15, 15, 15, 15, 15, /**/ 0,0,0,0,0,0,0,0,
15, 15, 15, 15, 15, 15, 15, 15, /**/ 0,0,0,0,0,0,0,0,
15, 15, 15, 15, 15, 15, 15, 15, /**/ 0,0,0,0,0,0,0,0,
15, 15, 15, 15, 15, 15, 15, 15, /**/ 0,0,0,0,0,0,0,0,
15, 15, 15, 15, 15, 15, 15, 15, /**/ 0,0,0,0,0,0,0,0,
15, 15, 15, 15, 15, 15, 15, 15, /**/ 0,0,0,0,0,0,0,0,
13, 15, 15, 15, 12, 15, 15, 14, /**/ 0,0,0,0,0,0,0,0
};
public byte[] Board = new byte[128];
public byte[] PieceList = new byte[32];
public byte ToMove; // Black or White
private byte castleRights; // Bitmask - 1 = wk, 2 = wq, 4 = bk, 8 = bq
private byte epSquare;
public byte[] SeenPositions;
public ulong[] SeenPositionLock;
// These variables are updated every move
public int BaseEval;
public int MyMaterial;
public int OtherMaterial;
public ulong HashKey;
public bool InCheck;
private static ulong RandomUlong(Random random)
{
byte[] tmp = new byte[8];
random.NextBytes(tmp);
ulong result = 0;
for (int k = 0; k < 8; k++)
{
result |= ((ulong)tmp[k]) << (k * 8);
}
return result;
}
static Position()
{
InitializeVectorDelta();
Random random = new Random();
Position.zobrist = new ulong[128][];
for (int i = 0; i < 128; i++)
{
Position.zobrist[i] = new ulong[16];
Position.zobristEpSquare[i] = Position.RandomUlong(random);
for (int j = 0; j < 16; j++)
{
Position.zobrist[i][j] = Position.RandomUlong(random);
}
}
for (int i = 0; i < 16; i++)
{
Position.zobristCastleRights[i] = Position.RandomUlong(random);
}
Position.zobristBlack = Position.RandomUlong(random);
}
public Position()
{
this.CaptureGenerators = new CaptureGenerator[8];
this.CaptureGenerators[Pieces.Pawn] = this.GeneratePawnCaptures;
this.CaptureGenerators[Pieces.Knight] = this.GenerateKnightKingCaptures;
this.CaptureGenerators[Pieces.Bishop] = this.GenerateSliderCaptures;
this.CaptureGenerators[Pieces.Rook] = this.GenerateSliderCaptures;
this.CaptureGenerators[Pieces.Queen] = this.GenerateSliderCaptures;
this.CaptureGenerators[Pieces.King] = this.GenerateKnightKingCaptures;
}
public byte EpSquare
{
get { return this.epSquare; }
}
public void ResetBoard()
{
this.ToMove = Pieces.White;
this.epSquare = 0xFF;
this.castleRights = 0xF;
for (int i = 0; i < 128; i++) this.Board[i] = Pieces.Empty;
for (int i = 0; i < 8; i++)
{
this.Board[0x10 | i] = (byte)(Pieces.Black | Pieces.Pawn);
this.Board[0x60 | i] = (byte)(Pieces.White | Pieces.Pawn);
}
this.Board[0x00] = Pieces.Black | Pieces.Rook;
this.Board[0x07] = Pieces.Black | Pieces.Rook;
this.Board[0x01] = Pieces.Black | Pieces.Knight;
this.Board[0x06] = Pieces.Black | Pieces.Knight;
this.Board[0x02] = Pieces.Black | Pieces.Bishop;
this.Board[0x05] = Pieces.Black | Pieces.Bishop;
this.Board[0x03] = Pieces.Black | Pieces.Queen;
this.Board[0x04] = Pieces.Black | Pieces.King;
this.Board[0x70] = Pieces.White | Pieces.Rook;
this.Board[0x77] = Pieces.White | Pieces.Rook;
this.Board[0x71] = Pieces.White | Pieces.Knight;
this.Board[0x76] = Pieces.White | Pieces.Knight;
this.Board[0x72] = Pieces.White | Pieces.Bishop;
this.Board[0x75] = Pieces.White | Pieces.Bishop;
this.Board[0x73] = Pieces.White | Pieces.Queen;
this.Board[0x74] = Pieces.White | Pieces.King;
this.InitializePieceList();
this.EndInit();
}
public void InitializeFromFen(string fen)
{
string[] chunks = fen.Split(' ');
for (int i = 0; i < 128; i++) this.Board[i] = Pieces.Empty;
int row = 0, col = 0;
//foreach (char c in chunks[0])
for (int i = 0; i < chunks[0].Length; i++)
{