How to write Javascript code efficiently

I have a game where every time the user types 5, 10 or 15, he adds a new enemy. The numbers that I randomly chose and intend to change later.

I managed to figure out how to add new enemies every time the player reaches one of these points, but I have to make a new boolean variable for each new point. How can I write this same code in a smarter way without a lot of gates?

Sketch.js

var addEnemyAt5= true; //boolean I have to create over and over
var addEnemyAt10 = true;
var addEnemyAt15 = true;
var score = 0;

if (score == 5 && enemyScore5) {
  console.log("new enemy at 5");
  addEnemyAt5 = false;

} else if (score == 10 && enemyScore10) {
  console.log("new enemy at 10");
  addEnemyAt10 = false;

} else if (score == 15 && enemyScore15) {
  console.log("new enemy at 15");
  addEnemyAt15 = false;
}

      

HUD.js

this.scoreUpdate = function() {
  score += 5;
}

      

+3


source to share


3 answers


You can create a variable lastScore

to track changes in score

:

Sketch.js:

var lastScore = 0
var score = 0

if (score > lastScore) {
  if (score === 5) {
    console.log("new enemy at 5")
  } else if (score === 10) {
    console.log("new enemy at 10")
  } else if (score === 15) {
    console.log("new enemy at 15")
  }
  lastScore = score
}

      

HUD.js:

this.scoreUpdate = function() {
  score += 5
}

      




Demo snippet:

var lastScore = 0
var score = 0

setInterval(function SketchDotJS() {

  if (score > lastScore) {
    if (score === 5) {
      console.log("new enemy at 5")
    } else if (score === 10) {
      console.log("new enemy at 10")
    } else if (score === 15) {
      console.log("new enemy at 15")
    }
    lastScore = score
  }

}, 10)

;(function HUDDotJS() {

  this.scoreUpdate = function() {
    score += 5
  }

})()
      

<!-- Boilerplate code to get the demo to work -->
<button onclick="scoreUpdate()">Increase <var>score</var> by 5</button>
<pre><var>score</var> = <span id="score">0</span></pre>
<script>setInterval(function(e){score===+e.textContent||(e.textContent=score)},10,document.getElementById('score'))</script>
      

Run codeHide result


+2


source


Try maybe:

createEnemyAtScore = {
    5: true,
    10: true,
    15: true
};
var score = 10;

if (createEnemyAtScore[score]) {
    // create your enemy... or whatever..
}

      



but I would suggest moving this CodeReview question

+1


source


You can organize a topic into an object

var milestoneMet = {
    5: false,
    10: false,
    15: false
};

// for each milestone, check and set milestoneMet

      

+1


source







All Articles