我目前正在使用JavaScript进行雷区游戏。我在游戏结束时遇到了问题。我有三个难度级别,因此很容易给用户45个猜测,中间40个猜测和高级是35个猜测。但是,出于某些原因,当我将它设置为中间/高级时,它会继续进行45次猜测,而不是应该停止的位置。
在我花了很长时间看着它并改变不同的东西,比如变量的名称和编辑代码。猜测工作正常,所以每个猜测实际上算作1猜测现在他们计算为3.代码现在停在35。
var number_of_guesses = 0;
var maximum_guesses = 45;
var intermediate_guesses = 40;
var advanced_guesses = 35;
var number_of_hits = 0;
var number_of_misses = 0;
var element = opener.document.getElementById("easy");
if (element.checked === true)
{
maximum_guesses = 45;
}
var intermediate = opener.document.getElementById("intermediate");
if (element.checked === true)
{
intermediate_guesses = 40;
}
var advanced = opener.document.getElementById("advanced");
if (element.checked === true)
{
advanced_guesses = 35;
}
number_of_guesses++;
if (number_of_guesses > maximum_guesses)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
number_of_guesses++;
if (number_of_guesses > intermediate_guesses)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
number_of_guesses++;
if (number_of_guesses > intermediate_guesses)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
有人可以告诉我: a)如何使每个猜测计数为1而不是3? b)如何正确设置每个难度?
答案 0 :(得分:1)
尝试让所有三个选项设置maximum_guesses
变量,而不是针对不同的困难设置三个不同的变量。然后检查一个变量。
var number_of_guesses = 0;
var maximum_guesses = 45;
var number_of_hits = 0;
var number_of_misses = 0;
// notice the missing intermediate_guesses and advanced_guesses vars
var element = opener.document.getElementById("easy");
if (element.checked)
{
maximum_guesses = 45;
}
var intermediate = opener.document.getElementById("intermediate");
if (intermediate.checked)
{
maximum_guesses = 40; // changed this to maximum_guesses
}
var advanced = opener.document.getElementById("advanced");
if (advanced.checked)
{
maximum_guesses = 35; // changed this to maximum_guesses
}
number_of_guesses++; // you only need this once
if (number_of_guesses > maximum_guesses)
{
window.alert("Sorry, you have run out of guesses!");
return;
}
编辑:您还有一个错字,当您检查是否检查了中间和高级复选框时,您仍在检查easy元素。
编辑2 :此外,在您的代码中,您正在调用number_of_guesses++;
三次,这就是每次猜测计数3次的原因。对于他们只计算一个,你只需要第一个。每次检查时,数字都会保持不变,因此您不需要增加三次。
编辑3 :在我的代码中,请注意我删除了您选中的if语句中的=== false
部分是否已选中复选框。