gpt4 book ai didi

java - 使用继承和多态来解决一个常见的游戏问题

转载 作者:IT老高 更新时间:2023-10-28 20:39:01 24 4
gpt4 key购买 nike

我有两个类;让我们称他们为食人魔和巫师。 (所有字段都是公开的,以使示例更易于输入。)

public class Ogre
{
int weight;
int height;
int axeLength;
}

public class Wizard
{
int age;
int IQ;
int height;
}

在每个类中,我都可以创建一个名为battle() 的方法,该方法将决定如果食人魔相遇并且食人魔或巫师遇到巫师,谁将获胜。这是一个例子。如果食人魔遇到食人魔,则较重的人获胜。但如果重量相同,则斧头较长者获胜。

public Ogre battle(Ogre o)
{
if (this.height > o.height) return this;
else if (this.height < o.height) return o;
else if (this.axeLength > o.axeLength) return this;
else if (this.axeLength < o.axeLength) return o;
else return this; // default case
}

我们可以为巫师制作类似的方法。

但是如果巫师遇到食人魔怎么办?我们当然可以为此制定一种方法,例如仅比较高度。

public Wizard battle(Ogre o)
{
if (this.height > o.height) return this;
else if (this.height < o.height) return o;
else return this;
}

我们会为遇到巫师的食人魔制作一个类似的。但是,如果我们必须在程序中添加更多字符类型,事情就会失控。

这就是我卡住的地方。一个明显的解决方案是创建一个具有共同特征的 Character 类。食人魔和巫师从角色继承并扩展它以包含定义每个特征的其他特征。

public class Character
{
int height;

public Character battle(Character c)
{
if (this.height > c.height) return this;
else if (this.height < c.height) return c;
else return this;
}
}

有没有更好的方法来组织类(class)?我已经查看了策略模式和中介模式,但我不确定它们中的任何一个(如果有的话)在这里有什么帮助。我的目标是达到某种常见的战斗方法,这样如果食人魔遇到食人魔,它会使用食人魔对食人魔的战斗,但如果食人魔遇到巫师,它会使用更通用的战斗方式。此外,如果相遇的角色没有共同特征怎么办?我们如何决定谁会赢得一场战斗?

编辑:很多很棒的回应!我需要消化它们并找出最适合我的情况。

最佳答案

visitor pattern “是一种将算法与其操作的对象结构分离的方法”。

对于你的例子,你可以有

class Character {
boolean battle(BattleVisitor visitor) {
return visitor.visit(this);
}
}

class Ogre extends Character {..}
class Wizard extends Character {..}
class Dwarf extends Character {..}

interface BattleVisitor {
boolean visit(Ogre character);
boolean visit(Wizard character);
boolean visit(Dwarf character);
}

class OgreBattleVisitor implements BattleVisitor {
private Ogre ogre;
OgreBattleVisitor(Ogre ogre) { this.ogre = ogre; }
boolean visit(Ogre ogre) {
// define the battle
}

boolean visit(Wizard wizard) {
// define the battle
}
...
}

每当发生战斗时:

targetChar.battle(new OgreBattleVisitor(ogre));

为巫师和矮人以及任何出现的东西定义一个访客实现。另请注意,我将 visit 方法的结果定义为 boolean(赢或输),而不是返回赢家。

因此,在添加新类型时,您必须添加:

  • 访问者处理新类型的方法。
  • 处理新类型战斗的实现

现在,事实证明,如果“Ogre vs Wizard”==“Wizard vs Ogre”,您将有一些重复的代码。我不知道是不是这种情况——例如,根据谁先出手,可能会有所不同。此外,您可能希望为“与食人魔的沼泽战斗”与“与食人魔的村庄战斗”提供完全不同的算法。因此,您可以创建一个新的访问者(或访问者的层次结构)并在需要时应用适当的访问者。

关于java - 使用继承和多态来解决一个常见的游戏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2768748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com