Java
1public class Hero{ 2 String name; 3 int hp; 4 int atk; 5 boolean def; //防御状態かどうか 6 boolean esc; //逃走状態かどうか 7 Hero(){ 8 this.hp = 100; 9 this.atk = 15; 10 } 11 void act(){ 12 System.out.println("1 攻撃 2防御 3逃走"); 13 int commandSelect = new java.util.Scanner(System.in).nextInt(); //コマンドの入力 14 switch (commandSelect){ 15 case 1: 16 attack(); //アタックメソッドの呼び出し 17 break; 18 case 2: 19 defence(); //ディフェンスメソッドの呼び出し 20 break; 21 case 3: 22 escape(); //逃走メソッドの呼び出し 23 break; 24 } 25 } 26 void attack(){ 27 int damage = (int)((Math.random()+1)*this.atk); //自分の攻撃力×1.0^1.9のダメージを生成 28 e.hp -= damage; 29 System.out.println("あなたは"+e.name+"に"+damage+"ダメージ与えた!!\r\n残りの体力は"+e.hp); 30 } 31 void defence(){ 32 def = true; 33 } 34 void escape(){ 35 int a = (int)(Math.random()*10); //二分の一で逃げれるかどうか 36 if (a >= 4 ){ 37 esc = true; 38 }else{ 39 esc = false; 40 } 41 } 42}
Java
1public class Enemy{ 2 String name; 3 int atk; 4 int hp; 5 Enemy(){ 6 this.hp = 200; 7 this.atk = 5; 8 this.name = "スライム"; 9 } 10 void act(){ 11 int a = new java.util.Random().nextInt(2)++; 12 switch (a){ 13 case 1: 14 attack(); 15 break; 16 case 2: 17 grin(); 18 break; 19 } 20 } 21 void attack(){ 22 int damage = (int)((Math.random()+1)*this.atk); //自分の攻撃力×1.0^1.9のダメージを生成 23 h.hp -= damage; 24 if (h.def == true){ 25 damage = damage/2; 26 } 27 System.out.println(tihs.name+"の攻撃"+damage+"のダメージを食らった!!"); 28 } 29 void grin(){ 30 System.out.println(this.name+"はにやにやしている"); 31 } 32} 33``````Java 34public class BattleSystem{ 35 public static void main(String[] args){ 36 Hero h = new Hero(); 37 Enemy e = new Enemy(); 38 System.out.println("あなたの名前を入力してください"); 39 h.name = new java.util.Scanner(System.in).nextLine(); 40 System.out.println(e.name+"が現れた!!\r\n君はどうする?\r\n現在の体力:"+h.hp); 41 while (true){ //ここからバトルのループのwhile 42 h.act(); //主人公のターンでの行動 43 e.act(); //敵のターンでの行動 44 if (h.hp == 0){ //バトルの結果表示のif 45 System.out.println("GAME OVER"); 46 break; 47 }else if (h.esc == true){ 48 System.out.println("逃亡に成功した"); 49 break; 50 }else{ 51 System.out.println("YOU WIN"); 52 break; 53 } 54 } //ここまでwhileループ 55 } 56}
簡単なゲームを作っているのですが
上記のそれぞれのactメソッドにはswitchでattackメソッドなどコマンド入力で選べるようにしてあるのですがHeroクラスのattackメソッドではEnemyクラスのhpフィールドといったふうにそれぞれがそれぞれのフィールドにアクセスしたいのですがアクセスすることができません。どうすればいいでしょうか?よろしくお願いします
追記 すみませんほかのクラスを記入するの忘れていました、、、
具体的にはHeroクラスのattackメソッドでe.hpを使えない、といった感じです。追加しましたので改めてよろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/04/23 07:07