简单的Java口袋妖怪扑灭模拟器
发布时间:2020-12-15 08:44:47 所属栏目:Java 来源:网络整理
导读:我写了一个类来创建和战斗口袋妖怪,但我无法弄清楚如何在测试器类中调用battle方法来测试我写的类. 我的任务是编写和测试模拟两个神奇宝贝之间的战斗的模拟.每个神奇宝贝都有一个健康值,一个力量值和一个速度值.运行状况,强度和速度值作为参数传递给构造函数
我写了一个类来创建和战斗口袋妖怪,但我无法弄清楚如何在测试器类中调用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); Pokemon blastoise = new Pokemon(150,150); Pokemon.battle(charizard,blastoise); } 您还可以创建新的PokemonTester并使用它的变量: public static void main(String[] args){ PokemonTester tester=new PokemonTester(); Pokemon.battle(tester.charizard,tester.blastoise); } 您可以了解有关静态成员here的更多信息 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |