我想建立一个国际象棋引擎,很长一段时间的项目。目前,我正在给flipp板(如扭转,但改变颜色也一样)的方法。大写字母代表白块,lowercaser字母黑色的。但好像Java是改写即使我不分配给它的任何值,我的临时变量,最初的初始化之后。正如看到的System.out.println:“R” < - 第一输出; “R”< - 第二输出
我很新的JAVA,并认为这个问题是分配一个静态变量的值给一个临时变量时引起的。在我的眼里应该的代码工作正常休息。
public class chess{
static String chessBoard[][]={
{"r","k","b","q","a","b","k","r"},
{"p","p","p","p","p","p","p","p"},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," ","P"," "},
{"P","P","P","P","P","P"," ","P"},
{"R","K","B","Q","A","B","K","R"}};
}
public static void flipBoard() {
String temp[][]=chessBoard;
System.out.println(temp[0][0]);
for(int i=0;i<64;i++){
int r=i/8, c=i%8;
chessBoard[r][c]=temp[7-r][7-c];
}
System.out.println(temp[0][0]);
}
我期待:
chessBoard[][]={
{"R","K","B","A","Q","B","K","R"},
{"P"," ","P","P","P","P","P","P"},
{" ","P"," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{"p","p","p","p","p","p","p","p"},
{"r","k","b","a","q","b","k","r"}};
但我得到:
chessBoard[][]={
{"R","K","B","A","Q","B","K","R"},
{"P"," ","P","P","P","P","P","P"},
{" ","P"," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," "," "," "},
{" "," "," "," "," "," ","P"," "},
{"P","P","P","P","P","P"," ","P"},
{"R","K","B","Q","A","B","K","R"}};
正如你所看到的,所有的作品现在都是白色的。我真的失去了我的脑海里有关的任何帮助,非常感谢!
String temp[][]=chessBoard;
//分配棋盘变量的参考温度。
为了使阵列的深层副本,试试这个
String[][] temp = new String[chessBoard.length][chessBoard[0].length];
为什么不:
public static void flipBoard() {
for(int r=0;r<4;r++){
String[] temp = chessBoard[r];
chessBoard[r] = chessBoard[7-r];
chessBoard[7-r] = temp;
}
}
或者你可能要扭转这种局面沿diagonale:
public static void flipBoard() {
for(int r=0;r<4;r++){
for(int c=0;c<8;c++){
String temp= chessBoard[r][c];
chessBoard[r][c] = chessBoard[7-r][7-c];
chessBoard[7-r][7-c] = temp;
}
}
}