文本冒险游戏战斗系统

时间:2015-07-20 19:55:03

标签: java oop tags

我试图为一个文本冒险游戏创建一个战斗系统,该游戏产生随机健康游泳池的随机敌人,但每个生成的敌人似乎没有自己的健康游泳池,而是“主要”的敌人健康变量不断递增受到攻击时因此输出显示负面健康的新敌人而不是新的健康池。 到目前为止我的代码:

 public class Combat{

    //enemy variables
    private int enemyHealth = (int) (Math.random()*75);
    private int maxEnemyDamage = 25;
    private String enemyName;
    //player variables
    private int playerHealth = 100;
    private int playerDamage = 50;
    //health potion variables
    private int numHealthPotions = 3;
    private int healAmount = 30;
    private int dropChance = 50; //percentage

    public String getEnemyName() {
        String[] enemy = {"Zombie", "Witch", "Hell Dog", "Skeleton"};
        int i = (int) (Math.random() * 4);
        this.enemyName = enemy[i];
        return this.enemyName;
    }
    public int getEnemyHealth(){
        return enemyHealth;
    }
    public void enemyAppears(){
        String enemy = getEnemyName();
        System.out.println("A " + enemy + " has appeared with " + enemyHealth + " health.");
    }
    public void attack() {
        int damageTaken =(int) (Math.random() * maxEnemyDamage);
        int damageDealt =(int) (Math.random() * playerDamage);
        enemyHealth -= damageDealt - getEnemyHealth();
        playerHealth -= damageTaken;
        System.out.println("You strike for " + damageDealt);
        System.out.println("You have been hit for " + damageTaken);
        System.out.println("You have " + playerHealth + " hp left.\n The enemy has " + enemyHealth + " hp left.");
        if (playerHealth < 0){
            System.out.println("You died.");
            System.exit(15);
        }

调用这些方法的主要方法:

 Combat combat = new Combat();
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to the dungeon");
    boolean running = true;
    GAME:
    while(running){

        combat.enemyAppears();

        System.out.println("Choose:\n1. To Attack \n2. To Heal \n3. To Run");
        String choice = input.next();
        if(choice.equals("1")) {
            combat.attack();
        } else if (choice.equals("2")){
            combat.heal();
        } else {
            combat.run();
            break;
        }
    }
}

我想将敌人作为对象产生(我只是随机生成名称)因为我认为这会解决这个问题,但我无法弄明白我的构造函数需要什么。我可以猜到为什么我的代码不起作用,但我也无法修复它。是否有一个简单的构造函数或setter可以解决这个问题?

1 个答案:

答案 0 :(得分:1)

您只有变量enemyHealth。如果你希望每个敌人拥有它自己的健康变量,你将不得不使用int[]。除了真正的OOP方法之外,还有将敌人作为对象实施。小注意:你可以使用类java.util.Random来创建随机数。该类还提供了在给定范围内直接创建随机int的方法。