【问题标题】:Basics of manipulating variables in different classes在不同类中操作变量的基础知识
【发布时间】:2016-04-09 01:21:45
【问题描述】:

我已经进行了相当多的挖掘,但似乎无法找到我正在寻找的答案,我可能问错了问题,因为我很菜鸟。

无论如何,我正在尝试构建一个简单的口袋妖怪风格游戏进行练习,但我似乎无法在战斗活动期间改变对手或玩家的生命值..

我有,所以你选择 1. 使用以下代码进行攻击:

if(select == 1){
            System.out.println("You strike at the raccoon!");
            System.out.println("You deal " + play1.atk + " damage!");
            Math.subtract(raccoon1.hp, play1.atk);

Math.subtract 类只是

public static int subtract(int x, int y){    
        return (x-y);           
    }

它从我从一个“对手”类构建的对象中提取 raccoon1.hp 的位置:

public class Opponent { 
    public int hp = 5;
    public int def = 0;
    public int atk = 1;
} 

播放器的设置方式相同。

我确定我只是想念和/或做一些愚蠢的事情,但对新程序员的任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: java class variables


    【解决方案1】:
    Racoon1.hp = Math.subtract(raccoon1.hp, play1.atk)
    

    你必须设置返回值等于raccoon.hp,否则返回值没有意义。

    【讨论】:

      【解决方案2】:

      这是一个正确的面向对象编程的问题。与其从变量的角度考虑它,不如从方法的角度考虑它。不要尝试直接操作变量,尝试通过类的操作来操作。

      你的情况……

      if(select == 1){
                  System.out.println("You strike at the raccoon!");
                  System.out.println("You deal " + play1.atk + " damage!");
                  //reduce the health by the current attack value of the player
                  racoon.reduceHealth(play1.getAttackValue());
      

      在您的Pokemon 类中,或者您在创建新口袋妖怪时实例化实例的任何类中,创建这样的方法...

      public void reduceHealth(int attackValue){
          this.hp = this.hp - attackValue;
      }
      

      在您的 Player 类中,或者您在创建新 Player 时实例化实例的任何您命名的类中,创建这样的方法...

      public int getAttackValue(){
          return this.atk;
      }
      

      这样,对对象执行的操作由其自己的类完成,而不是其他类。获取信息时,创建返回所需信息的方法。操作对象的变量时,使用对象的方法进行操作。

      【讨论】:

      • 非常感谢您的回答,这真的帮助我理解了“this”的工作原理。
      • 没问题!祝你的游戏好运!
      【解决方案3】:

      我建议你做类似的事情

      public class Opponent {
          public int hp = 5;
          public int def = 0;
          public int atk = 1;
          public void attack(Opponent target){
              target.hp -= atk;
          }
      }
      

      以后你可以简单地做

      Opponent player = new Opponent ();
      Opponent badGuy = new Opponent ();
      player.attack(badGuy);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-04
        • 1970-01-01
        • 2014-04-16
        • 2018-05-25
        相关资源
        最近更新 更多