需要一些关于Javascript数字猜谜游戏的建议

时间:2015-07-26 03:24:18

标签: javascript

这是我的第一篇文章,所以对我来说很容易哈哈!我正在开发一个数字游戏,提示用户猜测1到100之间的随机数。我遇到问题的部分是告诉用户他们之前是否已经猜到了一个数字。我自己一直在玩它,例如,如果我提交10,然后10再次它会说我重复猜测(这应该是什么)。如果我第三次说10,它并没有告诉我我重复猜测而是数字太低了(它应该说我再次重复猜测)。以下是澄清的问题:https://jsfiddle.net/k1d8awf6/2/

var random = Math.ceil(Math.random()*100);
var guessList = new Array();

var guess = prompt("Hello user, I'm thinking of a number between 1-100. What is it?");
guessList.push(guess);

while (guess != random) {    
    for (i = 0; i < guessList.length-1; i++) {
        if (guess == guessList[i]) {
        guess = prompt("You already guessed this number. Try again.");     
        }
    }
    if (guess > random) {
        guess = prompt("Your guess is too high! Try again.");
        guessList.push(guess);
    }
    if (guess < random) {
        guess = prompt("Your guess is too low! Try again.");
        guessList.push(guess);
    }
    if (guess == random) {
       alert("Nice job! You guessed the correct number! It took you " + guessList.length + " tries!"); 
    }
}

1 个答案:

答案 0 :(得分:2)

如果你应该做其他事情,那你就是在做什么。此外,您可以使用indexOf函数而不是循环遍历元素。例如:

var random = Math.ceil(Math.random()*100);
var guessList = new Array();

var guess = prompt("Hello user, I'm thinking of a number between 1-100. What is it?");
while (guess != random) {
    if (!guess) {
        // The user cancelled or entered 0, just cancel the game
        return;
    } else if (guessList.indexOf(guess) >= 0) {
        // User already guessed this number
        guess = prompt("You already guessed this number. Try again.");
    } else {
        // User hasn't guessed this number, store their guess then display whether they're too high or too low
        guessList.push(guess);

        if (guess > random) {
            guess = prompt("Your guess is too high! Try again.");
        } else if (guess < random) {
            guess = prompt("Your guess is too low! Try again.");
        }
    } 
}

// The guess is correct when we exit the loop
alert("Nice job! You guessed the correct number! It took you " + (guessList.length + 1) + " tries!");

有关indexOf的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

如果用户输入&#39; 0&#39>,您可能还想结束游戏。或取消对话框:)

修改

修改了一些逻辑错误,在这里更新了小提琴:https://jsfiddle.net/k1d8awf6/8/