1

I want to program a chess engine using bitboards. Because I am not very familiar with bitboards I am trying to figure out first how to use them. I wrote a small function which should print the bitboard. That's where I stumbled upon a problem. My function seems to print out the ranks correctly but doesn't seem to print out the files correctly.

def print_bitboard(bitboard):
    board = str(bin(bitboard)).zfill(64)
    for i in range(8):
    print(board[8*i+0] + " " + board[8*i+1] + " " + board[8*i+2] + " " + 
          board[8*i+3] + " " + board[8*i+4] + " " + board[8*i+5] + " " + 
          board[8*i+6] + " " + board[8*i+7])


bitboard1 = 
int("0000000000000000000000000000000000000000000000001111111100000000", 2)  
# 2nd rank
bitboard2 = 
int("1000000010000000100000001000000010000000100000001000000010000000", 2)  
# file A

print_bitboard(bitboard1)
print("")
print_bitboard(bitboard2)

Result:

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 b
1 1 1 1 1 1 1 1 
0 0 0 0 0 0 0 0

0 b 1 0 0 0 0 0     ----> wrong, should be: 1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0                             1 0 0 0 0 0 0 0
  • Is the incorrect indentation of the `print` statement below `for i in range(8):` actually that way in your code? – Random Davis Feb 12 '19 at 20:41
  • What do you expect to get when you do, say, `str(bin(1))`? What do you get when you actually try it? – glibdud Feb 12 '19 at 20:44

2 Answers2

1

The bin function always returns a valid Python representation of a binary literal starting with 0b. If you not want it you can use the str.format method instead:

board = '{:064b}'.format(bitboard)
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

You can use wrap to split a string to a list of substrings and join to merge the created lists:

from textwrap import wrap

                                       # |                           |
def print_bitboard(board):             # v split for spaces          v split for newlines
    print('\n'.join([' '.join(wrap(line, 1)) for line in wrap(board, 8)]))

bitboard1 = '0000000000000000000000000000000000000000000000001111111100000000'
print_bitboard(bitboard1)

# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 0 0 0 0 0 0 0 0
# 1 1 1 1 1 1 1 1
# 0 0 0 0 0 0 0 0

bitboard2 = '1000000010000000100000001000000010000000100000001000000010000000'
print_bitboard(bitboard2)

# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
# 1 0 0 0 0 0 0 0
Darius
  • 10,762
  • 2
  • 29
  • 50