当前位置: 动力学知识库 > 问答 > 编程问答 >

JSfiddle number guessing game

问题描述:

I have put together a number guessing game in Jsfiddle, im having trouble getting the random number stored into an array. i need to program to pic a random number and store it untill the number is either guessed or the game ends

here is my fiddle link https://jsfiddle.net/e64gt4sv/

any help would be appreciated thanks

HTML code:

<h1>The Guesssing Game</h1> Pick a number between 1 and 1000:

<input id="myAssumption" type="text" />

<input type="submit" id="byBtn" onclick="checkMyAnswer()" value="Click To See If your Correct" />

Js code:

 var numberOfSteps = 1;

function checkMyAnswer() {

var actual = Math.floor(Math.random() * 1000) + 1;

var myAnswer = document.getElementById("myAssumption").value; //getting user value

if (myAnswer < actual) { //checking less tha answer

alert("Guessed " + myAnswer + " too low");

numberOfSteps++;

} else if (myAnswer > actual) { //checking grater than answer

alert("Guessed " + myAnswer + " too high");

numberOfSteps++;

} else { //you got answer

alert("Guessed " + myAnswer + " Got it!!");

alert("It tool " + numberOfSteps + " steps");

}

}

网友答案:

I edited the jsfiddle. Check it out https://jsfiddle.net/e64gt4sv/3/.

var numberOfSteps = 1;
var actual = Math.floor(Math.random() * 1000) + 1;
var guesses = [];

function checkMyAnswer() {
    ...
}

Jeremy is right, each time you call the checkMyAnswer, you regenerated the actual number. Instead, if you set it outside the function, you can still get the value inside the function, but it will only be set each time the actual javascript file loads (meaning each time the page is loaded / reloaded).

Also, I added something to store each guess in an array. The array guesses is a global variable, and then when you call checkMyAnswer(), the value that the user inputted is added to the array by doing

var myAnswer = document.getElementById("myAssumption").value; //getting user value
guesses.push(myAnswer);
分享给朋友:
您可能感兴趣的文章:
随机阅读: