6

How do I make an if statement run only once. I am making a game in javascript and once the users score is 5 I want to add a new enemy into the array. The problem I am having is once the if statement is true it keeps adding new enemies over and over until the whole screen is covered with enemies. I want it to add only 1 new enemy when score is 5 then another when score is 10 and so on. I cannot think of a way to accomplish this. Thank You.

Sketch.js

   var score = 0;

   //3 three enemies once game starts
   function StartingEnemies() { 
      for (var i = 0; i < 2; i++) {
        enemies[i] = new BasicEnemy();
      }
   }


   //add new enemies into the array
   function spawnNewEnemies() {
     enemies.push(new BasicEnemy());
   }


   if (score == 5) {
     spawnNewEnemies();
   }
2
  • 1
    are you incrementing the score later Commented Mar 20, 2017 at 5:12
  • show us what have you done in spawnNewEnemies();
    – Maharshi
    Commented Mar 20, 2017 at 5:13

7 Answers 7

6
var addNew=true;
if (score == 5 && addNew) {
  spawnNewEnemies();
  addNew=false;
}

If you are running the code inside of a function, make sure that addNew is declared somewhere that it will persist between calls.

4

You need a simple latch. Try adding a boolean variable called isEnemyAddedAtFive and set it to false as it's default value.

var isEnemyAddedAtFive = false;

Then at your check point test this value and if not latched, act and latch:

if( score == 5 && !isEnemyAddedAtFive ) {
    addEnemy();
    isEnemyAddedAtFive = true;
}

Good Luck!

3
if ( score != 0 && score % 5 == 0) {
     spawnNewEnemies();
}

Try this one.

2
  • 1
    If this is incorporated into the scoring method then it is the correct answer. As you would only need to make the check once when the score changes. It would also eliminate the need for the isAdded check and would reduce checking the score on every cycle. Commented Mar 20, 2017 at 5:23
  • Agree with answer, but you should describe what this code is doing. Some folks might not know about the mod operator Commented Mar 20, 2017 at 5:58
2

This is a little more complex than you are currently coding. There are a few ways you could interpret this. Firm your requirements.

Do you want to only add an enemy if the score is divisible by 5... Meaning only when the score ends in 0 or 5 (5, 10, 15, 20, etc):

If (score % 5 == 0) {
  enemies.push(new BasicEnemy());
}

Otherwise you may need to track a total score and a level/segmented score representing the score since the program last took action on the game.

// Initialization
var totalScore = 0;
Var currents core = 0;

// Game event loop
while (player.lifeState > 0) {

// Check current score is 5 or more on every iteration of the game event loop
if (currentScore >= 5) {
// Handle score
spawnNewEnemies();
// Update scoring
totalScore += currentScore;
// Reset currentScore (or not if you want to do more stuff in the level before resetting but this may change the above logic)
currentScore = 0;
}

Your logic will get more complex as you as more features. The best first step is to define clear requirements before coding as one retirement may influence how you implement another

1

//post this snippet at some top level of your code.
var onceMap = {};

function once(key) {
  if (onceMap[key]) {
    return false;
  } else {
    onceMap[key] = true;
    return true;
  }
}
var score = 10;

//do this in your task function
function task() {
  if (score >= 5 && once("score5")) {
    console.log("score 5 action");
  }
  if (score >= 10 && once("score10")) {
    console.log("score 10 action");
  }
}
task();
task();
task();

1
  • Seems I'm too late Commented Mar 20, 2017 at 5:29
1

What comes first to mind after seeing your code is that:

  • It should be

    for (var i = 0; i < 3; i++)
    

    for 3 enemies

  • You are calling your code (i.e .js file multiple times). This means that score resets to 0 each time it is called and score==5 condition occurs multiple times.

Solution:

Change your logic such that the .js file is called only once and store the score for the entire duration of the game.

Hope this helps

0
 !( score != 0 && score % 5 == 0) || spawnNewEnemies()
//how it functions
 !true || run()

I'll have to admit this is a bit abstract. But what this does is if the score is true, it forces into false and runs spawnNewEnemies. If the score isn't true. It forces into true and don't run the false condition.

However id suggest a function edit:

var spawnNewEnemies =scored=> !(scored !=0 && scored%5===0) || enemies.push(new BasicEnemy());
spawnNewEnemies(score);

SpawnNewEnemies now takes a score parameter. But also is an arrow function that can be used for quick one-liners. Since score is a dependency, itll run on that condition. If the base score is 0 and also divisible by 5, the condition returns true, but the "bang" (!) operator forces it into false, and executes the new enemies. If the score isn't divisible by five, itll return false but the bang flips it and will not return the OR false arguement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.