Jay Osayi
Jay Osayi

Reputation: 21

is there a better way to write this code in Python ? (transforming UCI-move into bitboard, chess)

I want to transform a UCI-move into bitboard.

for example a2a3 -> 32768, 8388608

I need to assign [7,6,...,0] to [a,b,...,h] so that for each letter i have the assigned number(n) to calculate 2^n

which i can then left shift by the value in uci[1] or uci[3] *8 depending on start- or endfield.

This is my approach and it doesnt look very nice and redundant.

def ucitoBit(uci):
    if uci[0] == 'a':
        mask1 = 2 ** 7
    if uci[0] == 'b':
        mask1 = 2 ** 6
    if uci[0] == 'c':
        mask1 = 2 ** 5
    if uci[0] == 'd':
        mask1 = 2 ** 4
    if uci[0] == 'e':
        mask1 = 2 ** 3
    if uci[0] == 'f':
        mask1 = 2 ** 2
    if uci[0] == 'g':
        mask1 = 2 ** 1
    if uci[0] == 'h':
        mask1 = 2 ** 0
    mask1 = mask1 << 8 * (int(uci[1]) - 1)

    if uci[2] == 'a':
        mask2 = 2 ** 7
    if uci[2] == 'b':
        mask2 = 2 ** 6
    if uci[2] == 'c':
        mask2 = 2 ** 5
    if uci[2] == 'd':
        mask2 = 2 ** 4
    if uci[2] == 'e':
        mask2 = 2 ** 3
    if uci[2] == 'f':
        mask2 = 2 ** 2
    if uci[2] == 'g':
        mask2 = 2 ** 1
    if uci[2] == 'h':
        mask2 = 2 ** 0
    mask2 = mask2 << 8 * (int(uci[3]) - 1)
    bitstring = [np.uint64(mask1), np.uint64(mask2)]
    return bitstring

Upvotes: 2

Views: 134

Answers (1)

Grim
Grim

Reputation: 11

How about defining two arrays containing the rows and cols indices and use them like this:

    rows = ["1", "2", "3", "4", "5", "6", "7", "8"]
    cols = ["a", "b", "c", "d", "e", "f", "g", "h"]

def parse_move(move):
    from_col, from_row, to_col, to_row = list(move)
    from_sq = 2**((7 - cols.index(from_col)) + 8*rows.index(from_row))
    to_sq = 2**((7 - cols.index(to_col)) + 8*rows.index(to_row))
    return [from_sq, to_sq]

Upvotes: 1

Related Questions