简体   繁体   English

javascript中刽子手游戏的机会数

[英]number of chances in hangman game in javascript

I just developed the hangman game in javascript. 我刚刚用javascript开发了刽子手游戏。 I want to add the number of chances the player is left with after giving a wrong answer. 我想在给出错误答案后添加玩家留下的机会数。 Let's say I want to give him a maximum of 7 chances. 假设我想给他最多7次机会。 I also want it to be displayed in the prompt. 我也希望它在提示中显示。

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);

Add a tries variable at the beginning, initialized with max chances. 在开头添加一个tries变量,用最大机会初始化。

Add a condition to your while loop, tries must be > 0 while循环中添加一个条件, tries必须> 0

Add it to the prompt : 将其添加到提示符:

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

If user don't guess a letter (figure this out yourself), decrement tries 如果用户不猜一封信(自己想出来),减少tries

At the end, check if user has succeeded (for example check if tries == 0 ) 最后,检查用户是否成功(例如检查是否tries == 0

If not, print that : (from http://www.berkeleyinternet.com/perl/node30.html ) 如果没有,请打印:(来自http://www.berkeleyinternet.com/perl/node30.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM