我试图制作一个战斗模拟器,在其中我提示用户输入攻击部队,防御部队,以及通过使用JavaScript中的prompt()函数来杀死率。当我将代码写入HTML文档进行测试时,它无法提示用户。我确实意识到我现在可以通过使用原型来更好地编写代码,但这个想法只有在完成代码后才能找到我。我为下面代码中的格式怪异道歉。我需要帮助调试的代码如下。你能帮我弄清楚代码有什么问题吗?
<!DOCTYPE html>
<html>
<head>
<title> Battle Simulator AMUN </title>
</head>
<body>
<SCRIPT LANGUAGE="JAVASCRIPT">
var armyAttackingIn;
var armyAttackingNumber;
var armyDefendingIn;
var armyDefendingNumber;
//declares variables
armyAttackingIn=prompt("How many forces are in the attacking army?");
armyAttackingNumber = parseInt(armyAttackingIn);
armyDefendingIn=prompt("How many forces are in the defending army?");
armyDefendingNumber = parseInt(armyDefendingIn);
//gets the number of armies
var morale;
//makes morale a factor
var moraleYesOrNo = prompt("Shall morale be a factor? Y/N");
if (moraleYesOrNo=="Y"||moraleYesOrNo=="Yes"||moraleYesOrNo="yes") {
morale = ((defender/attacker)*3+.3)*100;
if (morale>=100) {
morale = 100;
}
}
else {
morale = 100;
};
//defines what morale is.
var killRateDefense = parseInt(prompt("Insert the defensive kill rate. Default is 70.","70");)/100;
var killRateOffense = parseInt(prompt("Insert the offensive kill rate. Default is 60.","60");)/100;
var battle = function() {
//defines the kill rate
var armyAttackingLeft = armyAttackingNumber - (armyDefendingNumber*killRateDefense*(100/morale));
var defendingArmyLeft = armyDefendingNumber - (armyAttackingNumber*killRateOffense*(morale/100));
//gets armies left
if(armyAttackingLeft<0) {
armyAttackingLeft = 0
};
if(armyDefendingLeft<0) {
armyDefendinigLeft = 0
};
//makes the minimum troops left 0
}
battle();
document.write("The attacking army was " + armyAttackingIn + "men strong" <br>");
document.write("The defending army was " + armyDefendingIn + "men strong" <br>");
document.write("The morale was " + morale + "/%" <br>);
document.write("The defensive kill rate was " + killRateDefensive + "/% and the offensive kill rate was " + killRateOffensive + "/%" <br>);
document.write("There were " + (armyAttackingNumber-armyAttackingLeft) + " attackers killed" <br>);
document.write("There were " + (armyDefendingNumber-armyDefendingLeft) + " defenders killed" <br>);
document.write("There are " + armyAttackingLeft + " attacking soldiers that survived and there are " + armyDefendingLeft + " defending soldiers that survived.");
if (armyAttackingLeft == 0) {
document.write(<br>"The attacking force was demolished. Everyone died.");
};
if (armyDefendingLeft == 0) {
document.write(<br>"The defending force was demolished. Everyone died.");
};
//writes the document
</SCRIPT>
</body>
</html>
答案 0 :(得分:0)
您之前是否使用过浏览器的Javascript控制台?您可能会发现它是一个有用的调试工具。
只有prompt()调用的明显错误:你的代码中有一个额外的分号,并且在参数列表之后导致了这个错误“Uncaught SyntaxError:missing”。
正确的行是:
parseInt(prompt("Insert the defensive kill rate. Default is 70.","70"))/100;
您的if语句缺少'='。您目前正在进行分配而不是检查,并且它正在抛出错误。它应该是:
if (moraleYesOrNo=="Y"||moraleYesOrNo=="Yes"||moraleYesOrNo=="yes") {
你的一个变种中还有一个拼写错误:
armyDefendinigLeft = 0