[英]Javascript clicker game
I've recently got myself into making a clicker game in javascript, but as expected, I ran into a little problem.我最近开始用 javascript 制作一个点击游戏,但正如预期的那样,我遇到了一个小问题。
When I have for example 5 coins per second, it goes a lot faster, like i have 20 or 30 coins per second.例如,当我每秒有 5 个硬币时,它会快得多,就像我每秒有 20 或 30 个硬币一样。 There isn't a specific pattern to this, eg that it goes 2x faster or 3x faster, pretty random.
对此没有特定的模式,例如它快 2 倍或 3 倍,非常随机。
These are parts of code involving coins, any feedback would be appreciated这些是涉及硬币的代码部分,任何反馈将不胜感激
var coinsPS = 0;
..................
setInterval(function renderCoinsPS() {
document.getElementById("coinsPS").innerHTML = "Coins per second: " + coinsPS;
})
....................
function getCoinsPS() {
if (coins >= 50) {
coinsPS += 10;
coins -= 50;
} else {
alert("Sorry, you don't have enough coins.")
}
........................
setInterval(function coinPS() {
coins += coinsPS;
}, 1000)
}
Edit: Here is the entire code if it helps:编辑:如果有帮助,这里是整个代码:
<!DOCTYPE Html>
<head>
<title>Coin Clicker</title>
</head>
<body>
<h1>Coin Clicker</h1>
<h3 id="coins"></h3>
<h4 id="coinsPS"></h3>
<button onclick ="gainCoin()">Coin</button>
<button onclick ="getCoinsPS()">1 Coin Per Second</button>
<script>
var coins = 0;
var coinsPS = 0;
var coinsPC = 1;
function gainCoin() {
coins += coinsPC;
}
setInterval(function renderCoins() {
document.getElementById("coins").innerHTML = "Coins: " + coins;
})
setInterval(function renderCoinsPS() {
document.getElementById("coinsPS").innerHTML = "Coins per second: " +
coinsPS;
})
function getCoinsPS(){
if (coins >= 50){
coinsPS += 1;
coins -= 50;
}
else{
alert("Sorry, you don't have enough coins.")
}
setInterval(function coinPS(){
coins += coinsPS;
}, 1000)
}
</script>
</body>
You add add multiple intervals without cancelling the old one.您添加多个间隔而不取消旧的间隔。 So cancel the old one before you create a new one.
所以在创建新的之前取消旧的。
var addInterval;
function getCoinsPS() {
if (coins >= 50) {
coinsPS += 10;
coins -= 50;
} else {
alert("Sorry, you don't have enough coins.")
}
if (addInterval) window.clearTimeout(addInterval)
addInterval = setInterval(function coinPS() {
coins += coinsPS;
}, 1000)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.