在Java中处理多个对象



我正在创造一款玩家(玩家对象)必须与许多僵尸(僵尸对象)战斗的游戏。战斗是模拟的,但用户可以在战斗期间设置防御。

我想要一个有效的方式来处理所有的僵尸。每个僵尸对象都有生命值和攻击等属性,它们分别影响玩家对象的攻击和生命值。当玩家用武器攻击特定的僵尸时,我希望能够执行specificZombie.health -= 20;

我的问题是,我不知道如何处理数十或数百个僵尸对象,每个对象都有自己的属性和单独的方法,如attack()或move()。我也不知道如何有效地初始化所有的僵尸,同时仍然能够调用特定的僵尸。我知道我可以使用循环,但是我如何命名所有的僵尸,以便它们可以被单独调用呢?

将它们放入列表或数组中,然后遍历列表/数组。每个僵尸可以通过列表或数组的索引来识别。

数组:

Zombie[] zombieArray = new Zombie[10];
for(int x=0; x<10; x++){
    Zombie z = new Zombie(--whatever your parameters are);
    zombieArray[x] = z;
}

列表:

List<Zombie> zombieList = new ArrayList<>();
    for(int x=0; x<10; x++){
        Zombie z = new Zombie(--whatever your paremeters are);
        zombieList.add(z);
    }

我的问题是我不知道如何处理十位或百位的僵尸对象,每一个都有自己的个体属性和单独的方法,如attack()或move()。我也没有知道如何在静止状态下有效地初始化所有僵尸能够调用特定的

=>您需要声明一个interface,但至少要声明一个abstract class僵尸。然后在实现时,你将有一个RapidAttackZombie,一个SlowRunningZombie,它扩展你的父类。强烈建议阅读此页

因为它们有一个共同的类,所以你可以放入任何存储集合:数组,数组列表,哈希表,任何你需要的。

在实现时,您将实现/重写attack()和move(),它们应该在抽象类中声明为抽象,或者可以有默认实现。

僵尸的初始化取决于你的关卡编辑器引擎输出结果,也就是说你必须声明:在X位置我想要一个ZombieType1,在y位置我想要一个ZombieType2,等等。

这不是10分钟如何开发一个完整的游戏,希望对大家有帮助!

最好有一个像

这样的数据结构
Map<String,List<zombieClass>>

String部分可以存储僵尸名称或类型。在你的地图中使用一个列表(ArrayList)来保存各种僵尸。在数组中,你会有调整大小的约束,而在ArrayList中,它是动态的,可以在运行时修改。在列表中,你可以有你的ZombieClass。

public class ZombieClass{
   private float health;
   private float damageCapability;
   //getters ans setters
}

创建包含僵尸的僵尸对象数组或列表

Class Zombie {
     private int health ;
     private int attack;
     public boolean died(){
       if(health < 0) return true;  
     }        
}

class Game {
    public static void main(String [] arg){
      List<Zombie> zombies = new ArrayList<Zombie>();
      for(int i  =0 ;i<10; i++)  
      zombies.add(new Zombie());
    } 
    // main game loop
    public void render(){
        for(int i =0; i<10; i++){
              // get each zombie and do whatever you want
        }     
    }
   }

您可以使用策略模式使您的Zombie类如下:

class Zombie {
   private AttackAction atackAction;
   private MoveAction moveAction;
   //other attributes of the zombie;
}

和你的AttackActionMoveAction接口如下:

interface AttackAction {
      public void attack();
}
interface MoveAction {
      public void move();
}

并且每个接口可以有两个实现。如AttackAction,一个是RealAttackAction,另一个是DummyAttackAction

class RealAttackAction implements AttackAction {
     public void action(){
         //do some real action
     }
}
class DummyAttackAction implements AttackAction {
     public void action(){
         //do some dummy action
     }
}

然后如果僵尸可以攻击,传递RealAttackAction的引用给它,如果它不能攻击,传递DummyAttackAction的引用。类似的事情可以用MoveAction接口完成。

你可以维护一个list(或map,如果每个僵尸有一个唯一的标识),让僵尸有效地处理它们!

最新更新