This Python code parses string representations of Reversi boards and converts them into bit string suitable for use by a bitstring module: b = BitArray('0b110')
or bitarray module: a = bitarray('000111')
if blackInit
and whiteInit
are initialized as empty strings.
I am interested in a simpler way to do this in Python. I would like to preserve the idea of having a human readable string representation of the board converted into 2 bitstrings, one for the black pieces and one for the white pieces. It seems like it could be simpler if it was just a split and then a map instead of a loop, but I wanted to be able to see the strings line by line and don't see how to workaround that.
board1 = [
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_']
board2 = [
'B|_|_|_|_|_|_|W',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'W|_|_|_|_|_|_|B']
board3 = [
'W|W|W|W|B|B|B|B',
'W|_|_|_|_|_|_|B',
'W|_|_|_|_|_|_|B',
'W|_|_|_|_|_|_|B',
'B|_|_|_|_|_|_|W',
'B|_|_|_|_|_|_|W',
'B|_|_|_|_|_|_|W',
'B|B|B|B|W|W|W|W']
board4 = [
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|W|B|_|_|_',
'_|_|_|B|W|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_',
'_|_|_|_|_|_|_|_']
board5 = [
'W|_|_|_|_|_|_|B',
'_|W|_|_|_|_|B|_',
'_|_|W|_|_|B|_|_',
'_|_|_|W|B|_|_|_',
'_|_|_|B|W|_|_|_',
'_|_|B|_|_|W|_|_',
'_|B|_|_|_|_|W|_',
'B|_|_|_|_|_|_|W']
def parse_board(board):
def map_black(spot):
return str(int(spot == 'B'))
def map_white(spot):
return str(int(spot == 'W'))
blackInit = '0b'
whiteInit = '0b'
for line in board:
squares = line.split('|')
blackInit = blackInit + ''.join(map(map_black,squares))
whiteInit = whiteInit + ''.join(map(map_white,squares))
return (blackInit,whiteInit)
print(parse_board(board1))
print(parse_board(board2))
print(parse_board(board3))
print(parse_board(board4))
print(parse_board(board5))