FrederikBA
FrederikBA

Reputation: 15

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

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 < food.length; ++i) {

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

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

Upvotes: 0

Views: 51

Answers (2)

Kaviarasu
Kaviarasu

Reputation: 58

You just return the function when player life is MAX_VALUE.

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

Upvotes: 0

azro
azro

Reputation: 54168

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

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

With 2 methods, you see that one is useless

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

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

Upvotes: 1

Related Questions