-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchess.sol
More file actions
1301 lines (1171 loc) · 55.8 KB
/
chess.sol
File metadata and controls
1301 lines (1171 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;
contract Chess {
uint8 constant empty_const = 0x0;
uint8 constant pawn_const = 0x1; // 001
uint8 constant bishop_const = 0x2; // 010
uint8 constant knight_const = 0x3; // 011
uint8 constant rook_const = 0x4; // 100
uint8 constant queen_const = 0x5; // 101
uint8 constant king_const = 0x6; // 110
uint8 constant type_mask_const = 0x7;
uint8 constant color_const = 0x8;
uint8 constant piece_bit_size = 4;
uint8 constant piece_pos_shift_bit = 2;
uint32 constant en_passant_const = 0x000000ff;
uint32 constant king_pos_mask = 0x0000ff00;
uint32 constant king_pos_zero_mask = 0xffff00ff;
uint16 constant king_pos_bit = 8;
/**
@dev For castling masks, mask only the last bit of an uint8, to block any under/overflows.
*/
uint32 constant rook_king_side_move_mask = 0x00800000;
uint16 constant rook_king_side_move_bit = 16;
uint32 constant rook_queen_side_move_mask = 0x80000000;
uint16 constant rook_queen_side_move_bit = 24;
uint32 constant king_move_mask = 0x80800000;
uint16 constant pieces_left_bit = 32;
uint8 constant king_white_start_pos = 0x04;
uint8 constant king_black_start_pos = 0x3c;
uint16 constant pos_move_mask = 0xfff;
uint16 constant request_draw_const = 0x1000;
uint16 constant accept_draw_const = 0x2000;
uint16 constant resign_const = 0x3000;
uint8 constant inconclusive_outcome = 0x0;
uint8 constant draw_outcome = 0x1;
uint8 constant white_win_outcome = 0x2;
uint8 constant black_win_outcome = 0x3;
uint256 constant game_state_start =
0xcbaedabc99999999000000000000000000000000000000001111111143265234;
uint256 constant full_long_word_mask =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant invalid_move_constant =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/** @dev Initial white state:
0f: 15 (non-king) pieces left
00: Queen-side rook at a1 position
07: King-side rook at h1 position
04: King at e1 position
ff: En-passant at invalid position
*/
uint32 constant initial_white_state = 0x000704ff;
/** @dev Initial black state:
0f: 15 (non-king) pieces left
38: Queen-side rook at a8 position
3f: King-side rook at h8 position
3c: King at e8 position
ff: En-passant at invalid position
*/
uint32 constant initial_black_state = 0x383f3cff;
constructor ()
{ }
function checkGameFromStart(uint16[] memory moves)
public pure
returns (uint8, uint256, uint32, uint32)
{
return checkGame(game_state_start, initial_white_state, initial_black_state, false, moves);
}
/**
@dev Calculates the outcome of a game depending on the moves from a starting position.
Reverts when an invalid move is found.
@param startingGameState Game state from which start the movements
@param startingPlayerState State of the first playing player
@param startingOpponentState State of the other playing player
@param startingTurnBlack Whether the starting player is the black pieces
@param moves is the input array containing all the moves in the game
@return outcome can be 0 for inconclusive, 1 for draw, 2 for white winning, 3 for black winning
*/
function checkGame(uint256 startingGameState,
uint32 startingPlayerState,
uint32 startingOpponentState,
bool startingTurnBlack,
uint16[] memory moves)
public pure
returns (uint8 outcome, uint256 gameState, uint32 playerState, uint32 opponentState)
{
gameState = startingGameState;
playerState = startingPlayerState;
opponentState = startingOpponentState;
outcome = inconclusive_outcome;
bool currentTurnBlack = startingTurnBlack;
require(moves.length > 0, "inv moves");
if (moves[moves.length - 1] == accept_draw_const) {
// Check
require(moves.length >= 2, "inv draw");
require(moves[moves.length - 2] == request_draw_const, "inv draw");
outcome = draw_outcome;
} else if (moves[moves.length - 1] == resign_const) {
// Assumes that signatures have been checked and moves are in correct order
outcome = ((moves.length % 2) == 1) != currentTurnBlack ? black_win_outcome : white_win_outcome;
} else {
// Check entire game
// 50-move rule tracking
uint16 halfmoveClock = 0;
// Threefold/fivefold repetition tracking
bytes32[] memory posHashes = new bytes32[](moves.length + 1);
uint8[] memory posCounts = new uint8[](moves.length + 1);
uint256 uniquePos = 0;
for (uint256 i = 0; i < moves.length; )
{
uint16 move = moves[i];
// Record position for repetition detection (before move)
{
bytes32 posHash = keccak256(abi.encodePacked(gameState, playerState, opponentState, currentTurnBlack));
(bool isDraw, uint256 newUniquePos) = _checkRepetition(posHashes, posCounts, uniquePos, posHash);
uniquePos = newUniquePos;
if (isDraw) {
return (draw_outcome, gameState, playerState, opponentState);
}
}
// 50-move rule check (only for normal moves)
if (move < request_draw_const) {
halfmoveClock = _updateHalfmoveClock(gameState, move, halfmoveClock);
// 75-move automatic draw (FIDE Article 9.6)
if (halfmoveClock >= 150) {
return (draw_outcome, gameState, playerState, opponentState);
}
}
(gameState, opponentState, playerState) = verifyExecuteMove(gameState, move, playerState, opponentState, currentTurnBlack);
require (!checkForCheck(gameState, opponentState), "inv check");
//require (outcome == 0 || i == (moves.length - 1), "Excesive moves");
currentTurnBlack = !currentTurnBlack;
unchecked { i++; }
}
uint8 endgameOutcome = checkEndgame(gameState, playerState, opponentState);
if (endgameOutcome == 2) {
outcome = currentTurnBlack ? white_win_outcome : black_win_outcome;
} else if (endgameOutcome == 1) {
outcome = draw_outcome;
}
}
}
/**
@dev Helper: checks and updates repetition tracking arrays.
@return isDraw true if fivefold repetition detected
@return newUniquePos updated count of unique positions
*/
function _checkRepetition(
bytes32[] memory posHashes,
uint8[] memory posCounts,
uint256 uniquePos,
bytes32 posHash
) internal pure returns (bool isDraw, uint256 newUniquePos) {
for (uint256 pi = 0; pi < uniquePos; pi++) {
if (posHashes[pi] == posHash) {
unchecked { posCounts[pi]++; }
if (posCounts[pi] >= 4) { // 5-fold = automatic (4 repetitions after initial = 5 total)
return (true, uniquePos);
}
return (false, uniquePos);
}
}
posHashes[uniquePos] = posHash;
posCounts[uniquePos] = 1;
unchecked { uniquePos++; }
return (false, uniquePos);
}
/**
@dev Helper: updates the halfmove clock for the 50-move rule.
@return updated halfmove clock value
*/
function _updateHalfmoveClock(
uint256 gameState,
uint16 move,
uint16 halfmoveClock
) internal pure returns (uint16) {
uint8 fromPos50 = uint8((move >> 6) & 0x3f);
uint8 toPos50 = uint8(move & 0x3f);
uint8 movingPiece50 = pieceAtPosition(gameState, fromPos50) & type_mask_const;
bool isCapture50 = pieceAtPosition(gameState, toPos50) != empty_const;
if (movingPiece50 == pawn_const || isCapture50) {
return 0;
} else {
unchecked { halfmoveClock++; }
return halfmoveClock;
}
}
/**
@dev Calculates the outcome of a single move given the current game state.
Reverts for invalid movement.
@param gameState current game state on which to perform the movement.
@param move is the move to execute: 16-bit var, high word = from pos, low word = to pos
move can also be: resign, request draw, accept draw.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecuteMove(uint256 gameState, uint16 move, uint32 playerState, uint32 opponentState, bool currentTurnBlack)
public pure
returns (uint256 newGameState, uint32 newPlayerState, uint32 newOpponentState)
{
// Handle special moves before piece validation
if (move == request_draw_const || move == accept_draw_const || move == resign_const) {
return (gameState, playerState, opponentState);
}
uint8 fromPos = (uint8)((move >> 6) & 0x3f);
uint8 toPos = (uint8)(move & 0x3f);
// uint8 moveExtra = (uint8)(move >> 12);
require(fromPos != toPos, "inv move stale");
uint8 fromPiece = pieceAtPosition(gameState, fromPos);
require(((fromPiece & color_const) > 0) == currentTurnBlack, "inv move color");
uint8 fromType = fromPiece & type_mask_const;
newPlayerState = playerState;
newOpponentState = opponentState;
if (fromType == pawn_const)
{
(newGameState, newPlayerState) =
verifyExecutePawnMove(gameState, fromPos, toPos, (uint8)(move >> 12), currentTurnBlack, playerState, opponentState);
}
else if (fromType == knight_const)
{
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
}
else if (fromType == bishop_const)
{
newGameState = verifyExecuteBishopMove(gameState, fromPos, toPos, currentTurnBlack);
}
else if (fromType == rook_const)
{
newGameState = verifyExecuteRookMove(gameState, fromPos, toPos, currentTurnBlack);
// Reset playerState if necessary when one of the rooks move
if (fromPos == (uint8)(playerState >> rook_king_side_move_bit)) {
newPlayerState = playerState | rook_king_side_move_mask;
} else if (fromPos == (uint8)(playerState >> rook_queen_side_move_bit)) {
newPlayerState = playerState | rook_queen_side_move_mask;
}
}
else if (fromType == queen_const)
{
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
}
else if (fromType == king_const)
{
(newGameState, newPlayerState) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
}
else
{
revert("inv move type");
}
require(newGameState != invalid_move_constant, "inv move");
if ( toPos == (opponentState & en_passant_const) ) {
if ( currentTurnBlack ) {
newGameState = zeroPosition(newGameState, toPos + 8);
} else {
newGameState = zeroPosition(newGameState, toPos - 8);
}
}
newOpponentState = opponentState | en_passant_const;
}
/**
@dev Calculates the outcome of a single move of a pawn given the current game state.
Returns invalid_move_constant for invalid movement.
@param gameState current game state on which to perform the movement.
@param fromPos is position moving from.
@param toPos is position moving to.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecutePawnMove(uint256 gameState, uint8 fromPos, uint8 toPos, uint8 moveExtra, bool currentTurnBlack, uint32 playerState, uint32 opponentState)
public pure
returns (uint256 newGameState, uint32 newPlayerState)
{
newPlayerState = playerState;
// require ((currentTurnBlack && (toPos < fromPos)) || (!currentTurnBlack && (fromPos < toPos)), "inv move");
if (currentTurnBlack != (toPos < fromPos)) {
// newGameState = invalid_move_constant;
return (invalid_move_constant, 0x0);
}
uint8 diff = uint8((fromPos > toPos ? fromPos - toPos : toPos - fromPos));
uint8 pieceToPosition = pieceAtPosition(gameState, toPos);
if (diff == 8 || diff == 16) {
if (pieceToPosition != 0) {
//newGameState = invalid_move_constant;
return (invalid_move_constant, 0x0);
}
if (diff == 16) {
if ((currentTurnBlack && ((fromPos >> 3) != 0x6)) ||
(!currentTurnBlack && ((fromPos >> 3) != 0x1))) {
return (invalid_move_constant, 0x0);
}
uint8 posToInBetween = toPos > fromPos ? fromPos + 8 : toPos + 8;
if (pieceAtPosition(gameState, posToInBetween) != 0) {
return (invalid_move_constant, 0x0);
}
newPlayerState = (newPlayerState & (~en_passant_const)) | (uint32)(posToInBetween);
}
} else if (diff == 7 || diff == 9) {
if (getVerticalMovement(fromPos, toPos) != 1) {
return (invalid_move_constant, 0x0);
}
if ((uint8)(opponentState & en_passant_const) != toPos) {
if ((pieceToPosition == 0) || // Must be moving to occupied square
(currentTurnBlack == ((pieceToPosition & color_const) == color_const)) // Must be different color
) {
return (invalid_move_constant, 0x0);
}
}
} else return (invalid_move_constant, 0x0);
newGameState = commitMove(gameState, fromPos, toPos);
if ((currentTurnBlack && ((toPos >> 3) == 0x0)) || (!currentTurnBlack && ((toPos >> 3) == 0x7))) {
// Promotion
require ((moveExtra == bishop_const) || (moveExtra == knight_const) ||
(moveExtra == rook_const) || (moveExtra == queen_const), "inv prom");
newGameState = setPosition(zeroPosition(newGameState, toPos), toPos, currentTurnBlack ? moveExtra | color_const : moveExtra);
}
}
/**
@dev Calculates the outcome of a single move of a knight given the current game state.
Returns invalid_move_constant for invalid movement.
@param gameState current game state on which to perform the movement.
@param fromPos is position moving from.
@param toPos is position moving to.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecuteKnightMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack)
public pure
returns (uint256)
{
uint8 pieceToPosition = pieceAtPosition(gameState, toPos);
if (pieceToPosition > 0) {
if (((pieceToPosition & color_const ) == color_const) == currentTurnBlack ) {
return invalid_move_constant;
}
}
uint8 h = getHorizontalMovement(fromPos, toPos);
uint8 v = getVerticalMovement(fromPos, toPos);
if (!((h == 2 && v == 1) || (h == 1 && v == 2))) {
return invalid_move_constant;
}
return commitMove(gameState, fromPos, toPos);
}
/**
@dev Calculates the outcome of a single move of a bishop given the current game state.
Returns invalid_move_constant for invalid movement.
@param gameState current game state on which to perform the movement.
@param fromPos is position moving from.
@param toPos is position moving to.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecuteBishopMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack)
public pure
returns (uint256)
{
uint8 pieceToPosition = pieceAtPosition(gameState, toPos);
if (pieceToPosition > 0) {
if ( ((pieceToPosition & color_const ) == color_const) == currentTurnBlack ) {
return invalid_move_constant;
}
}
uint8 h = getHorizontalMovement(fromPos, toPos);
uint8 v = getVerticalMovement(fromPos, toPos);
if (( h != v ) || ( (gameState & getInBetweenMask(fromPos, toPos)) != 0x00 )) {
return invalid_move_constant;
}
return commitMove(gameState, fromPos, toPos);
}
/**
@dev Calculates the outcome of a single move of a rook given the current game state.
Returns invalid_move_constant for invalid movement.
@param gameState current game state on which to perform the movement.
@param fromPos is position moving from.
@param toPos is position moving to.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecuteRookMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack)
public pure
returns (uint256)
{
uint8 pieceToPosition = pieceAtPosition(gameState, toPos);
if (pieceToPosition > 0) {
if ( ((pieceToPosition & color_const ) == color_const) == currentTurnBlack ) {
return invalid_move_constant;
}
}
uint8 h = getHorizontalMovement(fromPos, toPos);
uint8 v = getVerticalMovement(fromPos, toPos);
if(((h > 0) == (v > 0)) || (gameState & getInBetweenMask(fromPos, toPos)) != 0x00) {
return invalid_move_constant;
}
return commitMove(gameState, fromPos, toPos);
}
/**
@dev Calculates the outcome of a single move of the queen given the current game state.
Returns invalid_move_constant for invalid movement.
@param gameState current game state on which to perform the movement.
@param fromPos is position moving from.
@param toPos is position moving to.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecuteQueenMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack)
public pure
returns (uint256)
{
uint8 pieceToPosition = pieceAtPosition(gameState, toPos);
if (pieceToPosition > 0) {
if ( ((pieceToPosition & color_const ) == color_const) == currentTurnBlack ) {
return invalid_move_constant;
}
}
uint8 h = getHorizontalMovement(fromPos, toPos);
uint8 v = getVerticalMovement(fromPos, toPos);
if (((h != v) && (h != 0) && (v != 0)) || (gameState & getInBetweenMask(fromPos, toPos)) != 0x00) {
return invalid_move_constant;
}
return commitMove(gameState, fromPos, toPos);
}
/**
@dev Calculates the outcome of a single move of the king given the current game state.
Returns invalid_move_constant for invalid movement.
@param gameState current game state on which to perform the movement.
@param fromPos is position moving from. Behavior is undefined for values >= 0x40.
@param toPos is position moving to. Behavior is undefined for values >= 0x40.
@param currentTurnBlack true if it's black turn
@return newGameState the new game state after it's executed.
*/
function verifyExecuteKingMove(uint256 gameState, uint8 fromPos, uint8 toPos, bool currentTurnBlack, uint32 playerState)
public pure
returns (uint256 newGameState, uint32 newPlayerState)
{
newPlayerState = (playerState | king_move_mask) & king_pos_zero_mask | ((uint32)(toPos) << king_pos_bit);
uint8 pieceToPosition = pieceAtPosition(gameState, toPos);
if (pieceToPosition > 0) {
if ( ((pieceToPosition & color_const ) == color_const) == currentTurnBlack ) {
return (invalid_move_constant, newPlayerState);
}
}
if (toPos >= 0x40 || fromPos >= 0x40)
return (invalid_move_constant, newPlayerState);
uint8 h = getHorizontalMovement(fromPos, toPos);
uint8 v = getVerticalMovement(fromPos, toPos);
if ((h <= 1) && (v <= 1)) {
return (commitMove(gameState, fromPos, toPos), newPlayerState);
} else if ((h == 2) && (v == 0))
{
if (!pieceUnderAttack(gameState, fromPos)) {
// TODO: must we check king's 'from' position?
// Reasoning: castilngRookPosition resolves to an invalid toPos when the rook or the king have already moved.
uint8 castilngRookPosition = (uint8)(playerState >> rook_queen_side_move_bit);
if ( castilngRookPosition + 2 == toPos ) { // Queen-side castling
// Spaces between king and rook original positions must be empty
if ((getInBetweenMask(castilngRookPosition, fromPos) & gameState) == 0) {
// Move King 1 space to the left and check for attacks (there must be none)
newGameState = commitMove(gameState, fromPos, fromPos - 1);
if (!pieceUnderAttack(newGameState, fromPos - 1)) {
return (commitMove(commitMove(newGameState, fromPos - 1, toPos), castilngRookPosition, fromPos - 1), newPlayerState);
}
}
} else {
castilngRookPosition = (uint8)(playerState >> rook_king_side_move_bit);
if ( castilngRookPosition - 1 == toPos ) { // King-side castling
// Spaces between king and rook original positions must be empty
if ((getInBetweenMask(castilngRookPosition, fromPos) & gameState) == 0) {
// Move King 1 space to the left and check for attacks (there must be none)
newGameState = commitMove(gameState, fromPos, fromPos + 1);
if (!pieceUnderAttack(newGameState, fromPos + 1)) {
return (commitMove(commitMove(newGameState, fromPos + 1, toPos), castilngRookPosition, fromPos + 1), newPlayerState);
}
}
}
}
}
}
return (invalid_move_constant, 0x00);
}
function checkQueenValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack)
public pure
returns (bool)
{
uint256 newGameState;
uint8 toPos;
uint8 kingPos = (uint8)(playerState >> king_pos_bit); /* Kings position cannot be affected by Queen's movement */
// Check left
for ( toPos = fromPos - 1; (toPos & 0x7) < (fromPos & 0x7); toPos-- ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check right
for ( toPos = fromPos + 1; (toPos & 0x7) > (fromPos & 0x7); toPos++ ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check up
for ( toPos = fromPos + 8; toPos < 0x40; toPos += 8 ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check down
for ( toPos = fromPos - 8; toPos < fromPos; toPos -= 8 ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check up-right
for ( toPos = fromPos + 9; (toPos < 0x40) && ((toPos & 0x7) > (fromPos & 0x7)); toPos += 9 ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check up-left
for ( toPos = fromPos + 7; (toPos < 0x40) && ((toPos & 0x7) < (fromPos & 0x7)); toPos += 7 ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check down-right
for ( toPos = fromPos - 7; (toPos < fromPos) && ((toPos & 0x7) > (fromPos & 0x7)); toPos -= 7 ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check down-left
for ( toPos = fromPos - 9; (toPos < fromPos) && ((toPos & 0x7) < (fromPos & 0x7)); toPos -= 9 ) {
newGameState = verifyExecuteQueenMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
return false;
}
function checkBishopValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack)
public pure
returns (bool)
{
uint256 newGameState;
uint8 toPos;
uint8 kingPos = (uint8)(playerState >> king_pos_bit); /* Kings position cannot be affected by Bishop's movement */
// Check up-right
for ( toPos = fromPos + 9; (toPos < 0x40) && ((toPos & 0x7) > (fromPos & 0x7)); toPos += 9 ) {
newGameState = verifyExecuteBishopMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check up-left
for ( toPos = fromPos + 7; (toPos < 0x40) && ((toPos & 0x7) < (fromPos & 0x7)); toPos += 7 ) {
newGameState = verifyExecuteBishopMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check down-right
for ( toPos = fromPos - 7; (toPos < fromPos) && ((toPos & 0x7) > (fromPos & 0x7)); toPos -= 7 ) {
newGameState = verifyExecuteBishopMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check down-left
for ( toPos = fromPos - 9; (toPos < fromPos) && ((toPos & 0x7) < (fromPos & 0x7)); toPos -= 9 ) {
newGameState = verifyExecuteBishopMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
return false;
}
function checkRookValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack)
public pure
returns (bool)
{
uint256 newGameState;
uint8 toPos;
uint8 kingPos = (uint8)(playerState >> king_pos_bit); /* Kings position cannot be affected by Rook's movement */
// Check left
for ( toPos = fromPos - 1; (toPos & 0x7) < (fromPos & 0x7); toPos-- ) {
newGameState = verifyExecuteRookMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check right
for ( toPos = fromPos + 1; (toPos & 0x7) > (fromPos & 0x7); toPos++ ) {
newGameState = verifyExecuteRookMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check up
for ( toPos = fromPos + 8; toPos < 0x40; toPos += 8 ) {
newGameState = verifyExecuteRookMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
// Check down
for ( toPos = fromPos - 8; toPos < fromPos; toPos -= 8 ) {
newGameState = verifyExecuteRookMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
if (((gameState >> (toPos << piece_pos_shift_bit)) & 0xF) != 0) break;
}
return false;
}
function checkKnightValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack)
public pure
returns (bool)
{
uint256 newGameState;
uint8 toPos;
uint8 kingPos = (uint8)(playerState >> king_pos_bit); /* Kings position cannot be affected by knight's movement */
toPos = fromPos + 6;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos - 6;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos + 10;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos - 10;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos - 17;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos + 17;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos + 15;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = fromPos - 15;
newGameState = verifyExecuteKnightMove(gameState, fromPos, toPos, currentTurnBlack);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
return false;
}
function checkPawnValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, uint32 opponentState, bool currentTurnBlack)
public pure
returns (bool)
{
uint256 newGameState;
uint8 toPos;
uint8 moveExtra = queen_const; /* Since this is supposed to be endgame, movement of promoted piece is irrelevant. */
uint8 kingPos = (uint8)(playerState >> king_pos_bit); /* Kings position cannot be affected by pawn's movement */
toPos = currentTurnBlack ? fromPos - 7 : fromPos + 7;
(newGameState, ) = verifyExecutePawnMove(gameState, fromPos, toPos, moveExtra, currentTurnBlack, playerState, opponentState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = currentTurnBlack ? fromPos - 8 : fromPos + 8;
(newGameState, ) = verifyExecutePawnMove(gameState, fromPos, toPos, moveExtra, currentTurnBlack, playerState, opponentState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = currentTurnBlack ? fromPos - 9 : fromPos + 9;
(newGameState, ) = verifyExecutePawnMove(gameState, fromPos, toPos, moveExtra, currentTurnBlack, playerState, opponentState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
toPos = currentTurnBlack ? fromPos - 16 : fromPos + 16;
(newGameState, ) = verifyExecutePawnMove(gameState, fromPos, toPos, moveExtra, currentTurnBlack, playerState, opponentState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, kingPos))) {
return true;
}
return false;
}
function checkKingValidMoves(uint256 gameState, uint8 fromPos, uint32 playerState, bool currentTurnBlack)
public pure
returns (bool)
{
uint256 newGameState;
uint8 toPos;
toPos = fromPos - 9;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos - 8;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos - 7;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos - 1;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos + 1;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos + 7;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos + 8;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
toPos = fromPos + 9;
(newGameState, ) = verifyExecuteKingMove(gameState, fromPos, toPos, currentTurnBlack, playerState);
if ((newGameState != invalid_move_constant) && (!pieceUnderAttack(newGameState, toPos))) {
return true;
}
// Check king-side castling
{
if ((playerState & rook_king_side_move_mask) == 0 && !pieceUnderAttack(gameState, fromPos)) {
uint8 targetPos = uint8(uint256(fromPos) + 2);
// Check squares between king and rook are empty (king+1 and king+2)
if (pieceAtPosition(gameState, uint8(uint256(fromPos) + 1)) == empty_const &&
pieceAtPosition(gameState, targetPos) == empty_const) {
// Check king doesn't pass through check
if (!pieceUnderAttack(gameState, uint8(uint256(fromPos) + 1)) &&
!pieceUnderAttack(gameState, targetPos)) {
return true;
}
}
}
}
// Check queen-side castling
{
if ((playerState & rook_queen_side_move_mask) == 0 && !pieceUnderAttack(gameState, fromPos)) {
uint8 targetPos = uint8(uint256(fromPos) - 2);
// Queen-side: squares between king and rook must be empty (king-1, king-2)
if (pieceAtPosition(gameState, uint8(uint256(fromPos) - 1)) == empty_const &&
pieceAtPosition(gameState, targetPos) == empty_const) {
if (!pieceUnderAttack(gameState, uint8(uint256(fromPos) - 1)) &&
!pieceUnderAttack(gameState, targetPos)) {
return true;
}
}
}
}
return false;
}
/**
@dev Performs one iteration of recursive search for pieces.
@param gameState Game state from which start the movements
@param playerState State of the player
@param opponentState State of the opponent
@return returns true if any of the pieces in the current offest has legal moves
*/
function searchPiece(uint256 gameState, uint32 playerState, uint32 opponentState, uint8 color)
internal pure
returns (bool)
{
bool isTurnBlack = color != 0;
for (uint8 pos = 0; pos < 64; pos++) {
uint8 piece = uint8((gameState >> (uint256(pos) * piece_bit_size)) & 0xF);
if (piece == 0 || (piece & color_const) != color) continue;
uint8 pt = piece & type_mask_const;
if (pt == king_const && checkKingValidMoves(gameState, pos, playerState, isTurnBlack)) return true;
if (pt == pawn_const && checkPawnValidMoves(gameState, pos, playerState, opponentState, isTurnBlack)) return true;
if (pt == knight_const && checkKnightValidMoves(gameState, pos, playerState, isTurnBlack)) return true;
if (pt == rook_const && checkRookValidMoves(gameState, pos, playerState, isTurnBlack)) return true;
if (pt == bishop_const && checkBishopValidMoves(gameState, pos, playerState, isTurnBlack)) return true;
if (pt == queen_const && checkQueenValidMoves(gameState, pos, playerState, isTurnBlack)) return true;
}
return false;
}
/**
@dev Checks whether the given game state has insufficient material for either side to deliver checkmate.
@param gameState current game state
@return true if the position is a draw by insufficient material
*/
function checkInsufficientMaterial(uint256 gameState) internal pure returns (bool) {
// Count pieces for each side
uint8 whitePieces = 0;
uint8 blackPieces = 0;
uint8 whiteBishopColor = 0; // 1=light, 2=dark, 3=both
uint8 blackBishopColor = 0;
bool whiteHasBishop = false;
bool blackHasBishop = false;
bool whiteHasRookQueenPawn = false;
bool blackHasRookQueenPawn = false;
for (uint8 pos = 0; pos < 64; pos++) {
uint8 piece = pieceAtPosition(gameState, pos);
if (piece == empty_const) continue;
uint8 ptype = piece & type_mask_const;
bool isBlack = (piece & color_const) != 0;
if (ptype == pawn_const || ptype == rook_const || ptype == queen_const) {
if (isBlack) blackHasRookQueenPawn = true;
else whiteHasRookQueenPawn = true;
} else if (ptype == bishop_const) {
// Square color: (row + col) % 2, where pos = row*8 + col
uint8 squareColor = uint8((pos / 8 + pos % 8) % 2 + 1); // 1 or 2
if (isBlack) { blackHasBishop = true; blackBishopColor |= squareColor; blackPieces++; }
else { whiteHasBishop = true; whiteBishopColor |= squareColor; whitePieces++; }
} else if (ptype == knight_const) {
if (isBlack) { blackPieces++; }
else { whitePieces++; }
}
// Kings not counted
}
// If either side has rook/queen/pawn, not insufficient
if (whiteHasRookQueenPawn || blackHasRookQueenPawn) return false;
// K vs K
if (whitePieces == 0 && blackPieces == 0) return true;
// K+B vs K or K+N vs K
if ((whitePieces == 1 && blackPieces == 0) || (whitePieces == 0 && blackPieces == 1)) return true;
// K+B vs K+B, same-color bishops
if (whitePieces == 1 && blackPieces == 1 && whiteHasBishop && blackHasBishop) {
if (whiteBishopColor == blackBishopColor) return true; // same color squares
}
return false;
}
/**
@dev Checks the endgame state and determines whether the last user is checkmate'd or
stalemate'd, or neither.
@param gameState Game state from which start the movements
@param playerState State of the player
@return outcome can be 0 for inconclusive/only check, 1 stalemate, 2 checkmate
*/
function checkEndgame(uint256 gameState, uint32 playerState, uint32 opponentState)
public pure
returns (uint8) {
if (checkInsufficientMaterial(gameState)) {
return draw_outcome;
}
uint8 kingPiece = (uint8)(gameState >> ((uint8)(playerState >> king_pos_bit) << piece_pos_shift_bit)) & 0xF;
assert((kingPiece & (~color_const)) == king_const);
bool legalMoves = searchPiece(gameState, playerState, opponentState, color_const & kingPiece);
// If the player is in check but also
if (checkForCheck(gameState, playerState)) {
return legalMoves ? 0 : 2;
}
return legalMoves ? 0 : 1;
}
/**
@dev Gets the mask of the in-between squares.
Basically it performs bit-shifts depending on the movement.
Down: >> 8
Up: << 8
Right: << 1
Left: >> 1
UpRight: << 9
DownLeft: >> 9
DownRight: >> 7
UpLeft: << 7
Reverts for invalid movement.
@param fromPos is position moving from.