如何以有效的方式编写Javascript代码

时间:2017-03-21 04:57:16

标签: javascript

我有一个游戏,每当用户的分数为5,10或15时,它就会增加一个新的敌人。我随机选择并打算稍后更改的数字。

每当玩家达到其中一个分数时,我就能弄清楚如何添加新的敌人,但我必须为每个新分数制作一个新的布尔变量。如何在没有很多布尔语的情况下以更智能的方式编写相同的代码?

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 个答案:

答案 0 :(得分:2)

您可以创建一个lastScore变量来跟踪何时考虑对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
}

<小时/>

演示片段:

&#13;
&#13;
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
  }

})()
&#13;
<!-- 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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试一下:

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

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

但我建议将此问题移至CodeReview

答案 2 :(得分:1)

您可以将主题组织到对象中

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

// for each milestone, check and set milestoneMet