javascript中刽子手游戏的机会数

时间:2015-02-19 13:58:12

标签: javascript

我刚用javascript开发了刽子手游戏。我想在给出错误答案后添加玩家留下的机会数。让我们说我想给他最多7次机会。我也希望它在提示中显示。

var words = ["THE GRAND BUDAPEST HOTEL","MATRIX RELOADED","GLADIATOR","BEN HUR","SAVING PRIVATE RYAN"];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
for (var i = 0; i < word.length; i++) 
{
    answerArray[i] = "_";
    if (word[i] === " ")
    {
        answerArray[i] = "  ";
    }
}
var remainingLetters = word.length;
while( remainingLetters > 0)
{
    alert(answerArray.join(" "));

    var guess = prompt("Guess a letter or click cancel to stop playing.");
    guess = guess.toUpperCase();

    if ( guess === null)
        {
            break;
        }

    else if(guess.length !== 1)
        {
            alert("Please enter a single letter.");
        }
    else  
        {
                for (var j = 0; j < word.length; j++) 
            {
                if (word[j] === guess)
                {
                    answerArray[j] = guess;
                    remainingLetters--;
                }


            }

        }
}

alert(answerArray.join(" "));
alert("Good job! The answer was " + word);

1 个答案:

答案 0 :(得分:0)

在开头添加tries变量,初始化为最大机会。

while循环添加条件,tries必须为&gt; 0

将其添加到提示符:

"Guess a letter or click cancel to stop playing." + tries + " remaining"

如果用户不猜一封信(自己想出来),请递减tries

最后,检查用户是否成功(例如检查是否tries == 0

如果没有,请打印:(来自http://www.berkeleyinternet.com/perl/node30.html

var hangString = "";
hangString += " ________     \n";
hangString += "|        |    \n";
hangString += "|        0    \n";
hangString += "|       /|\\  \n";
hangString += "|       / \\  \n";
hangString += "|             \n";