说明开始
如果点击的方块上有棋子 (clickedSquare.getPiece()!= null)
确保游戏块属于当前玩家。您可以通过对 getPlayerType()
返回的 AbstractGamePiece
调用 getPiece()
方法来获取拥有的玩家。然后,您可以将其与 currentPlayerTurn
JailBreak
类成员进行比较。
如果点击方块上的棋子属于当前玩家 将选定的正方形设置为与单击的正方形相等 在选中的方块上调用select()方法显示黄色边框
说明结束
我已经找到了如何通过实现 select() 方法来突出显示部分,butt
我尝试了几种不同的实现,例如 AbstractGamePiece.getPlayerType()==currentPlayerTurn
,使用嵌套的 if
语句在 clickedSquare.getPiece()
上设置条件,以及其他一些我想不出来的实现。我似乎无法从抽象类中获得对 getPlayerType()
的引用。类中有一些预先编写的代码,就访问 AbstractGamePiece
而言似乎工作正常,例如
private void changePlayerTurn()
{
if (currentPlayerTurn == AbstractGamePiece.PLAYER_OUTLAWS)
currentPlayerTurn = AbstractGamePiece.PLAYER_POSSE;
else
currentPlayerTurn = AbstractGamePiece.PLAYER_OUTLAWS;
}
我觉得我做错了,但我似乎无法获得对 getPlayerType()
的引用。有一次,我创建了一个抽象类的新对象,但是构造函数需要 3 个参数,在这里不太合适。
支持代码:
abstract public class AbstractGamePiece
{
// All class members are provided as part of the activity starter!
// These two constants define the Outlaws and Posse teams
static public final int PLAYER_OUTLAWS = 0;
static public final int PLAYER_POSSE = 1;
// These variables hold the piece's column and row index
protected int myCol;
protected int myRow;
// This variable indicates which team the piece belongs to
protected int myPlayerType;
// These two strings contain the piece's full name and first letter abbreviation
private String myAbbreviation;
private String myName;
// All derived classes will need to implement this method
abstract public boolean hasEscaped();
// The student should complete this constructor by initializing the member
// variables with the provided data.
public AbstractGamePiece(String name, String abbreviation, int playerType)
{
myName = name;
myAbbreviation = abbreviation;
myPlayerType = playerType;
}
public int getPlayerType()
{
return myPlayerType;
}
public void setPosition (int row, int col)
{
myRow = row;
myCol = col;
}
public int getRow()
{
return myRow;
}
public int getCol()
{
return myCol;
}
public String getAbbreviation()
{
return myAbbreviation;
}
public String toString()
{
return (myName + " at " + "(" + myRow + "," + myCol + ")");
}
public boolean canMoveToLocation(List<GameSquare> path)
{
return false;
}
public boolean isCaptured(GameBoard gameBoard)
{
return false;
}
不加选择地突出显示部分的代码已成功实施。
private void handleClickedSquare(GameSquare clickedSquare)
{
if (selectedSquare == null)
{
selectedSquare=clickedSquare;
selectedSquare.select();
}
else if (selectedSquare == clickedSquare)
{
selectedSquare.deselect();
selectedSquare = null;
}
else
{
}
为什么我无法创建对 getPlayerType()
方法的引用?
答案 0 :(得分:0)
只需对 getPlayerType
类型的任何表达式调用 X
,其中 X 是 AbstractGamePiece 或其任何子类。例如,square.getPiece().getPlayerType()
。
方法引用是 Java 中的一个东西,绝对不是你想要的,你使用的词(“我无法创建对 getPlayerType 的引用”)意味着别的东西。方法引用看起来像 AbstractGamePiece::getPlayerType,并让您将调用该方法的概念传递给其他代码(例如,您可以创建一个连续调用某些代码 10 次的方法 - 因此该方法将作为参数, '一些代码' - 和方法引用是一种方法)。这不是您想要的,您只想调用该方法。这是通过 ref.getPlayerType()
完成的,其中 ref
是一个类型与 AbstractGamePiece 兼容的表达式。从上下文来看,clickedSquare.getPiece()
就是那个表达式。