gpt4 book ai didi

javascript - 如何高效地编写 Javascript 代码

转载 作者:行者123 更新时间:2023-11-29 10:06:06 25 4
gpt4 key购买 nike

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

我能够弄清楚每次玩家达到这些分数之一时如何添加新敌人,但我必须为每个新分数创建一个新的 bool 变量。如何在没有很多 bool 值的情况下以更智能的方式编写相同的代码?

素描.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;
}

最佳答案

您可以创建一个 lastScore 变量来跟踪何时考虑了对 score 的更改:

素描.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
}


演示片段:

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>

关于javascript - 如何高效地编写 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com