Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chess bitboard implementation in Java

Tags:

java

bitboard

I'm looking to create a basic chess (or failing that, checkers/draughts) engine. After researching the topic I'm fairly confident that I want to use a series of bitboards. I understand the concept at a basic level but I'm having trouble representing them in Java.

I've attempted to represent the white pieces of a chessboard as 1 and everything else as 0 using a long:

long whitePieces = 0000000000000000000000000000000000000000000000001111111111111111L;

But when I print it out I get the following 46 bits:

System.out.println(Long.toBinaryString(whitePieces));
1001001001001001001001001001001001001001001001

What is causing this result? I'm sure there's something I'm fundamentally misunderstanding here; If anyone could point me in the right direction I'd be very grateful.

like image 413
BeepBeep Avatar asked Aug 15 '14 07:08

BeepBeep


1 Answers

Add 0b in front of your long to say that it's a binary number.

long whitePieces = 0b0000000000000000000000000000000000000000000000001111111111111111L;
                   ^^

(0b prefix was introduced in Java 7. If you're on an older version you could do Long.parseLong("000...111", 2))


A different approach: How about creating an enum:

enum ChessPiece { Pawn, Knight, ... };

and store the board in a ChessPiece[8][8]. This should provide you with a much cleaner interface to read and modify the state than a bunch of longs would give you.

If you're concerned about performance, just keep the actual representation properly encapsulated in a Board class (make the actual data structure private). If you, at a later point, find that ChessPiece[8][8] turns out to be a bottleneck, you can play around and change it to a long without much effort.

like image 131
aioobe Avatar answered Oct 03 '22 05:10

aioobe