CONTEXT
I'm making this chess engine in python and one aspect of the program is that the board is represented by 64-bit numbers called bitboards, so I created a class to do just that, here is a snippet:
from __future__ import annotations
FULL_MASK = 0xFFFFFFFFFFFFFFFF
class BitBoard:
def __init__(self, board: int) -> None:
self.__board: int = board
@property
def board(self) -> int:
return self.__board & FULL_MASK
@board.setter
def board(self, value: int) -> None:
self.__board = value & FULL_MASK
def set_bit(self, square: int) -> None:
self.__board |= (1 << square) & FULL_MASK
def get_bit(self, square: int) -> None:
self.__board &= (1 << square) & FULL_MASK
def pop_bit(self, square: int) -> None:
self.__board &= ~(1 << square) & FULL_MASK
def __and__(self, value: int) -> BitBoard:
return BitBoard((self.__board & value) & FULL_MASK)
def __or__(self, value: int) -> BitBoard:
return BitBoard((self.__board | value) & FULL_MASK)
def __xor__(self, value: int) -> BitBoard:
return BitBoard((self.__board ^ value) & FULL_MASK)
def __inv__(self) -> BitBoard:
return BitBoard(~self.__board & FULL_MASK)
def __lshift__(self, value: int) -> BitBoard:
return BitBoard((self.__board << value) & FULL_MASK)
def __rshift__(self, value: int) -> BitBoard:
return BitBoard((self.__board >> value) & FULL_MASK)
As shown I've overidden all bitwise operations. While the NOT, SHIFT-LEFT, and SHIFT-RIGHT are rarely and/or never used with other bitboards, the AND, OR and XOR operators sometimes are.
QUESTION
Using the AND operator as in example, I want it so that if a bitboard is ANDed with a literal, it will bitwise AND its board with that literal. similarly, if it is ANDed with another bitboard, it will bitwise AND its board with the other's board. is there a way to do this? preferably without external modules.
ATTEMPTS
I've tried
def __and__(self, value: int | BitBoard) -> BitBoard:
result: BitBoard
if type(value) == int:
result = BitBoard((self.__board & value) & FULL_MASK)
if type(value) == Bitboard:
result = BitBoard((self.__board & value.board) & FULL_MASK)
return result
and other similar things but everytime the type checker yells at me for doing them. I know there is a way to do it with metaclasses but that would be counter productive since the purpose of using bitboards is to reduce computation. I am aware of the multipledispatch module but I'm aiming for this project to be pure base python.