我有一个看起来像
的简单测试public class Game {
public static void main(String[] args) {
// TODO Auto-generated method stub
Board b1 = new Board();
Knight bk = new Knight(Player.BLACK);
b1.placePiece(0, 0, bk);
System.out.println(b1.getPiece(0, 0));
}
}
这应该打印出“bk”,因为它被放在Board b1的(0,0)上。但它实际上会返回null。
我的Board类看起来像这样:
getPiece应该返回棋盘[x] [y]上的棋子但当然不会因为棋盘上没有任何东西[x] [y]。我知道什么是错的,但我不知道如何解决这个问题。
My Piece类看起来像:
public abstract class Piece {
Player color;
int x, y;
Piece(Player color){
this.color = color;
}
...
}
所以,我不知道如何让board [x] [y]成为正确的Piece对象。
编辑:
EDIT2:
public class Board {
....
}
答案 0 :(得分:1)
您需要初始化主板
board = new Piece[rows][cols]
考虑在构造函数
中执行此操作更新
要获取名称,您应该将成员名称添加到Piece类
abstract class Piece {
java.awt.Color color;
String name;
int x, y;
Piece(java.awt.Color color, String name) {
this.color = color;
this.name = name;
}
@Override
public String toString() {
return "Piece{" +
"color=" + color +
", name='" + name + '\'' +
", x=" + x +
", y=" + y +
'}';
}
}
class Knight extends Piece {
Knight(Color color, String name) {
super(color, name);
}
@Override
public boolean equals(Object obj) {
Knight that = (Knight) obj;
return this.color == that.color && this.name.equals(that.name);
}
}
覆盖字符串将导致
System.out.println(new Knight(Color.BLACK, "Robin Hood"));
打印
Piece{color=java.awt.Color[r=0,g=0,b=0], name='Robin Hood', x=0, y=0}