一个方法是否可以在条件为真时阻止另一个方法被调用?

huangapple go评论72阅读模式
英文:

Is it possible for a method to stop another method from being called if a condition is true?

问题

我被分配了一个任务,需要编辑一个游戏并添加不同的元素,其中之一是在与对象交互时恢复玩家生命值,我已经完成了这部分。

接下来的步骤是在玩家生命值达到最大值(100)时停止此功能。

我的想法是创建一个带有条件的方法(如果条件为真,则停止我的生命增加方法的运行/调用)。

示例:

 private void checkMaxLife() {
    if (playerLife==100) {
      //停止 addLife 方法的运行
    }
  }

这是否可行,语法是什么?

编辑:
这是修复方法,在碰撞方法中添加 playerLife < 100。

private void foodAddLife() {
    //检查食物碰撞
    for (int i = 0; i < food.length; ++i) {

      if (playerLife < 100 && food[i].getX() == player.getX() && food[i].getY() == player.getY()) {

        //发生碰撞
        ++playerLife;
      }
    }
}
英文:

I've been given an assignment to edit a game and add different elements to it, one was the ability to restore player life when interacting with an object which I have completed.

The next step is to stop this from working when the players life is max (100).

My idea then was to create a method with a condition (and if it is true, stop my life adding method from working / being called.)

Example:

 private void checkMaxLife() {
    if (playerLife==100) {
      //Stop method addLife from working
    }
  }

Would this be possible and what is the syntax?

EDIT:
This was the fix, added playerLife < 100 to the collision method instead.

private void foodAddLife() {
    //Check food collisions
    for (int i = 0; i &lt; food.length; ++i) {

      if (playerLife &lt; 100 &amp;&amp; food[i].getX() == player.getX() &amp;&amp; food[i].getY() == player.getY()) {

        //We have a collision
        ++playerLife;
      }
    }

答案1

得分: 1

看起来你不需要 checkMaxLife,只需在方法 addLife 中使用属性 playerLife

private void addLife() {
    if (playerLife < 100) {
        playerLife++;  // 或者任何其他值
    }
}

通过这两个方法,你可以看出其中一个是无用的。

private boolean isFullLife() {
    return playerLife >= 100;
}

private void addLife() {
    if (!isFullLife()) {
        playerLife++;  // 或者任何其他值
    }
}
英文:

It seems you don't need checkMaxLife, just use the attribute playerLife in the method addLife

private void addLife() {
    if (playerLife &lt; 100) {
        playerLife++;  // or whatever value
    }
}

With 2 methods, you see that one is useless

private boolean isFullLife() {
    return playerLife &gt;= 100;
}

private void addLife() {
    if (!isFullLife()) {
        playerLife++;  // or whatever value
    }
}

答案2

得分: 0

你只需在玩家生命值为MAX_VALUE时返回该函数。

private void addLife() {
    if (playerLife >= 100)
        return;
    // 做你需要做的事情
}
英文:

You just return the function when player life is MAX_VALUE.

private void addLife() {
    if(playerLife&gt;=100)
        return;
    // Do Whatever you need to do
}

huangapple
  • 本文由 发表于 2020年9月26日 17:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64076120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定