使用特定范围内的随机数猜测游戏

时间:2015-08-30 00:33:22

标签: javascript

该程序是一个高低猜谜游戏,其中从用户输入的特定范围生成随机数,并且用户必须猜测该随机数。

我想知道targetNumber或currentGuess是否有问题。程序似乎最初工作正常,但是当我输入currentGuess数字时,对话框要么再次弹出,要么告诉我太大的尝试,即使数字小于数字范围。

另外,我想让用户在输入targetMax和targetMin时无法输入十进制数字或其他字符。

var keepPlaying = true;
var currentGuess = 0;
var targetMax = null;
var targetMin = null;
var targetNumber = parseInt(targetMin + Math.random()*((targetMax - targetMin)+1));
var turnCounter = 1;

targetMax = prompt("Choose a whole number to set your maximum parameter.");
targetMin = prompt("Choose a whole number to set your minimum parameter.");
while (keepPlaying) {
    //get a valid guess
    do {
        currentGuess = prompt("Please guess a whole number between " +targetMin+ " and " +targetMax+ ".", "");
    }
    while (!((currentGuess > targetMin) && (currentGuess <= targetMax)))
    //handle the guess
    if (currentGuess == targetNumber) {
        alert("YOU'RE RIGHT!!!\n\nIt took you " + turnCounter + " tries to guess the number.");
        keepPlaying = confirm("Do you want to play again?")
        if (!keepPlaying) {
            break; //not needed, just wanted to show how to exit a loop early
        }
        //reset game
        targetNumber = parseInt(targetMin + Math.random()*((targetMax-targetMin)+1));
        turnCounter = 0;
    } else if (currentGuess > targetNumber) {
        alert("Too big, try again.");
    } else if (currentGuess < targetNumber) {
        alert("Too small, try again.");
    } else { //should be inaccessible
        alert("There was an error parsing your guess.");
    }
    //update counter
    turnCounter++;
}
document.write("<h1>Thank you for using my <font color='red'>AWESOME</font>, web-based guessing game.</h1>");

1 个答案:

答案 0 :(得分:0)

Math.random()返回0到1之间的随机浮点数。正如您所确定的那样,您需要将其相乘以获得两个其他数字之间的随机值。但是,在您的代码中,您在之前执行此操作您已提示用户输入这些值。结果,您乘以null,结果为0.

如果在提示用户输入值之后移动该行,则应获得预期的结果。