friendly-chess 0.6.0

friendly neighborhood chess engine
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
use crate::chess::Piece::*;
use crate::errors::*;
use regex::Regex;
use std::collections::HashMap;

const BOARD_SIZE: u8 = 128;
const COLOR_MASK: u8 = 128; // 10000000
const MOVED_MASK: u8 = 64; // 01000000
const EN_PASSANT_SQUARE: u8 = 5; // 00000101

// use | to make a piece black or white
// use & to check if a piece is black or white
pub const WHITE: u8 = 0;
pub const BLACK: u8 = 128;

#[allow(non_snake_case)]
pub mod Piece {
    use crate::chess::*;

    pub type PieceIndex = u8;
    pub type PieceType = u8;

    pub const EMPTY: PieceType = 0; //         00000000
    pub const MOVED_PAWN: PieceType = PAWN | MOVED_MASK; //    10000001
    pub const MOVED_BLACK_PAWN: PieceType = MOVED_PAWN | BLACK; // 11000001
    pub const MOVED_KING: PieceType = KING | MOVED_MASK;

    pub const MOVED_ROOK: PieceType = ROOK | MOVED_MASK; //    10000001
    pub const MOVED_BLACK_ROOK: PieceType = BLACK_ROOK | MOVED_MASK; // 11000001

    pub const PAWN: PieceType = 1; //          00000001
    pub const ROOK: PieceType = 2; //          00000010
    pub const KNIGHT: PieceType = 4; //        00000100
    pub const BISHOP: PieceType = 8; //        00001000
    pub const KING: PieceType = 16; //         00010000
    pub const QUEEN: PieceType = 32; //        00100000

    pub const BLACK_PAWN: PieceType = PAWN | BLACK;
    pub const BLACK_ROOK: PieceType = ROOK | BLACK;
    pub const BLACK_KNIGHT: PieceType = KNIGHT | BLACK;
    pub const BLACK_BISHOP: PieceType = BISHOP | BLACK;
    pub const BLACK_KING: PieceType = KING | BLACK;
    pub const BLACK_QUEEN: PieceType = QUEEN | BLACK;
}

const WHITE_PAWN_DELTAS: [i8; 4] = [-16, -32, -17, -15];
const BLACK_PAWN_DELTAS: [i8; 4] = [16, 32, 17, 15];
const MOVED_WHITE_PAWN_DELTAS: [i8; 4] = [-16, 0, -17, -15];
const MOVED_BLACK_PAWN_DELTAS: [i8; 4] = [16, 0, 17, 15];
const BISHOP_DELTAS: [i8; 4] = [17, 15, -17, -15];
const ROOK_DELTAS: [i8; 4] = [16, -16, 1, -1];
const QUEEN_DELTAS: [i8; 8] = [16, -16, 1, -1, 17, 15, -17, -15];
const KNIGHT_DELTAS: [i8; 8] = [14, 31, 18, 33, -14, -31, -18, -33];
const KING_DELTAS: [i8; 10] = [1, 16, 17, 15, -1, -16, -17, -15, 2, -2];
const MOVED_KING_DELTAS: [i8; 8] = [1, 16, 17, 15, -1, -16, -17, -15];

// why does it have 239 items?
// because of how the indexes of the squares on the real board are laid out due to the fact that
// we have to use some indexes in between to represent the dummy board
/*
    q & b = 40
    q & r = 34
    q & b & k = 56

    queen, bishop, king = 56

    queen, bishop, white pawn, king = 57  = 00111001
    queen, bishop, black pawn, king = 185 = 10111001

    00100000
    00001000
    10000001
    00010000



    queen, bishop can move diagonally to any square = 40 = 00101000

    knight can move in L shape = 4 = 00000100

    queen, rook can move vertically or horizontally to any square = 34 = 00100010

    queen, rook, king = 50 = 00110010

  what is the signifance of the fact that the diff. between each square is unique?
  because they are unique, we can store every single diff. (offset by 119) in an array for lookup.
  This way, we can quickly check if a square can be attacked by just finding the difference between the indexes
*/
#[rustfmt::skip]
const ATTACKS: [u8; 239]= [
   40, 0, 0, 0, 0, 0, 0, 34,  0, 0, 0, 0, 0, 0,40, 0, // Notice how the non-zero numbers are placed very specifically,
   0, 40, 0, 0, 0, 0, 0, 34,  0, 0, 0, 0, 0,40, 0, 0, 
   0, 0, 40, 0, 0, 0, 0, 34,  0, 0, 0, 0,40, 0, 0, 0,
   0, 0, 0, 40, 0, 0, 0, 34,  0, 0, 0,40, 0, 0, 0, 0,
   0, 0, 0, 0, 40, 0, 0, 34,  0, 0,40, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 40, 4, 34,  4,40, 0, 0, 0, 0, 0, 0,
   0, 0, 0, 0, 0, 4, 57, 50, 57, 4, 0, 0, 0, 0, 0, 0,
   34,34,34,34,34,34,50,  0, 50,34,34,34,34,34,34, 0, // Note the zero in the very middle, it basically represents the current piece that is being evaluated for attacks
   0, 0, 0, 0, 0, 4,185, 50,185, 4, 0, 0, 0, 0, 0, 0, // But the piece isn't always in the middle? We can "move" it to the middle by adding 119
   0, 0, 0, 0, 0, 40, 4, 34, 4, 40, 0, 0, 0, 0, 0, 0, // and then applying the difference between two squares to find the index relative to the piece in the middle
   0, 0, 0, 0, 40, 0, 0, 34, 0, 0, 40, 0, 0, 0, 0, 0,
   0, 0, 0, 40, 0, 0, 0, 34, 0, 0, 0, 40, 0, 0, 0, 0,
   0, 0, 40, 0, 0, 0, 0, 34, 0, 0, 0, 0, 40, 0, 0, 0,
   0, 40, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 40, 0, 0,
   40, 0, 0, 0, 0, 0, 0, 34,  0, 0, 0, 0, 0, 0, 40, 
];

#[rustfmt::skip]
const DELTAS: [i8; 239]= [
   -17,  0,  0,  0,  0,  0,  0,-16,  0,  0,  0,  0,  0,  0,-15, 0,
     0,-17,  0,  0,  0,  0,  0,-16,  0,  0,  0,  0,  0,-15,  0, 0,
     0,  0,-17,  0,  0,  0,  0,-16,  0,  0,  0,  0,-15,  0,  0, 0,
     0,  0,  0,-17,  0,  0,  0,-16,  0,  0,  0,-15,  0,  0,  0, 0,
     0,  0,  0,  0,-17,  0,  0,-16,  0,  0,-15,  0,  0,  0,  0, 0,
     0,  0,  0,  0,  0,-17,  0,-16,  0,-15,  0,  0,  0,  0,  0, 0,
     0,  0,  0,  0,  0,  0,-17,-16,-15,  0,  0,  0,  0,  0,  0, 0,
    -1, -1, -1, -1, -1, -1, -1,  0,  1,  1,  1,  1,  1,  1,  1, 0,
     0,  0,  0,  0,  0,  0, 15, 16, 17,  0,  0,  0,  0,  0,  0, 0,
     0,  0,  0,  0,  0, 15,  0, 16,  0, 17,  0,  0,  0,  0,  0, 0,
     0,  0,  0,  0, 15,  0,  0, 16,  0,  0, 17,  0,  0,  0,  0, 0,
     0,  0,  0, 15,  0,  0,  0, 16,  0,  0,  0, 17,  0,  0,  0, 0,
     0,  0, 15,  0,  0,  0,  0, 16,  0,  0,  0,  0, 17,  0,  0, 0,
     0, 15,  0,  0,  0,  0,  0, 16,  0,  0,  0,  0,  0, 17,  0, 0,
    15,  0,  0,  0,  0,  0,  0, 16,  0,  0,  0,  0,  0,  0, 17
 ];

const BOARD_MAP: [u8; 64] = [
    0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23, 32, 33, 34, 35, 36, 37, 38, 39, 48, 49,
    50, 51, 52, 53, 54, 55, 64, 65, 66, 67, 68, 69, 70, 71, 80, 81, 82, 83, 84, 85, 86, 87, 96, 97,
    98, 99, 100, 101, 102, 103, 112, 113, 114, 115, 116, 117, 118, 119,
];

const FILES: [&str; 8] = ["a", "b", "c", "d", "e", "f", "g", "h"];

fn is_number(arg: &str) -> bool {
    arg.chars()
        .collect::<Vec<char>>()
        .iter()
        .all(|&c| c.is_digit(10))
}

#[derive(Debug)]
struct HistoryEntry {
    from_idx: PieceIndex,
    to_idx: PieceIndex,
    from_piece: PieceType,
    to_piece: PieceType,
    kings: King,
    castle: bool,
    capture: bool,
    turn: u8,
    last_turn: u8,
    en_passant_capture: bool,
    en_passant_move: bool,
    promotion: bool,
    half_moves: u8,
    full_moves: u8,
    en_passant_square: Option<String>,
    can_white_king_side_castle: bool,
    can_white_queen_side_castle: bool,
    can_black_king_side_castle: bool,
    can_black_queen_side_castle: bool,
}

#[derive(Debug)]
pub struct Move {
    from: PieceIndex,
    to: PieceIndex,
    // in_check: bool,
    // opponent_in_check: bool,
}

// impl Vec<Move> {}

#[derive(Debug, Clone)]
struct King {
    white: PieceIndex,
    black: PieceIndex,
}
#[derive(Debug)]
pub struct Chess {
    pub board: [PieceType; BOARD_SIZE as usize],

    /// 0 = white, 128 = black
    turn: u8,

    history: Vec<HistoryEntry>,

    /// the kings' indices on the board
    kings: King,

    pub white_captures: Vec<PieceType>,
    pub black_captures: Vec<PieceType>,

    // TODO use bits for these so we only have to keep track of two fields
    pub can_white_king_side_castle: bool,
    pub can_white_queen_side_castle: bool,

    pub can_black_king_side_castle: bool,
    pub can_black_queen_side_castle: bool,

    /// Record the number of each position.
    /// If any position happens 3 times, the game is declared draw
    unique_positions: HashMap<String, u8>,

    half_moves: u8,
    full_moves: u8,

    lastest_en_passant_square: Option<String>,

    last_turn: u8,

    pub captures: u64,
    pub castles: u64,
    pub checks: u64,
    pub promotions: u64,

    pub moves: HashMap<String, u64>,
}

impl Chess {
    pub fn new() -> Self {
        Self {
            board: [EMPTY; BOARD_SIZE as usize],
            turn: WHITE,
            history: vec![],
            kings: King { white: 1, black: 2 },
            white_captures: vec![],
            black_captures: vec![],
            can_white_king_side_castle: true,
            can_white_queen_side_castle: true,
            can_black_king_side_castle: true,
            can_black_queen_side_castle: true,
            unique_positions: HashMap::new(),
            moves: HashMap::new(),

            half_moves: 0,
            full_moves: 0,
            lastest_en_passant_square: None,
            last_turn: WHITE,
            captures: 0,
            castles: 0,
            checks: 0,
            promotions: 0,
        }
    }
    // DISREGARD
    pub fn move_piece(&mut self, move_notation: &str) -> Result<String, MoveError> {
        if move_notation.is_empty() {
            return Err(MoveError::InvalidPieceToMove);
        }

        let parts: Vec<char> = move_notation.chars().collect();
        let move_regex =
            Regex::new(r"^([KQRBN])?([a-h]|[1-8])?(x)?([a-h])([1-8])(=)?([KQRBN])?([+#])?$")
                .unwrap();

        // TODO is there anyway we can reduce the noise?

        // king-side castle
        if move_notation == "O-O" {
            if self.turn == WHITE {
                if !self.can_white_king_side_castle {
                    return Err(MoveError::IllegalKingSideCastle);
                }

                let legal_moves = self.inner_moves(self.kings.white);

                // let m = Move {
                //     from: self.kings.white,
                //     to: 118,
                //     opponent_in_check: false,
                // };

                if legal_moves.contains(&118) {
                    self.inner_move_piece(self.kings.white, 118);
                } else {
                    return Err(MoveError::IllegalKingSideCastle);
                }
            } else {
                if !self.can_black_king_side_castle {
                    return Err(MoveError::IllegalKingSideCastle);
                }

                let legal_moves = self.inner_moves(self.kings.black);

                if legal_moves.contains(&6) {
                    self.inner_move_piece(self.kings.black, 6);
                } else {
                    return Err(MoveError::IllegalKingSideCastle);
                }
            }
        // queen side castle
        } else if move_notation == "O-O-O" {
            if self.turn == WHITE {
                if !self.can_white_queen_side_castle {
                    return Err(MoveError::IllegalQueenSideCastle);
                }

                let legal_moves = self.inner_moves(self.kings.white);

                if legal_moves.contains(&114) {
                    self.inner_move_piece(self.kings.white, 114);
                } else {
                    return Err(MoveError::IllegalQueenSideCastle);
                }
            } else {
                if !self.can_black_queen_side_castle {
                    return Err(MoveError::IllegalQueenSideCastle);
                }

                let legal_moves = self.inner_moves(self.kings.black);

                if legal_moves.contains(&2) {
                    self.inner_move_piece(self.kings.black, 2);
                } else {
                    return Err(MoveError::IllegalQueenSideCastle);
                }
            }
        } else {
            // TODO error for this
            let captures = move_regex
                .captures(move_notation)
                .expect("Invalid move notation");

            let piece_identifer = captures.get(2).map_or("", |m| m.as_str());
            let is_capture = captures.get(3).map_or(false, |_| true);
            let to_file = captures.get(4).map_or("", |m| m.as_str());
            let to_rank = captures.get(5).map_or("", |m| m.as_str());
            let is_promotion = captures.get(6).map_or(false, |_| true);
            let promotion_piece = captures.get(7).map_or("", |m| m.as_str());

            let mut from_idx: Option<PieceIndex> = None;
            let idx = self
                .convert_algebraic_notation_to_index(format!("{}{}", to_file, to_rank).as_str());

            let to_idx = BOARD_MAP[idx as usize];
            let target_piece = self.get(to_idx);

            // en passant only if piece is pawn
            if is_capture
                && ((self.is_friendly(target_piece) && target_piece != EN_PASSANT_SQUARE)
                    || target_piece == EMPTY)
            {
                return Err(MoveError::IllegalCapture);
            }

            let mut target_file = None;
            let mut target_rank = None;

            if !piece_identifer.is_empty() {
                if is_number(piece_identifer) {
                    target_rank = Some(piece_identifer.parse::<u8>().unwrap());
                } else {
                    target_file =
                        Some(FILES.iter().position(|f| f.eq(&piece_identifer)).unwrap() as u8);
                }
            }

            if parts[0].is_uppercase() {
                // [a-h][file-rank-identifier][a-h][file]
                // [a-h]x[a-h][file]
                // [a-h][file-rank-identifier]x[a-h][file]

                let mut count = 0;
                let target_type = match parts[0] {
                    'K' => KING,
                    'Q' => QUEEN,
                    'R' => ROOK,
                    'B' => BISHOP,
                    'N' => KNIGHT,
                    _ => {
                        return Err(MoveError::UnknownPiece);
                    }
                };

                for idx in 0..BOARD_SIZE {
                    if !self.is_on_board(idx) {
                        continue;
                    }

                    let piece = self.get(idx);
                    let piece_type = self.get_type(piece);

                    if piece_type == target_type && self.is_friendly(piece) {
                        count += 1;

                        // TODO use .moves instead of .inner_moves so we don't have to convert the index
                        let _moves = self.inner_moves(idx);
                        let file = idx & 7;
                        let rank = 8 - ((idx >> 4) + 1) + 1;

                        if !_moves.contains(&to_idx) {
                            continue;
                        }

                        if let Some(target_file) = target_file {
                            if file == target_file {
                                if count >= 2 && _moves.contains(&to_idx) {
                                    return Err(MoveError::AmbiguousMoveNotation);
                                }
                                from_idx = Some(idx);
                            }
                        } else if let Some(target_rank) = target_rank {
                            if rank == target_rank {
                                if count >= 2 && _moves.contains(&to_idx) {
                                    return Err(MoveError::AmbiguousMoveNotation);
                                }
                                from_idx = Some(idx);
                            }
                        } else {
                            if count >= 2 && _moves.contains(&to_idx) && from_idx != None {
                                // if the second piece can also move to that location, then we panic
                                // because we don't know which piece to move
                                return Err(MoveError::AmbiguousMoveNotation);
                            }

                            from_idx = Some(idx);
                        }
                    }
                }

                if let Some(from_idx) = from_idx {
                    self.inner_move_piece(from_idx, to_idx)
                } else {
                    println!("{} {} {:?}", move_notation, self.get_fen(), self.board);
                    return Err(MoveError::InvalidPieceToMove);
                }
            } else {
                let rank = 8 - ((to_idx >> 4) + 1) + 1;

                if is_promotion && (rank > 1 && rank < 8) {
                    return Err(MoveError::InvalidPromotion);
                }

                if rank == 0 || rank == 8 {
                    if !is_promotion {
                        return Err(MoveError::InvalidPromotion);
                    }

                    if is_promotion {
                        if promotion_piece.is_empty() {
                            return Err(MoveError::InvalidPromotion);
                        }
                    }
                }

                // pawn move
                for idx in 0..BOARD_SIZE {
                    if !self.is_on_board(idx) {
                        continue;
                    }

                    let piece = self.get(idx);
                    let piece_type = self.get_type(piece);

                    if piece_type == PAWN && self.is_friendly(piece) {
                        let _moves = self.inner_moves(idx);

                        if !_moves.contains(&to_idx) {
                            // println!("{} {:?}", idx, _moves);
                            continue;
                        }
                        from_idx = Some(idx);
                    }
                }

                if let Some(from_idx) = from_idx {
                    self.inner_move_piece(from_idx, to_idx);

                    if is_promotion {
                        let piece = match promotion_piece {
                            "K" => KING,
                            "Q" => QUEEN,
                            "R" => ROOK,
                            "B" => BISHOP,
                            "N" => KNIGHT,
                            _ => return Err(MoveError::InvalidPromotion),
                        };

                        self.set(piece, to_idx);
                    }
                } else {
                    return Err(MoveError::InvalidPieceToMove);
                }
            }
        }

        if self.turn == BLACK {
            self.full_moves += 1;
        }

        let fen = self.get_fen();
        let position = fen.split(" ").collect::<Vec<&str>>()[0];

        // *self
        //     .unique_positions
        //     .entry(position.to_string())
        //     .or_insert(0) += 1;
        self.update_castling_rights();
        self.change_turn();
        // if self.is_draw() {
        //     println!("game drawn");
        // }

        let mut new_notation = move_notation.to_string();

        // if self.is_checkmate() {
        //     println!("game over by checkmate");
        //     new_notation.push('#');
        // } else if self.in_check() {
        //     new_notation.push('+');
        // }

        Ok(new_notation)
    }

    pub fn inner_move_piece(&mut self, from_idx: PieceIndex, to_idx: PieceIndex) {
        if self.is_on_board(to_idx) {
            let mut piece = self.get(from_idx);

            if piece == EMPTY || piece == EN_PASSANT_SQUARE {
                panic!("can't move an empty square");
            }

            let to_piece = self.get(to_idx);
            let piece_type = self.remove_color(piece);

            let mut history_entry = HistoryEntry {
                from_idx,
                to_idx,
                from_piece: self.get(from_idx),
                to_piece,
                kings: self.kings.clone(),
                castle: false,
                capture: false,
                en_passant_capture: false,
                en_passant_move: false,
                promotion: false,
                turn: self.turn,
                last_turn: self.last_turn,
                half_moves: self.half_moves,
                full_moves: self.full_moves,
                en_passant_square: self.lastest_en_passant_square.clone(),
                can_white_king_side_castle: self.can_white_king_side_castle,
                can_white_queen_side_castle: self.can_white_queen_side_castle,
                can_black_king_side_castle: self.can_black_king_side_castle,
                can_black_queen_side_castle: self.can_black_queen_side_castle,
            };

            if to_piece != EN_PASSANT_SQUARE {
                self.clear_latest_en_passant_square();
            }

            if piece_type == PAWN {
                // set the pawn to moved
                piece = piece | MOVED_MASK;
                // if it has moved 2 squares, update en passant square
                if to_idx.abs_diff(from_idx) == 32 {
                    // make the square behind the pawn an en passant square
                    let idx = match to_idx {
                        i if i > from_idx => from_idx + 16,
                        i if i < from_idx => from_idx - 16,
                        _ => panic!("could not calculate en passant squares"),
                    };

                    self.set(EN_PASSANT_SQUARE, idx);
                    self.lastest_en_passant_square =
                        Some(self.convert_index_algebraic_notation(idx));
                    history_entry.en_passant_move = true;
                }

                self.reset_half_moves();
            } else if piece_type == MOVED_PAWN {
                if to_piece == EN_PASSANT_SQUARE {
                    if self.turn == BLACK {
                        self.capture(self.get(to_idx - 16));
                        self.set(Piece::EMPTY, to_idx - 16);
                    } else {
                        self.capture(self.get(to_idx + 16));
                        self.set(Piece::EMPTY, to_idx + 16);
                    }

                    self.captures += 1;

                    history_entry.capture = true;
                    history_entry.en_passant_capture = true;
                    self.reset_half_moves();
                }

                let rank = 8 - ((to_idx >> 4) + 1) + 1;

                if rank == 1 || rank == 8 {
                    history_entry.promotion = true;
                }
                self.reset_half_moves();
                self.lastest_en_passant_square = None;
            } else if piece_type == KING {
                self.update_kings_position(to_idx);

                piece = piece | MOVED_MASK;

                let (can_king_side_castle, can_queen_side_castle) = self.get_castling_rights();

                if can_king_side_castle || can_queen_side_castle {
                    if self.is_king_side_castling(from_idx, to_idx) && can_king_side_castle {
                        self.set(Piece::ROOK | self.turn | MOVED_MASK, to_idx - 1);
                        self.set(Piece::EMPTY, to_idx + 1);
                        history_entry.castle = true;
                        self.castles += 1;
                    } else if self.is_queen_side_castling(from_idx, to_idx) && can_queen_side_castle
                    {
                        self.set(Piece::ROOK | self.turn | MOVED_MASK, to_idx + 1);
                        self.set(Piece::EMPTY, to_idx - 2);
                        history_entry.castle = true;
                        self.castles += 1;
                    }
                }
            } else if piece_type == MOVED_KING {
                self.update_kings_position(to_idx);
            } else if piece_type == ROOK {
                piece = piece | MOVED_MASK;
            } else {
                self.half_moves += 1;
            }

            if self.is_occupied(to_idx) {
                if !self.is_friendly(to_piece) {
                    self.capture(to_piece);
                    history_entry.capture = true;
                    self.reset_half_moves();
                    self.captures += 1;
                }
            }

            // // check if we are capturing a piece
            // if to_piece != EMPTY {
            //     if to_piece != EN_PASSANT_SQUARE &&
            // }

            if to_piece == EN_PASSANT_SQUARE {
                self.lastest_en_passant_square = None;
            }

            self.set(piece, to_idx);
            self.set(Piece::EMPTY, from_idx);

            self.history.push(history_entry);
        } else {
            // panic!("illegal move!")
        }
    }

    /// Return the piece on the square
    fn get(&self, square_idx: PieceIndex) -> PieceIndex {
        if !self.is_on_board(square_idx) || square_idx > 150 {
            println!("lmao");
            panic!("square out of bound");
        }

        self.board[square_idx as usize]
    }

    /// Put a piece on a square
    pub fn set(&mut self, piece: PieceType, square_idx: PieceIndex) {
        if !self.is_on_board(square_idx) || square_idx > 150 {
            panic!("square out of bound");
        }

        if piece == KING {
            self.kings.white = square_idx;
        }

        if piece == BLACK_KING {
            self.kings.black = square_idx;
        }

        self.board[square_idx as usize] = piece;

        // self.update_castling_rights();
    }

    // DISREGARD
    pub fn moves(&mut self, square: &str) -> Vec<String> {
        let square_idx = BOARD_MAP[self.convert_algebraic_notation_to_index(square) as usize];

        if !self.is_on_board(square_idx) {
            panic!("invalid square");
        }

        let moves = self.inner_moves(square_idx);

        let piece = self.get(square_idx);
        let piece_type = self.get_type(piece);

        let prefix = match piece_type {
            KING => "K",
            QUEEN => "Q",
            ROOK => "R",
            BISHOP => "B",
            KNIGHT => "N",
            PAWN => "",
            _ => {
                panic!("invalid piece")
            }
        };

        let mut a: Vec<String> = moves
            .iter()
            .map(|m| {
                // TODO: use a Move struct to make our lives easier

                if *m == 118 && piece_type == KING {
                    return String::from("O-O");
                } else if *m == 114 && piece_type == KING {
                    return String::from("O-O-O");
                } else {
                    let to = self.get(*m);
                    let rank = 8 - ((*m >> 4) + 1) + 1;

                    if (rank == 1 || rank == 8) && piece_type == PAWN {
                        return m.to_string();
                        // return format!(
                        //     "{}={}",
                        //     FILES[file as usize],
                        //     self.convert_index_algebraic_notation(*m)
                        // );
                    }

                    if to == EN_PASSANT_SQUARE && piece_type == PAWN {
                        let file = square_idx & 7;

                        return format!(
                            "{}x{}",
                            FILES[file as usize],
                            self.convert_index_algebraic_notation(*m)
                        );
                    }

                    if self.is_occupied(*m) && !self.is_friendly(to) {
                        return format!("{}x{}", prefix, self.convert_index_algebraic_notation(*m));
                    }

                    return format!("{}{}", prefix, self.convert_index_algebraic_notation(*m));
                }
            })
            .collect();

        let mut t_idx: Option<usize> = None;

        let mut temp_a = a.clone();

        // for (i, b) in a.iter().enumerate() {
        //     if is_number(b) {
        //         let idx: u8 = b.parse().unwrap();

        //         let rank = 8 - ((idx >> 4) + 1) + 1;

        //         if (rank == 1 || rank == 8) && piece_type == PAWN {
        //             temp_a.push(format!(
        //                 "{}={}",
        //                 self.convert_index_algebraic_notation(idx),
        //                 "Q"
        //             ));

        //             temp_a.push(format!(
        //                 "{}={}",
        //                 self.convert_index_algebraic_notation(idx),
        //                 "R"
        //             ));

        //             temp_a.push(format!(
        //                 "{}={}",
        //                 self.convert_index_algebraic_notation(idx),
        //                 "N"
        //             ));
        //             temp_a.push(format!(
        //                 "{}={}",
        //                 self.convert_index_algebraic_notation(idx),
        //                 "B"
        //             ));
        //         }

        //         t_idx = Some(i as usize);
        //     }
        // }

        // if let Some(t_idx) = t_idx {
        //     temp_a.remove(t_idx);
        // }

        a
    }

    pub fn inner_moves(&mut self, square_idx: PieceIndex) -> Vec<PieceIndex> {
        let piece = self.get(square_idx);

        if !self.is_friendly(piece) {
            panic!("can't generate inner_moves for enemy piece, set the turn correctly.");
        }

        if piece == EMPTY || piece == EN_PASSANT_SQUARE {
            panic!("can't generate moves for empty squares")
        }

        let inner_moves = match self.remove_color(piece) {
            PAWN => self.generate_pawn_moves(square_idx),
            MOVED_PAWN => self.generate_pawn_moves(square_idx),
            BISHOP => self.generate_sliding_moves(square_idx, BISHOP_DELTAS.to_vec()),
            ROOK => self.generate_sliding_moves(square_idx, ROOK_DELTAS.to_vec()),
            QUEEN => self.generate_sliding_moves(square_idx, QUEEN_DELTAS.to_vec()),
            KNIGHT => self.generate_knight_moves(square_idx),
            KING => self.generate_king_moves(square_idx, KING_DELTAS.to_vec()),
            MOVED_KING => self.generate_king_moves(square_idx, MOVED_KING_DELTAS.to_vec()),
            MOVED_ROOK => self.generate_sliding_moves(square_idx, ROOK_DELTAS.to_vec()),
            _ => vec![],
        };

        let mut legal_moves: Vec<PieceIndex> = vec![];

        for idx in inner_moves {
            let to_idx = idx;
            // play the move
            self.inner_move_piece(square_idx, to_idx as u8);

            if !self.in_check() {
                // println!("{:?}", self.board);
                legal_moves.push(to_idx);
                // legal_moves.push(Move {
                //     // Optimize this later?
                //     // opponent_in_check: self.opponent_in_check(),
                //     from: square_idx,
                //     to: to_idx,
                // });
            }

            // revert the move
            self.undo();
        }

        legal_moves
    }

    pub fn generate_pawn_moves(&mut self, square_idx: PieceIndex) -> Vec<u8> {
        let mut inner_moves = vec![];

        let pawn = self.get(square_idx);

        let deltas = match pawn {
            PAWN => WHITE_PAWN_DELTAS,
            BLACK_PAWN => BLACK_PAWN_DELTAS,
            MOVED_PAWN => MOVED_WHITE_PAWN_DELTAS,
            MOVED_BLACK_PAWN => MOVED_BLACK_PAWN_DELTAS,
            _ => panic!("piece is not a pawn"),
        };

        let mut can_move_forward = true;

        for delta in deltas {
            if delta == 0 {
                continue;
            }

            let destination_idx = square_idx as i16 + delta as i16;
            let destination_idx = destination_idx as u8;

            if self.is_on_board(destination_idx) {
                let piece = self.get(destination_idx);

                let rank = 8 - ((destination_idx as u8 >> 4) + 1) + 1;

                if rank == 1 || rank == 8 {
                    // println!("hi");
                }
                // is it a diagonal move?
                if delta % 2 != 0 {
                    if self.is_occupied(destination_idx) {
                        let is_enemy = !self.is_friendly(piece);

                        if is_enemy {
                            inner_moves.push(destination_idx);
                        }
                    } else if piece == EN_PASSANT_SQUARE {
                        if self.turn == WHITE {
                            let below = self.get(destination_idx + 16);
                            if !self.is_friendly(below) && self.get_type(below) == PAWN {
                                inner_moves.push(destination_idx);
                            }
                        } else {
                            let above = self.get(destination_idx - 16);
                            if !self.is_friendly(above) && self.get_type(above) == PAWN {
                                inner_moves.push(destination_idx);
                            }
                        }
                    }

                    // let rank = 8 - ((destination_idx as u8 >> 4) + 1) + 1;

                    // if rank == 1 || rank == 8 {
                    //     inner_moves.push(destination_idx);
                    //     inner_moves.push(destination_idx);
                    //     inner_moves.push(destination_idx);
                    // }
                } else {
                    // pawn can only forward if it is not blocked by any piece
                    if self.is_occupied(destination_idx) {
                        can_move_forward = false;
                    }

                    if can_move_forward {
                        inner_moves.push(destination_idx);
                    }
                }
            }
        }

        inner_moves
    }

    pub fn generate_king_moves(&mut self, square_idx: PieceIndex, deltas: Vec<i8>) -> Vec<u8> {
        let mut inner_moves: Vec<PieceIndex> = vec![];

        for delta in deltas {
            // convert to i16 to prevent overflow
            let destination_idx = (square_idx as i16 + delta as i16) as PieceIndex;

            if self.is_on_board(destination_idx) {
                let piece = self.get(destination_idx);
                let is_friendly = self.is_friendly(piece);

                if self.is_occupied(destination_idx) {
                    let is_castling_move = self.is_king_side_castling(square_idx, destination_idx)
                        || self.is_queen_side_castling(square_idx, destination_idx);

                    // we can only castle if the square is empty
                    if is_castling_move {
                        continue;
                    }

                    // if enemy piece, we can capture it
                    if !is_friendly || piece == EN_PASSANT_SQUARE {
                        inner_moves.push(destination_idx);
                    }
                } else {
                    let is_king_side_castling =
                        self.is_king_side_castling(square_idx, destination_idx);

                    let is_queen_side_castling =
                        self.is_queen_side_castling(square_idx, destination_idx);

                    let (can_king_side_castle, can_queen_side_castle) = self.get_castling_rights();

                    // if try to castle without castling rights, skip

                    if is_king_side_castling && !can_king_side_castle {
                        continue;
                    }

                    if is_queen_side_castling && !can_queen_side_castle {
                        continue;
                    }

                    if is_king_side_castling || is_queen_side_castling {
                        let rook_idx: PieceIndex = if is_king_side_castling {
                            destination_idx + 1
                        } else if is_queen_side_castling {
                            destination_idx - 2
                        } else {
                            panic!("failed to castle")
                        };

                        let piece = self.get(rook_idx);
                        let mut is_checked = false;
                        let mut is_blocked = false;
                        let mut idx = square_idx;
                        let mut idx_2 = square_idx;

                        let block_range = if is_king_side_castling {
                            0..3
                        } else if is_queen_side_castling {
                            0..4
                        } else {
                            0..2
                        };

                        let attack_range = if is_king_side_castling {
                            0..3
                        } else if is_queen_side_castling {
                            0..3
                        } else {
                            0..2
                        };

                        for _ in block_range {
                            // let is_attacked = self.is_attacked(idx);

                            // if is_attacked {
                            //     is_checked = true;
                            // }

                            if idx_2 != square_idx && self.get(idx_2) != EMPTY {
                                is_blocked = true;
                            }

                            if is_king_side_castling {
                                idx_2 += 1;
                            }

                            if is_queen_side_castling {
                                idx_2 -= 1;
                            }
                        }

                        for _ in attack_range {
                            let is_attacked = self.is_attacked(idx);

                            if is_attacked {
                                is_checked = true;
                            }

                            if is_king_side_castling {
                                idx += 1;
                            }

                            if is_queen_side_castling {
                                idx -= 1;
                            }
                        }

                        if piece != EMPTY
                            && self.remove_color(piece) == ROOK
                            && self.is_friendly(piece)
                            && !is_checked
                            && !is_blocked
                        {
                            inner_moves.push(destination_idx);
                        }
                        // self.update_castling_rights();
                    } else {
                        inner_moves.push(destination_idx);
                    }
                }
            }
        }

        inner_moves
    }

    pub fn generate_knight_moves(&mut self, square_idx: PieceIndex) -> Vec<u8> {
        let mut inner_moves: Vec<PieceIndex> = vec![];

        for delta in KNIGHT_DELTAS {
            // convert to i16 to prevent overflow
            let destination_idx = square_idx as i16 + delta as i16;

            if self.is_on_board(destination_idx as u8) {
                let piece = self.get(destination_idx as PieceIndex);

                if self.is_occupied(destination_idx as PieceIndex) {
                    if self.is_friendly(piece) {
                        continue;
                    }
                }

                inner_moves.push(destination_idx as PieceIndex);
            }
        }

        inner_moves
    }

    pub fn generate_sliding_moves(&mut self, square_idx: PieceIndex, deltas: Vec<i8>) -> Vec<u8> {
        let mut inner_moves: Vec<PieceIndex> = vec![];

        for delta in deltas {
            // convert to i16 to prevent overflow
            let mut destination_idx = square_idx as i16 + delta as i16;

            while self.is_on_board(destination_idx as PieceIndex) {
                let piece = self.get(destination_idx as PieceIndex);

                if self.is_occupied(destination_idx as PieceIndex) {
                    // if we encounter a friendly piece, we can't move there
                    if self.is_friendly(piece) {
                        break;
                    } else {
                        // if we encounter an enemy piece, we can capture it but cannot move further
                        inner_moves.push(destination_idx as PieceIndex);
                        break;
                    }
                }

                inner_moves.push(destination_idx as PieceIndex);

                // if the destination square is on the board, we keep searching in that direction until we go off the board
                destination_idx += delta as i16;
            }
        }

        inner_moves
    }

    // TODO if this function causes any bugs down the road, just rewrite it by
    // saving a FEN string of the board everytime a move is made and use the previous FEN when undoing inner_moves
    pub fn undo(&mut self) {
        if let Some(old) = self.history.pop() {
            if old.castle {
                let HistoryEntry {
                    to_idx, from_idx, ..
                } = old;

                // TODO: just hardcode the castle squares
                let king_side = self.is_king_side_castling(from_idx, to_idx);
                let queen_side = self.is_queen_side_castling(from_idx, to_idx);

                if king_side {
                    self.set(ROOK | old.turn, to_idx + 1);
                    self.set(EMPTY, from_idx + 1);
                } else if queen_side {
                    self.set(ROOK | old.turn, to_idx - 2);
                    self.set(EMPTY, from_idx - 1);
                }
            }

            if old.capture {
                if old.turn == WHITE {
                    self.white_captures.pop();
                } else {
                    self.black_captures.pop();
                }
            }

            if old.en_passant_capture {
                let from_idx = old.from_idx;

                let idx = match old.to_idx {
                    i if i < from_idx => old.to_idx + 16,
                    i if i > from_idx => old.to_idx - 16,
                    _ => panic!("could not calculate en passant squares"),
                };

                self.set(EN_PASSANT_SQUARE, idx);

                let piece = old.from_piece;

                if piece == MOVED_PAWN {
                    self.set(MOVED_BLACK_PAWN, old.to_idx + 16);
                } else if piece == MOVED_BLACK_PAWN {
                    self.set(MOVED_PAWN, old.to_idx - 16);
                }
            }

            if old.en_passant_move {
                let from_idx = old.from_idx;

                let idx = match old.to_idx {
                    i if i < from_idx => old.to_idx + 16,
                    i if i > from_idx => old.to_idx - 16,
                    _ => panic!("could not calculate en passant squares"),
                };

                self.set(EMPTY, idx);
            }

            self.can_black_king_side_castle = old.can_black_king_side_castle;
            self.can_black_queen_side_castle = old.can_black_queen_side_castle;
            self.can_white_king_side_castle = old.can_white_king_side_castle;
            self.can_white_queen_side_castle = old.can_white_queen_side_castle;

            self.half_moves = old.half_moves;
            self.full_moves = old.full_moves;

            self.turn = old.turn;
            self.last_turn = old.last_turn;

            self.kings = old.kings.clone();

            // self.update_castling_rights();

            self.lastest_en_passant_square = old.en_passant_square;
            if let Some(ep_square) = &self.lastest_en_passant_square {
                let ep_idx = BOARD_MAP
                    [self.convert_algebraic_notation_to_index(ep_square.as_str()) as usize];

                if self.get(ep_idx) == EMPTY {
                    self.set(EN_PASSANT_SQUARE, ep_idx);
                }
            }

            // move the pieces back to its original square
            self.set(old.from_piece, old.from_idx);
            self.set(old.to_piece, old.to_idx);
        }
    }

    /*
        black pieces = lowercase
        white = uppercase
        empty square = number

    */
    pub fn get_fen(&self) -> String {
        let mut fen = String::from("");

        let turn = self.turn();
        let mut castling_rights = String::new();
        let en_passant_square = if let Some(sq) = self.lastest_en_passant_square.clone() {
            sq
        } else {
            "-".to_string()
        };

        let half_moves = self.half_moves;
        let full_moves = self.full_moves;

        if self.can_white_king_side_castle {
            castling_rights.push_str("K");
        }

        if self.can_white_queen_side_castle {
            castling_rights.push_str("Q");
        }

        if self.can_black_king_side_castle {
            castling_rights.push_str("k");
        }

        if self.can_black_queen_side_castle {
            castling_rights.push_str("q")
        }

        if castling_rights.is_empty() {
            castling_rights.push_str("-");
        }

        let mut empty_square: u8 = 0;
        for idx in 0..BOARD_SIZE {
            if !self.is_on_board(idx) {
                continue;
            }

            let piece = self.get(idx);

            if self.is_occupied(idx) {
                if empty_square != 0 {
                    fen.push_str(empty_square.to_string().as_str());
                    empty_square = 0;
                }

                let piece_type = self.get_type(piece);

                if self.get_color(piece) == WHITE {
                    match piece_type {
                        PAWN => fen.push_str("P"),
                        ROOK => fen.push_str("R"),
                        KNIGHT => fen.push_str("N"),
                        BISHOP => fen.push_str("B"),
                        QUEEN => fen.push_str("Q"),
                        KING => fen.push_str("K"),
                        _ => panic!("error generating FEN"),
                    }
                } else {
                    match piece_type {
                        PAWN => fen.push_str("p"),
                        ROOK => fen.push_str("r"),
                        KNIGHT => fen.push_str("n"),
                        BISHOP => fen.push_str("b"),
                        QUEEN => fen.push_str("q"),
                        KING => fen.push_str("k"),
                        _ => panic!("error generating FEN"),
                    }
                }
            } else {
                empty_square += 1;
            }

            if (idx + 1) % 8 == 0 {
                if empty_square != 0 {
                    fen.push_str(empty_square.to_string().as_str());
                    empty_square = 0;
                }

                // if it is the last rank on board, no need to separate with /
                if idx != 119 {
                    fen.push('/');
                }
            }
        }

        vec![
            fen,
            turn.to_string(),
            castling_rights,
            en_passant_square,
            half_moves.to_string(),
            full_moves.to_string(),
        ]
        .join(" ")
    }

    pub fn load_fen(&mut self, fen: String) {
        let fen_parts: Vec<&str> = fen.split(" ").collect();

        let ranks: Vec<&str> = fen_parts[0].split("/").collect();

        let mut idx: usize = 0;
        for rank in ranks {
            for piece in rank.chars() {
                match piece {
                    'p' => {
                        let rank = 8 - ((BOARD_MAP[idx] >> 4) + 1) + 1;

                        if rank != 7 {
                            self.set(MOVED_BLACK_PAWN, BOARD_MAP[idx])
                        } else {
                            self.set(BLACK_PAWN, BOARD_MAP[idx])
                        }
                    }
                    'r' => self.set(BLACK_ROOK, BOARD_MAP[idx]),
                    'n' => self.set(BLACK_KNIGHT, BOARD_MAP[idx]),
                    'b' => self.set(BLACK_BISHOP, BOARD_MAP[idx]),
                    'q' => self.set(BLACK_QUEEN, BOARD_MAP[idx]),
                    'k' => self.set(BLACK_KING, BOARD_MAP[idx]),
                    'P' => {
                        let rank = 8 - ((BOARD_MAP[idx] >> 4) + 1) + 1;

                        if rank != 2 {
                            self.set(MOVED_PAWN, BOARD_MAP[idx])
                        } else {
                            self.set(PAWN, BOARD_MAP[idx])
                        }
                    }
                    'R' => self.set(ROOK, BOARD_MAP[idx]),
                    'N' => self.set(KNIGHT, BOARD_MAP[idx]),
                    'B' => self.set(BISHOP, BOARD_MAP[idx]),
                    'Q' => self.set(QUEEN, BOARD_MAP[idx]),
                    'K' => self.set(KING, BOARD_MAP[idx]),
                    '1'..='8' => idx += piece.to_digit(10).unwrap() as usize - 1,
                    _ => panic!("can't load fen pieces"),
                }

                idx += 1;
            }
        }

        // set turn
        match fen_parts[1] {
            "w" => self.set_turn(WHITE),
            "b" => self.set_turn(BLACK),
            _ => panic!("can't load fen turn"),
        }

        // castling rights
        for castling_right in fen_parts[2].chars() {
            match castling_right {
                'K' => {
                    self.can_white_king_side_castle = true;
                }
                'Q' => {
                    self.can_white_queen_side_castle = true;
                }
                'k' => {
                    self.can_black_king_side_castle = true;
                }
                'q' => {
                    self.can_black_queen_side_castle = true;
                }

                '-' => {
                    self.can_white_king_side_castle = false;
                    self.can_white_queen_side_castle = false;
                    self.can_black_king_side_castle = false;
                    self.can_black_queen_side_castle = false;
                }
                _ => panic!("cant load fen castling rights"),
            }
        }

        // en passant square
        let square = fen_parts[3];

        match square {
            // no en passant square
            "-" => {
                self.lastest_en_passant_square = None;
            }
            _ => {
                self.lastest_en_passant_square = Some(square.to_string());
                let idx = self.convert_algebraic_notation_to_index(square) as usize;

                self.set(EN_PASSANT_SQUARE, BOARD_MAP[idx]);
            }
        }

        self.half_moves = fen_parts[4].parse().unwrap();
        self.full_moves = fen_parts[5].parse().unwrap();

        *self
            .unique_positions
            .entry(fen_parts[0].to_string())
            .or_insert(0) += 1;
    }

    /// Return true or false if the color to move is in check
    pub fn in_check(&self) -> bool {
        let king_idx = match self.turn {
            WHITE => self.kings.white,
            BLACK => self.kings.black,
            _ => panic!("Turn cannot be determined when checking if king is attacked"),
        };

        return self.is_attacked(king_idx);
    }

    // DISREGARD
    pub fn is_checkmate(&mut self) -> bool {
        let mut no_legal_moves = true;

        for idx in 0..BOARD_SIZE {
            if !self.is_on_board(idx) {
                continue;
            }

            let piece = self.get(idx);

            if self.is_friendly(piece) {
                let inner_moves = self.inner_moves(idx);

                if inner_moves.len() > 0 {
                    no_legal_moves = false;
                }
            }
        }

        self.in_check() && no_legal_moves
    }
    // DISREGARD
    pub fn is_draw(&mut self) -> bool {
        self.is_stalemate()
            || self.is_threefold_repetition()
            || self.is_50_moves_rule()
            || self.is_insufficient_materials()
    }
    // DISREGARD
    /// stalemate happens when a player has no legal inner_moves and is not in check
    pub fn is_stalemate(&mut self) -> bool {
        let mut no_legal_moves = true;

        for idx in 0..BOARD_SIZE {
            if !self.is_on_board(idx) {
                continue;
            }

            let piece = self.get(idx);

            if (piece != EMPTY || piece != EN_PASSANT_SQUARE) && self.is_friendly(piece) {
                let inner_moves = self.inner_moves(idx);

                if inner_moves.len() > 0 {
                    no_legal_moves = false;
                }
            }
        }

        !self.in_check() && no_legal_moves
    }

    // convert every move to FEN, store it as a unique key in a hashmap
    // if the value >= 3, then it is threefold repetition
    pub fn is_threefold_repetition(&mut self) -> bool {
        let fen = self.get_fen();
        let position = fen.split(" ").collect::<Vec<&str>>()[0];

        if let Some(count) = self.unique_positions.get(position) {
            *count >= 3
        } else {
            false
        }
    }
    // DISREGARD
    pub fn is_50_moves_rule(&mut self) -> bool {
        self.half_moves >= 100
    }
    // DISREGARD
    /*
        If both sides have any one of the following, and there are no pawns or other pieces on the board:

        A lone king
        a king and bishop (of same colors)
        a king and knight

        a king and two knights vs a lone king = draw

        accoring to https://support.chess.com/article/128-what-does-insufficient-mating-material-mean
    */
    pub fn is_insufficient_materials(&mut self) -> bool {
        let mut friendly_knights = 0;
        let mut friendly_bishops = 0;
        let mut friendly_dark_bishops = 0;
        let mut friendly_light_bishops = 0;
        let mut enemy_dark_bishops = 0;
        let mut enemy_light_bishops = 0;
        let mut enemy_knights = 0;
        let mut enemy_bishops = 0;

        for idx in 0..BOARD_SIZE {
            if !self.is_on_board(idx) {
                continue;
            }

            let piece = self.get(idx);
            let file = (idx & 7) + 1;
            let rank = 8 - ((idx >> 4) + 1) + 1;

            // if rank is odd and file is odd = dark
            // if rank is even and file is even = dark

            // if rank is even and file is odd = light
            // if rank is odd and file is even = light

            if piece != EMPTY {
                let piece_without_color = self.remove_color(piece);

                if piece_without_color == PAWN
                    || piece_without_color == ROOK
                    || piece_without_color == QUEEN
                {
                    return false;
                }

                if self.is_friendly(piece) {
                    if piece_without_color == KNIGHT {
                        friendly_knights += 1;
                    }

                    if piece_without_color == BISHOP {
                        // dark square bishop
                        if (rank % 2 != 0 && file % 2 != 0) || (rank % 2 == 0 && file % 2 == 0) {
                            friendly_dark_bishops += 1;

                            if enemy_light_bishops >= 1 {
                                return false;
                            }
                        }

                        // light square bishop
                        if (rank % 2 == 0 && file % 2 != 0) || (rank % 2 != 0 && file % 2 == 0) {
                            friendly_light_bishops += 1;

                            if enemy_dark_bishops >= 1 {
                                return false;
                            }
                        }

                        friendly_bishops += 1;
                    }
                } else {
                    if piece_without_color == KNIGHT {
                        enemy_knights += 1;
                    }

                    if piece_without_color == BISHOP {
                        // dark square bishop

                        if (rank % 2 != 0 && file % 2 != 0) || (rank % 2 == 0 && file % 2 == 0) {
                            enemy_dark_bishops += 1;

                            if friendly_light_bishops >= 1 {
                                return false;
                            }
                        }

                        // light square bishop
                        if (rank % 2 == 0 && file % 2 != 0) || (rank % 2 != 0 && file % 2 == 0) {
                            enemy_light_bishops += 1;

                            if friendly_dark_bishops >= 1 {
                                return false;
                            }
                        }

                        enemy_bishops += 1;
                    }
                }
            }
        }

        // king vs king
        if friendly_knights == 0
            && friendly_bishops == 0
            && enemy_knights == 0
            && enemy_bishops == 0
        {
            return true;
        }

        if friendly_knights == 0 && enemy_knights == 0 {
            if friendly_bishops == 2 || enemy_bishops == 2 {
                return false;
            }

            return true;
        }

        if friendly_bishops == 0 && enemy_bishops == 0 {
            if friendly_knights >= 1 && enemy_knights >= 1 {
                return false;
            }

            return true;
        }

        return false;
    }

    pub fn is_attacked(&self, square_idx: PieceIndex) -> bool {
        let mut is_attacked = false;
        for idx in 0..BOARD_SIZE {
            if !self.is_on_board(idx) {
                continue;
            }

            if is_attacked {
                break;
            }

            let piece = self.get(idx);
            let attacker_idx = idx;
            let defender_idx = square_idx;
            let defender_piece = self.get(defender_idx);

            if (self.is_friendly(piece) && piece != EN_PASSANT_SQUARE)
                || piece == EMPTY
                || piece == EN_PASSANT_SQUARE
            {
                continue;
            }

            let diff = (defender_idx as i16 - attacker_idx as i16) + 119;

            let attack_bits_mask = ATTACKS[diff as usize];

            if attack_bits_mask != 0 {
                // although the king can be attacked from a particular square, we also
                // have to take into account if that piece can attack from there
                let piece = self.get(attacker_idx);

                // remove the color mask
                let piece_type = self.get_type(piece);

                // check if that piece can attack from that particular square
                if (piece_type & attack_bits_mask) == piece_type {
                    if piece_type == KNIGHT {
                        return true;
                    } else if piece_type == PAWN {
                        let piece = self.remove_mask(piece, MOVED_MASK);
                        is_attacked = (piece & attack_bits_mask == piece)
                            && self.get_color(attack_bits_mask) == self.get_color(piece);
                    } else {
                        // check if there is a piece standing in the way of the attack
                        let delta = DELTAS[diff as usize];

                        let mut destination_idx = attacker_idx as i16 + delta as i16;

                        while self.is_on_board(destination_idx as PieceIndex) {
                            let piece = self.get(destination_idx as PieceIndex);
                            // 11000001
                            if piece == defender_piece
                                && destination_idx as PieceIndex == defender_idx
                            {
                                is_attacked = true;
                                break;
                            } else {
                                // check if there is a piece blocking the attack
                                if self.is_occupied(destination_idx as u8) {
                                    break;
                                }
                            }

                            destination_idx += delta as i16;
                        }
                    }
                }
            }
        }
        return is_attacked;
    }

    pub fn turn(&self) -> char {
        match self.turn {
            WHITE => 'w',
            BLACK => 'b',
            _ => panic!("Unknown turn"),
        }
    }

    /// 0 = white, 128 = black
    pub fn set_turn(&mut self, turn: u8) {
        if turn == WHITE {
            self.turn = WHITE;
        } else {
            self.turn = BLACK;
        }
    }

    pub fn convert_algebraic_notation_to_index(&self, notation: &str) -> u8 {
        let mut parts = notation.chars();

        let file = parts.next().unwrap();
        let rank = (parts.next().unwrap().to_digit(10).unwrap() - 1) as u8;

        let file = FILES
            .iter()
            .position(|f| f.eq(&file.to_string().as_str()))
            .unwrap() as u8;

        // we minus rank from 7 because the board is reversed (upside down)
        // so for example, for "e7", the rank 7 is rank 1 on our board
        (8 * (7 - rank) + file) as u8
    }

    pub fn convert_index_algebraic_notation(&self, index: u8) -> String {
        let file = index & 7;
        let rank = 8 - ((index >> 4) + 1) + 1;

        let file_letter = FILES[file as usize];

        let mut notation = String::new();

        notation.push_str(file_letter);
        notation.push_str(rank.to_string().as_str());

        notation
    }

    // https://www.chessprogramming.org/Perft
    pub fn perft(&mut self, depth: u8, yah: bool) -> u64 {
        let mut nodes: u64 = 0;
        let mut cnt = 0;

        if depth <= 0 {
            if self.in_check() {
                self.checks += 1;
            }
            return 1;
        }

        let moves = self.generate_legal_moves();

        for _move in moves {
            self.inner_move_piece(_move.from, _move.to);

            let from = self.convert_index_algebraic_notation(_move.from);
            let to = self.convert_index_algebraic_notation(_move.to);

            self.change_turn();
            self.update_castling_rights();

            cnt = self.perft(depth - 1, false);
            nodes += cnt;

            if yah {
                println!("{} {}", format!("{}{}", from, to), cnt);

                *self.moves.entry(format!("{}{}", from, to)).or_insert(0) = cnt;
            } else {
            }

            self.undo()
        }

        return nodes;
    }

    pub fn generate_legal_moves(&mut self) -> Vec<Move> {
        let mut moves = vec![];

        for idx in 0..BOARD_SIZE {
            if !self.is_on_board(idx) {
                continue;
            }

            let piece = self.get(idx);
            // let piece_type = self.get_type(piece);

            if piece == EN_PASSANT_SQUARE {
                continue;
            }

            if self.is_occupied(idx) && self.is_friendly(piece) {
                // for _move in self.moves(&self.convert_index_algebraic_notation(idx)) {
                //     // if _move.is_empty() {
                //     //     continue;
                //     // }
                //     moves.push(_move);
                // }
                for _move in self.inner_moves(idx) {
                    if _move > 150 {
                        continue;
                    }
                    moves.push(Move {
                        from: idx,
                        to: _move,
                    })
                }
            }
        }

        moves
    }

    pub fn change_turn(&mut self) {
        if self.turn == WHITE {
            self.last_turn = WHITE;
            self.set_turn(BLACK);
        } else {
            self.last_turn = BLACK;
            self.set_turn(WHITE);
        }
    }

    pub fn clear(&mut self) {
        *self = Self::new();
    }

    fn reset_half_moves(&mut self) {
        self.half_moves = 0;
    }

    fn is_occupied(&self, idx: PieceIndex) -> bool {
        let piece = self.get(idx);

        piece != EMPTY && piece != EN_PASSANT_SQUARE
    }

    fn clear_latest_en_passant_square(&mut self) {
        if let Some(sq) = &self.lastest_en_passant_square {
            let idx = BOARD_MAP[self.convert_algebraic_notation_to_index(sq.as_str()) as usize];

            let piece = self.get(idx);

            if piece == EN_PASSANT_SQUARE {
                self.set(EMPTY, idx);
                self.lastest_en_passant_square = None;
            }
        }
    }

    fn get_type(&self, piece: PieceType) -> PieceType {
        self.remove_mask(self.remove_color(piece), MOVED_MASK)
    }

    fn get_color(&self, piece: PieceType) -> PieceType {
        piece & COLOR_MASK
    }

    fn remove_color(&self, piece: PieceType) -> PieceType {
        self.remove_mask(piece, COLOR_MASK)
    }

    /// (white kingside, white queenside, blac kingside, black queenside)
    pub fn get_castling_rights_tests(&self) -> (bool, bool, bool, bool) {
        (
            self.can_white_king_side_castle,
            self.can_white_queen_side_castle,
            self.can_black_king_side_castle,
            self.can_black_queen_side_castle,
        )
    }

    pub fn get_castling_rights(&self) -> (bool, bool) {
        if self.turn == WHITE {
            (
                self.can_white_king_side_castle,
                self.can_white_queen_side_castle,
            )
        } else {
            (
                self.can_black_king_side_castle,
                self.can_black_queen_side_castle,
            )
        }
    }

    pub fn update_castling_rights(&mut self) {
        if self.kings.white != 116 {
            self.can_white_king_side_castle = false;
            self.can_white_queen_side_castle = false;
        }

        if self.kings.black != 4 {
            self.can_black_king_side_castle = false;
            self.can_black_queen_side_castle = false;
        }
        // 119 = h1
        // 112 = a1
        let right_white_rook_idx = 119;
        let left_white_rook_idx = 112;

        // 7 = h8
        // 0 = a8
        let right_black_rook_idx = 7;
        let left_black_rook_idx = 0;

        // if it isn't an *unmoved* rook, then we can't castle

        if self.get(right_white_rook_idx) != ROOK {
            self.can_white_king_side_castle = false;
        }

        if self.get(left_white_rook_idx) != ROOK {
            self.can_white_queen_side_castle = false;
        }

        if self.get(right_black_rook_idx) != BLACK_ROOK {
            self.can_black_king_side_castle = false;
        }

        if self.get(left_black_rook_idx) != BLACK_ROOK {
            self.can_black_queen_side_castle = false;
        }
    }

    fn is_queen_side_castling(&self, from: PieceIndex, to: PieceIndex) -> bool {
        to as i8 - from as i8 == -2
    }

    fn is_king_side_castling(&self, from: PieceIndex, to: PieceIndex) -> bool {
        to as i8 - from as i8 == 2
    }

    fn update_kings_position(&mut self, new_idx: PieceIndex) {
        if self.turn == WHITE {
            self.kings.white = new_idx;
        } else {
            self.kings.black = new_idx;
        }
    }

    fn capture(&mut self, piece: PieceType) {
        if self.turn == WHITE {
            self.white_captures.push(piece);
        } else {
            self.black_captures.push(piece);
        }
    }

    fn remove_mask(&self, piece: PieceType, mask: u8) -> u8 {
        (piece | mask) ^ mask
    }
    /// a piece is friendly if its color matches the current player's turn color
    fn is_friendly(&self, piece: PieceType) -> bool {
        piece & COLOR_MASK == self.turn
    }

    fn is_on_board(&self, square_idx: PieceIndex) -> bool {
        (square_idx) & 0x88 == 0
    }
}

// TODO: sort the inner_moves array in tests to ensure they match

#[cfg(test)]
mod bishop {
    use super::*;

    #[test]
    fn bishop_can_move_freely_if_king_is_not_checked() {
        let mut chess = Chess::new();

        chess.set(BISHOP, 52);
        chess.set(KING, 55);
        chess.set(BISHOP | BLACK, 86);

        let inner_moves = chess.inner_moves(52);
        let correct_moves = [69, 86, 67, 82, 97, 112, 35, 18, 1, 37, 22, 7];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        // chess.clear();

        // // chess.set(BISHOP, 0);
        // // chess.set(KING, 1);
        // // chess.set(BISHOP | BLACK, 7);

        // // let inner_moves = chess.inner_moves(0);
        // // let correct_moves = [17, 34, 51, 68, 85, 102, 119];

        // // assert!(inner_moves.iter().eq(correct_moves.iter()));

        // chess.clear();
        // chess.set_turn(BLACK);

        // chess.set(BISHOP, 103);
        // chess.set(KING | BLACK, 81);
        // chess.set(BISHOP | BLACK, 36);

        // let inner_moves = chess.inner_moves(36);
        // let correct_moves = [53, 70, 87, 51, 66, 19, 2, 21, 6];
        // assert!(inner_moves.iter().eq(correct_moves.iter()));

        // chess.clear();
        // chess.set_turn(BLACK);

        // chess.set(BISHOP, 103);
        // chess.set(KING | BLACK, 81);
        // chess.set(BISHOP | BLACK, 36);

        // let inner_moves = chess.inner_moves(36);
        // let correct_moves = [53, 70, 87, 51, 66, 19, 2, 21, 6];
        // assert!(inner_moves.iter().eq(correct_moves.iter()));

        // chess.clear();
        // chess.set_turn(BLACK);

        // chess.set(BISHOP, 0);
        // chess.set(KING | BLACK, 7);
        // chess.set(BISHOP | BLACK, 112);

        // let inner_moves = chess.inner_moves(112);
        // let correct_moves = [97, 82, 67, 52, 37, 22];

        // assert!(inner_moves.iter().eq(correct_moves.iter()));
    }

    #[test]
    fn bishop_can_not_move_because_king_is_checked() {
        let mut chess = Chess::new();

        chess.set(BISHOP, 117);
        chess.set(KING, 112);
        chess.set(BLACK_BISHOP, 97);

        let inner_moves = chess.inner_moves(117);

        assert_eq!(inner_moves, []);

        // chess.clear();

        // chess.set(BISHOP, 119);
        // chess.set(KING, 7);
        // chess.set(BISHOP | BLACK, 22);

        // let inner_moves = chess.inner_moves(119 as u8);
        // assert!(inner_moves.len() == 0);

        // chess.clear();

        // chess.set(BISHOP, 67);
        // chess.set(KING, 0);
        // chess.set(BISHOP | BLACK, 17);

        // let inner_moves = chess.inner_moves(67 as u8);
        // assert!(inner_moves.len() == 0);

        // chess.clear();

        // //======= BLACK =======
        // chess.set_turn(BLACK);

        // chess.set(BISHOP, 0);
        // chess.set(KING | BLACK, 17);
        // chess.set(BISHOP | BLACK, 51);

        // let inner_moves = chess.inner_moves(51);
        // assert!(inner_moves.len() == 0);

        // chess.clear();
        // chess.set_turn(BLACK);

        // chess.set(BISHOP, 67);
        // chess.set(KING | BLACK, 112);
        // chess.set(BISHOP | BLACK, 100);

        // let inner_moves = chess.inner_moves(100);
        // assert!(inner_moves.len() == 0);

        // chess.clear();
        // chess.set_turn(BLACK);

        // chess.set(BISHOP, 118);
        // chess.set(KING | BLACK, 16);
        // chess.set(BISHOP | BLACK, 21);

        // let inner_moves = chess.inner_moves(21);
        // assert!(inner_moves.len() == 0);
    }

    #[test]
    fn bishop_can_take_enemy_piece_to_stop_check() {
        let mut chess = Chess::new();

        chess.set(BISHOP, 2);
        chess.set(KING, 0);
        chess.set(BISHOP | BLACK, 17);

        let inner_moves = chess.inner_moves(2 as u8);
        let correct_moves = [17];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();

        chess.set(BISHOP, 99);
        chess.set(KING, 37);
        chess.set(BISHOP | BLACK, 54);

        let inner_moves = chess.inner_moves(99 as u8);
        let correct_moves = [54];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        // ====== BLACK =====

        chess.clear();
        chess.set_turn(BLACK);

        chess.set(BISHOP, 32);
        chess.set(KING | BLACK, 66);
        chess.set(BISHOP | BLACK, 17);

        let inner_moves = chess.inner_moves(17);
        let correct_moves = [32];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();
        chess.set_turn(BLACK);

        chess.set(BISHOP, 67);
        chess.set(KING | BLACK, 7);
        chess.set(BISHOP | BLACK, 118);

        let inner_moves = chess.inner_moves(118);
        let correct_moves = [67];

        assert!(inner_moves.iter().eq(correct_moves.iter()));
    }

    #[test]
    fn bishop_can_move_freely_if_king_is_shielded_from_check() {
        let mut chess = Chess::new();
        chess.set(BISHOP, 51);
        chess.set(KING, 7);
        chess.set(PAWN, 37);
        chess.set(BISHOP | BLACK, 67);

        let inner_moves = chess.inner_moves(51);
        let correct_moves = [68, 85, 102, 119, 66, 81, 96, 34, 17, 0, 36, 21, 6];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();

        chess.set(BISHOP, 118);
        chess.set(KING, 119);
        chess.set(PAWN, 102);
        chess.set(BISHOP | BLACK, 85);

        let inner_moves = chess.inner_moves(118);
        let correct_moves = [101, 84, 67, 50, 33, 16, 103];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();

        chess.set(BISHOP, 66);
        chess.set(KING, 17);
        chess.set(PAWN, 34);
        chess.set(BISHOP | BLACK, 51);

        let inner_moves = chess.inner_moves(66);
        let correct_moves = [83, 100, 117, 81, 96, 49, 32, 51];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        // ==== BLACK ====
        chess.clear();
        chess.set_turn(BLACK);

        chess.set(BISHOP, 64);
        chess.set(KING | BLACK, 4);
        chess.set(PAWN | BLACK, 19);
        chess.set(BISHOP | BLACK, 84);

        let inner_moves = chess.inner_moves(84);
        let correct_moves = [101, 118, 99, 114, 67, 50, 33, 16, 69, 54, 39];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();
        chess.set_turn(BLACK);

        chess.set(BISHOP, 53);
        chess.set(KING | BLACK, 87);
        chess.set(PAWN | BLACK, 70);
        chess.set(BISHOP | BLACK, 98);

        let inner_moves = chess.inner_moves(98);
        let correct_moves = [115, 113, 81, 64, 83, 68, 53];

        assert!(inner_moves.iter().eq(correct_moves.iter()));
    }
}

#[cfg(test)]
mod pawn {
    use super::*;

    #[test]
    fn pawn_valid_moves() {
        let mut chess = Chess::new();

        chess.set_turn(BLACK);
        chess.set(Piece::BLACK_PAWN, 98);
        let inner_moves = chess.inner_moves(98);
        let correct_moves = [114];

        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();

        chess.set_turn(BLACK);
        chess.set(Piece::BLACK_PAWN, 2);
        let inner_moves = chess.inner_moves(2);
        let correct_moves = [18, 34];
        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();

        chess.set(Piece::PAWN, 34);
        let inner_moves = chess.inner_moves(34);
        let correct_moves = [18, 2];
        assert!(inner_moves.iter().eq(correct_moves.iter()));

        chess.clear();

        chess.set(Piece::PAWN, 23);
        let inner_moves = chess.inner_moves(23);
        let correct_moves = [7];
        assert!(inner_moves.iter().eq(correct_moves.iter()));
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn lol() {}
}