为什么外卖系统不起作用

时间:2017-02-15 18:42:25

标签: javascript html

我试图开发一款游戏,但系统并不总是有效(如果你有足够的黄金,它会测试它)。我无法理解它,它有时只能用更大的数字而不是全部。这是代码:

<!--- Game Of War: Ice Age -->

<!DOCTYPE html>
<html>
<head>
    <title>Game Of War: Ice Age</title>
</head>
<h4 id="gold"></h4>
<!-- Gain Gold -->
<img src="file:///C:/Users/Hacker/Pictures/GOW%20-%20Ice%20Age/goldButton.png" height="50" style="border: solid; 5px; black;" width="50" onclick="gainGold()"></img>

<!-- Barracks -->
<img src="file:///C:/Users/Hacker/Pictures/GOW%20-%20Ice%20Age/barracks.png" height="50" style="border: solid; 5px; black;" width="50" onclick="training()"></img>
<body>
<script type="text/javascript">
var gold = 1000000;
var goldPC = 1;

<!-- Troop Training Variables -->
var mammothCost = 5;
var dinosaurCost = 100;
var mammoths = 0;

function gainGold(){
    gold += goldPC;

}

function training(){
    train = prompt("Train Troops!")
    if (train == "Mammoths") {
        alert("Train Mammoths")
        amount = prompt("How Many Mammoths Do You Want To Train?")
        takeaway = mammothCost * amount;
        if (gold - takeaway <= 0){
            alert("You Do Not Have Enough Gold!")
            training()
        }
        mammoths = amount += mammoths

        gold -= takeaway


    }
}

<!-- SetIntervalSettings -->

setInterval(function renderGold (){
    document.getElementById('gold').innerHTML = "Gold: " + gold;
});


</script>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

我的猜测是prompt()函数返回一个字符串,这会混淆后面的数学运算。通过parseInt()运行结果将返回一个整数。

在自动变量类型转换方面,Javascript变得非常挑剔。

答案 1 :(得分:0)

mammoths = amount += mammoths;

所以你把猛犸象分配给金额,猛犸象增加了?你可能想要:

mammoths += +amount;

额外的加号会将它转换为数字(输入是字符串!)所以你可能还想在每个提示之前添加一个+ ...

val=+prompt("this string is converted to number!");

如果没有足够的黄金,你可能想停止执行:

        if (gold - takeaway <= 0){
            alert("You Do Not Have Enough Gold!")
            setTimeout(training);
            return;
        }

setTimeout只是一种造型......