英文:
How to add an object inside another object?
问题
我正在尝试创建一个控制台国际象棋游戏。
我有一个Square类,我的棋盘上有64个Square对象。此外,其中一些方格有Piece对象。我该如何将这些Piece对象添加到Square对象中?*
public class Square {
int column;
int row;
Piece piece;
Square(){
}
public void setRow(int row) {
this.row = row;
}
public void setColumn(int col){
this.column = col;
}
@Override
public String toString() {
// TODO Auto-generated method stub
if (1 < row && row < 6)
return " ";
return super.toString();
}
}
英文:
I am trying to create a console chess game.
I have Square class and my Chessboard have 64 Square objects. Also some of these squares have Piece object. How can i add these Piece objects into the Square Objects?*
public class Square {
int column;
int row;
Piece piece;
Square(){
}
public void setRow(int row) {
this.row=row;
}
public void setColumn(int col){
this.column=col;
}
@Override
public String toString() {
// TODO Auto-generated method stub
if(1< row && row <6)
return " ";
return super.toString();
}
}
答案1
得分: 0
public void setPiece(Piece piece) {
this.piece = piece;
}
将这段代码添加到你的类中,可以为每个方格设置一个棋子。你还可以在方格的构造函数中定义棋子,这样可以确保每个方格始终有一个定义好的棋子。
英文:
public void setPiece(Piece piece) {
this.piece = piece;
}
Adding this to your class lets you set a piece for each square. You can also define the piece in the square's constructor as this quarantees that a square always has a defined piece.
答案2
得分: 0
你可以将这些有用的方法添加到你的Square
类中,以便在所有你想要的方格之间设置不同的棋子。
/**
* 在实际方格上放置棋子。
*/
public void setPiece(Piece piece) {
this.piece = piece;
}
/**
* 如果存在棋子,则移除实际方格上的棋子。
*/
public void removePiece() {
if(piece != null)
piece = null;
}
/**
* 将棋子移动到实际方格上的另一个方格。
* @param square 要将棋子移动到的方格。
* @return 如果成功移动棋子,则返回true;否则返回false。
* 例如,移动失败的情况是当实际方格上的棋子不存在,换句话说,它是空的。
*
* 注意:显然,移动后的棋子将从实际方格中移除。
*/
public boolean movePiece(Square square) {
if(piece != null) {
square.setPiece(piece);
removePiece();
return true;
} else
return false;
}
英文:
You can add these useful methods to your Square
class in order to set the various pieces between all the squares you want.
/**
* @param piece to set on the actual square.
*/
public void setPiece(Piece piece) {
this.piece = piece;
}
/**
* Removes the actual piece on the square, if it exists.
*/
public void removePiece() {
if(piece != null)
piece = null;
}
/**
* @param square where to move the piece on the actual square.
* @return true if the piece were moved correctly, false otherwise.
* e.g. of a false return is when the piece on the actual square is not present, in other words, it is null.
*
* ATTENTION: Obviously the moved piece is removed from the actual square.
*/
public boolean movePiece(Square square) {
if(piece != null) {
square.setPiece(piece);
removePiece();
return true;
} else
return false;
}
专注分享java语言的经验与见解,让所有开发者获益!
评论