我试着开发了一款游戏,但系统并不总是有效的(它会测试你是否有足够的金币)。我无法理解它,它只适用于有时较大的数字,但不适用于所有数字。下面是代码:
<!--- 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>发布于 2017-02-16 02:48:31
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只是一个样式的东西...
发布于 2017-02-16 02:50:53
我猜测可能是prompt()函数返回了一个字符串,这会混淆后面的数学运算。通过parseInt()运行结果将返回一个整数。
当涉及到自动变量类型转换时,Javascript变得非常挑剔。
https://stackoverflow.com/questions/42257604
复制相似问题