Chess bitboard implementation in Java

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.


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 long s 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.


You're not storing a binary number, but a decimal one. To create a number using binary notation, you need to prefix it with 0b . See Oracle docs on binary literals.

Also, a single tile or piece of the chessboard can't be represented by a single bit at all, so you might want to rethink your solution in general.

链接地址: http://www.djcxy.com/p/84664.html

上一篇: 棋盘游戏逻辑的持久化插槽(Android)

下一篇: Java中的棋盘实现