我正在制作国际象棋游戏并且出现错误,其中子类中的override方法并不总是覆盖父类。
更具体地说,关于temp2.setgetMoves(生成),但仅在第二次用于作品时。发生错误是因为我在父类中使用了继承,在子类中使用了覆盖方法。例如,在父类中,方法是:
abstract class Piece
{
String pieceType;
int pieceVal;
Panel piecePanel;
public Piece(String type, int value, Panel image)
{
image.BackgroundImage = (Image)(Properties.Resources.ResourceManager.GetObject(type));
pieceType = type;
pieceVal = value;
piecePanel = image;
}
public abstract List<Panel> setgetMoves(BoardGen board);
public virtual List<Panel> getMoves()
{
return null;
}
public String getType()
{
return pieceType;
}
public void setPanel(Panel newPanel)
{
piecePanel = newPanel;
}
public Panel getPanel()
{
return piecePanel;
}
public int getValue()
{
return pieceVal;
}
}
并且在子类中(作为一个例子,这是一个不完整的pawn类,它没有取件或en passant或者促销,但它是我到目前为止所得到的全部)代码是:
class Pawn : Piece
{
public List<Panel> possibleMoves;
public Pawn(string type, int value, Panel image) : base(type, value, image)
{
}
public override List<Panel> setgetMoves(BoardGen board)
{
possibleMoves = new List<Panel>();
foreach (Panel x in board.getPanels())
{
if (this.getType().Substring(0, 1).Equals("W"))
{
if (this.getPanel().Location.Y == 240 && ((x.Location.Y == this.getPanel().Location.Y - 40) || (x.Location.Y == this.getPanel().Location.Y - 80)) && (x.Location.X == this.getPanel().Location.X))
{
possibleMoves.Add(x);
}
else if((x.Location.Y == (this.getPanel().Location.Y - 40)) && (x.Location.X == this.getPanel().Location.X))
{
possibleMoves.Add(x);
}
}
else if (this.getType().Substring(0,1).Equals("B"))
{
if (this.getPanel().Location.Y == 40 && ((x.Location.Y == this.getPanel().Location.Y + 40) || (x.Location.Y == this.getPanel().Location.Y + 80)) && (x.Location.X == this.getPanel().Location.X))
{
possibleMoves.Add(x);
}
else if (x.Location.Y == this.getPanel().Location.Y + 40 && (x.Location.X == this.getPanel().Location.X))
{
possibleMoves.Add(x);
}
}
}
return possibleMoves;
}
public override List<Panel> getMoves()
{
return possibleMoves;
}
为什么它不能覆盖第二次的任何帮助都会非常有帮助。谢谢。
答案 0 :(得分:1)
由于来回的评论发现了可能的X-Y问题,我想帮助修复您的setPanel()
功能。希望这允许您重用正确类型的现有对象,并避免使用没有正确类型的全新对象(因此找不到正确的覆盖)。
您的构造函数更改了Panel参数的BackgroundImage
属性:
image.BackgroundImage = (Image)(Properties.Resources.ResourceManager.GetObject(type));
因此,当我们更改面板时,我们应该撤消之前与原始面板的交互,并为新面板重做它:
public void setPanel(Panel newPanel)
{
newPanel.BackgroundImage = piecePanel.BackgroundImage;
piecePanel.BackgroundImage = null;
piecePanel = newPanel;
}