Last active
March 15, 2022 10:55
-
-
Save ilamanov/fcc92f54cd7e8af24564344eab2fa448 to your computer and use it in GitHub Desktop.
isValid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| contract Chess { | |
| /// @notice Determines whether a move is valid or not (i.e. within bounds and not capturing | |
| /// same colored piece). | |
| /// @dev As mentioned above, the board representation has 2 sentinel rows and columns for | |
| /// efficient boundary validation as follows: | |
| /// 0 0 0 0 0 0 0 0 | |
| /// 0 1 1 1 1 1 1 0 | |
| /// 0 1 1 1 1 1 1 0 | |
| /// 0 1 1 1 1 1 1 0 | |
| /// 0 1 1 1 1 1 1 0 | |
| /// 0 1 1 1 1 1 1 0 | |
| /// 0 1 1 1 1 1 1 0 | |
| /// 0 0 0 0 0 0 0 0, | |
| /// where 1 means a piece is within the board, and 0 means the piece is out of bounds. The bits | |
| /// are bitpacked into a uint256 (i.e. ``0x7E7E7E7E7E7E00 = 0 << 63 | ... | 0 << 0'') for | |
| /// efficiency. | |
| function isValid(uint256 _board, uint256 _toIndex) internal pure returns (bool) { | |
| unchecked { | |
| return (0x7E7E7E7E7E7E00 >> _toIndex) & 1 == 1 // Move is within bounds. | |
| && ((_board >> (_toIndex << 2)) & 0xF == 0 // Square is empty. | |
| || (((_board >> (_toIndex << 2)) & 0xF) >> 3) != _board & 1); // Piece captured. | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment