Search code examples
pythonbitboard

update attack bit board when one attack is updated


This is just a principle. I would like the attacked bitboard to be updated when one of the attacks bitboards (knight, bishop or pawn) is altered without having to repeat line 1. Is this possible? what is the best way to do this? In borg class way or simply using the behaviour of dictionaries:

  1. attacked = pawn_attacks | knight_attacks | bishop_attacks

  2. pawn_attacks = (1 << (pawn + 9)) | (1<< (pawn + 7))

This doesn't work transparently / automatically when one of the attacks changes. Below the result of attacked is always 1.

class Test(object):
    def __init__(self):
        self.pawn_attacks = 0
        self.knight_attacks = 0
        self.bishop_attacks = 0

    @property
    def attacked(self):
        return self.pawn_attacks | self.knight_attacks | self.bishop_attacks

test = Test()
test.pawn_attacks = 1
print test.attacked
test.pawn_attacks = 2
print test.attacked

Solution

  • If you're writing a class, you can make attacked a (read-only) property so it gets transparently recomputed at need:

    ... rest of the class ...
    
    @property
    def attacked(self):
        return self.pawn_attacks | self.knight_attacks | self.bishop_attacks
    

    Now given an instance x of the class, x.attacked will always be up to date (caching to only recompute if needed is not warranted, given that the operation is so elementary anyway).

    If you're not willing to make a class you'll have to make attacked specifically a function to get the same idea working. However while Python doesn't force you to use classes the way some other languages do, nevertheless using classes when they provide structure and/or convenience, like here, is still a good idea:-)