简单的Java口袋妖怪扑灭模拟器

Bri*_*ian 3 java

我写了一个类来创建和战斗口袋妖怪,但我无法弄清楚如何在测试器类中调用battle方法来测试我写的类.

我的任务是编写和测试模拟两个神奇宝贝之间的战斗的模拟.每个神奇宝贝都有一个健康值,一个力量值和一个速度值.运行状况,强度和速度值作为参数传递给构造函数.这些值最初必须介于1到300之间,并且最初应为非零值.完成游戏的总体思路是两个口袋妖怪将在模拟中相互"战斗",口袋妖怪轮流攻击.(具有最高速度值的那一个每轮首先出现)攻击宠物小精灵的力量将从"攻击者"的生命值中减去.

public class Pokemon{
  private int health;
  private int strength;
  private int speed;

/**
* Constructs the pokemon
* @Require:
*    health is an integer greater than or equal to 1 but less than or equal to 300
*    strength is and integer greater than or equal to 1 but less than or equal to 300
*    speed is an integer greater than or equal to 1 but less than or equal to 300
*/
public Pokemon(int health, int strength, int speed){
  assert health >= 1;
  assert health <= 300;
  assert strength >= 1;
  assert strength <= 300;
  assert speed >= 1;
  assert speed <= 300;

  this.health = health;
  this.strength = strength;
  this.speed = speed;
}

public void battle(Pokemon pokemon1, Pokemon pokemon2){
  do{
    System.out.println(pokemon1+" begins the fight against "+pokemon2);
    pokemon2.health = pokemon2.health - pokemon1.strength;

    System.out.println(pokemon1 +" does "+ pokemon1.strength +" damage to "+
    pokemon2 +" and "+ pokemon2 +" has "+ pokemon2.health +" left.");

    pokemon1.health = pokemon1.health - pokemon2.strength;

    System.out.println(pokemon2 +" does "+ pokemon2.strength +" damage to "+ 
    pokemon1 +" and "+ pokemon1 +" has "+ pokemon1.health +" left.");

  }while(pokemon1.health >= 1 || pokemon2.health >= 1);
  if(pokemon1.health < 1)
    System.out.println(pokemon1 +" has lost the fight");
  else
    System.out.println(pokemon2 +" has lost the fight");
  }
}
Run Code Online (Sandbox Code Playgroud)

口袋妖怪测试员

public class PokemonTester{
  private Pokemon charizard;
  private Pokemon blastoise;
  private Pokemon venusaur;

public PokemonTester(){
   charizard = new Pokemon(100,50,50);
   blastoise = new Pokemon(150,25,150);
   venusaur = new Pokemon(300,10,100);
 }

public static void main(String[] args){
  Pokemon.battle(charizard, blastoise); //will not compile
 }
}
Run Code Online (Sandbox Code Playgroud)

我确实意识到我还没有在轮流中实现速度方面,因为我正试图让它工作.

Pio*_*zmo 6

添加staticbattle功能,就像在main.

此外,您不能使用charizardblastoisemain.非静态变量不能用于静态函数.您需要在`main中创建局部变量

public static void main(String[] args){
    Pokemon charizard = new Pokemon(100,50,50);
    Pokemon blastoise = new Pokemon(150,25,150);
    Pokemon.battle(charizard, blastoise);
}
Run Code Online (Sandbox Code Playgroud)

您还可以创建新的PokemonTester并使用它的变量:

public static void main(String[] args){
    PokemonTester tester=new PokemonTester();
    Pokemon.battle(tester.charizard, tester.blastoise);
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处了解有关静态成员的更多信