Java中的国际象棋位板实现 [英] Chess bitboard implementation in Java

查看:189
本文介绍了Java中的国际象棋位板实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻求创建一个基本的国际象棋(或失败的棋子/草稿)引擎.在研究了该主题之后,我非常有信心要使用一系列的位板.我基本了解了这个概念,但是在用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.

我试图用长号将棋盘的白色棋子表示为1,将其他所有东西表示为0:

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

long whitePieces = 0000000000000000000000000000000000000000000000001111111111111111L;

但是当我打印出来时,我得到了以下46位:

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.

推荐答案

在您的名字前面加0b表示它是一个二进制数.

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

long whitePieces = 0b0000000000000000000000000000000000000000000000001111111111111111L;
                   ^^

(Java 7中引入了0b前缀.如果您使用的是旧版本,则可以执行Long.parseLong("000...111", 2))

(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, ... };

,然后将板存放在ChessPiece[8][8]中.与一堆long所提供的内容相比,这应该为您提供一个更加整洁的界面来读取和修改状态.

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.

如果您担心性能,只需将实际表示形式正确封装在Board类中(将实际数据结构设为私有).如果您稍后发现ChessPiece[8][8]成为瓶颈,则可以尝试一下并轻松地将其更改为long.

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.

这篇关于Java中的国际象棋位板实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆