Limpuls
Limpuls

Reputation: 876

Execute if statement only once when conditional is met

I have a function like so:

function foundGold(ptX, ptY) {
  var gridX = Math.floor(ptX / 36);
  var gridY = Math.floor(ptY / 36);
  if(mapArray[gridY][gridX] == 3) {
    return true;
  }
}

if(foundGold(boatPosX + 36, boatPosY)) { goldAmount+= 1; gold.innerHTML = goldAmount; }

It check my game character position and if it steps on the certain part of the array, than means that the condition is true and the function keeps running. So in this case I check in another function if foundGold is true and if it is, give user some gold. The problem is that while the condition is true, the player will keep getting endless amount of gold, unless he steps off from that position and and condition is no longer true.

Now how can I make this so that even if user keeps standing in one spot and the condition is true for the whole time, he won't keep getting gold and the function will execute only once, no matter for how long the condition is true?

I don't want to keep adding +=1 to goldAmount all the time while the condition is true, only once. Is it possible to exit it after one run or anything like that?

Upvotes: 1

Views: 2248

Answers (1)

vox
vox

Reputation: 837

If you don't want to modify your original array, you can store the information elsewhere. If it's only used in the one function, I'd just store it on the function itself. Since you're using primitives, you can easily flatten it to a single key, combined with the playerId:

function foundGold( ptX, ptY, playerId ) {

    const gridX = Math.floor( ptX / 36 );
    const gridY = Math.floor( ptY / 36 );

    if ( mapArray[ gridY ][ gridX ] === 3 ) {

        // Gold exists; check if player already found it
        const key = `_memory;${playerId};${gridX};${gridY}`;
        if ( this[ key ] ) return false;
        this[ key ] = true;

        return true;

    }

    return false;

}

Alternatively, you can have a 3-dimensional array.

Upvotes: 1

Related Questions