gpt4 book ai didi

javascript - 如何阻止数字变成负数

转载 作者:行者123 更新时间:2023-11-28 05:14:34 26 4
gpt4 key购买 nike

我一直在“编写”一个游戏,其中涉及您收集资源,然后将这些资源花在一些东西上,然后创建更多该资源(当我完成时,它会更有趣)。

无论如何,我的问题是,在购买了太多可以创造更多资源的东西后,我无法找到一种方法来阻止资源数量变为负值。我需要某种方法来禁用该按钮。

我还想知道如何显示树木总数的百分比:)

为了方便起见,这里是代码...

<!DOCTYPE html>
<html>

<head>
<title>Game</title>
<script>
function collectSeeds() {
document.getElementById("Seeds").stepUp(1);
}

function plantTree() {
document.getElementById("Seeds").stepDown(10);
document.getElementById("Trees").stepUp(1);
}

function plantTrees10() {
document.getElementById("Seeds").stepDown(100);
document.getElementById("Trees").stepUp(10);
}
</script>
</head>

<body>
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" id="plantTree"
onClick="myTimer = setInterval(collectSeeds, 1000); plantTree();">Plant Tree</button>
<button
onClick="plantTrees10(); myTimer = setInterval(collectSeeds,100);">Plant Trees (10)</button>
<p>Seeds
<br/>
<input type="number" id="Seeds" disabled></input>
<p>Trees
<br/>
<input type="number" id="Trees" disabled></input>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>
</body>

</html>

最佳答案

  1. 按照 documentation 中的说明将最小值和最大值添加到字段中

  2. 您可能也想在某个地方留言。

  3. 最后在再次使用之前清除间隔 - 我重写了脚本,使其不显眼且通用。

var myTimer; // make global in scope
function collectSeeds() {
document.getElementById("Seeds").stepUp(1);
}

function plantTree(but) {
var nofSeeds = parseInt(but.getAttribute("data-nofseeds"), 10),
availableSeeds = parseInt(document.getElementById("Seeds").value, 10);
if (availableSeeds < nofSeeds) {
console.log(availableSeeds + " not enough, " + nofSeeds + " needed"); // give some message somewhere
return;
}
console.log(nofSeeds)
document.getElementById("Seeds").stepDown(10 * nofSeeds);
document.getElementById("Trees").stepUp(nofSeeds);
}

window.onload = function() {
var plantButtons = document.querySelectorAll(".plantTree");
for (var i = 0; i < plantButtons.length; i++) {
plantButtons[i].onclick = function() {
clearInterval(myTimer); // only have one timer running
myTimer = setInterval(collectSeeds, 1000);
plantTree(this);
}
}
}
<button onclick="collectSeeds()">Collect Seeds</button>
<button type="button" class="plantTree" data-nofseeds="1">Plant Tree</button>
<button type="button" class="plantTree" data-nofseeds="10">Plant Trees (10)</button>
<p>Seeds
<br/>
<input type="number" min="0" max="1000" id="Seeds" disabled />
</p>
<p>Trees
<br/>
<input type="number" id="Trees" disabled />
</p>
<div style="position: fixed; bottom: 0; right: 0;">Progress:</div>

关于javascript - 如何阻止数字变成负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41084150/

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