java宠物小精灵,简单的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");
}
}
口袋妖怪測試員
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
}
}
我確實意識到我還沒有在輪流中實現速度方面,因為我正試圖讓它工作.
添加靜態到戰斗功能,就像在main中一樣.
此外,你不能在主要使用charizard和blastoise.非靜態變量不能用于靜態函數.您需要在`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);
}
您還可以創建新的PokemonTester并使用它的變量:
public static void main(String[] args){
PokemonTester tester=new PokemonTester();
Pokemon.battle(tester.charizard, tester.blastoise);
}
您可以了解有關靜態成員here的更多信息
總結
以上是生活随笔為你收集整理的java宠物小精灵,简单的Java口袋妖怪扑灭模拟器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php pdf 加密 签名 时间戳,在现
- 下一篇: java操作mongodb_Java操作