JavaScript - begginner questions - javascript

I have some difficulties with my first number guessing "game" in JavaScript. Can someone have a look and guide me what I did wrong? Started with that language not that long ago..
Function is assigned to one button
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start !
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check(guess) {
window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}

You designed your check function to have a guess passed to it but you are just calling it without doing so. So all your comparisons are against undefined.
You are also using window.prompt to get the actual guess. What you need to do is save the value returned from the prompt into a variable and then compare it. Check the snippet.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert(
"Guess number " + attemps + " is incorrect. The number is " + result + "."
);
}
if (attemps >= 3) {
window.alert(
"Sorry, you have run out of guesses! The number was " + hiddenNum
);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start

you need to assign the prompt
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value='guess'onClick="check()">Click to start!
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.

You should store the value from window.prompt. In your code, you just use guess in the parameter of the function as the value of window.prompt which is incorrect.
Syntax for window.promp:
result = window.prompt(message, default);
Also, I have shorten your codes and store the duplicate item in a function to make it a little bit less messy.
function smallcheck() {
let again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again.toUpperCase() == "N") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
console.log(guess)
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
smallcheck()
} else {
attempts++;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attempts + " is incorrect. The number is " + result + ".");
}
if (attempts >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
smallcheck()
}
}

Noticed you never declared 'result'. So I made that variable into a ternary operator to shorten up your code a little more. Also, I added template literals :)
let hiddenNum = Math.floor(Math.random() * 10);
//console.log(hiddenNum);
hiddenNum = hiddenNum;
let attempts = 0;
const nextRound = function () {
let again = window.prompt('Would you like to try again? Enter Y or N.');
if (again.toUpperCase() === 'N') {
window.alert("Thank's for trying. Later nerd");
window.close();
} else {
window.alert('Try to guess the new number, nerd.');
window.location.reload();
}
};
function check() {
let guess = prompt('Please enter the number between 1 and 10');
console.log(guess);
if (hiddenNum === guess) {
alert('Congratulations! You guessed correctly !');
nextRound();
} else {
attempts++;
let result = hiddenNum < guess ? 'lower' : 'higher';
alert(`Guess number is ${attempts} is incorrect. The number is ${result}.`);
}
if (attempts >= 3) {
alert(`Sorry, you have run out of guesses! The number was ${hiddenNum}`);
nextRound();
}
}
<div>
<input
id="box"
class="btn"
style="
display: inline-block;
border-radius: 2em;
box-sizing: border-box;
color: white;
background-color: blueviolet;
cursor: pointer;
"
type="button"
value="Guess"
onClick="check()"
/>Click to start !
</div>

Related

How to stop execution of a JavaScript program

So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();

Do loop keeps on repeating

So my alternative version of this code is in Java, the logic is fairly similar although in JavaScript the userinput is repeated infinitely rather than carrying until the user loses. This is my working Java code for reference:
int stop =0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
do {
int card;
int upcommingcard;
String userinput;
card= rand.nextInt(13)+1;
System.out.println("Card is "+card);
System.out.println("Higher or Lower?");
userinput = scan.next();
upcommingcard = rand.nextInt(13)+1;
if(!userinput.equalsIgnoreCase("H")&&(!userinput.equalsIgnoreCase("L"))){
System.out.println("Invalid Input ");
}
else if((userinput.equalsIgnoreCase("H")) && (upcommingcard > card)){
System.out.println("Correct!");
}
else if(userinput.equalsIgnoreCase("L") && upcommingcard < card){
System.out.println("Correct!l ");
}
else {
System.out.println("You lost it was " + upcommingcard);
stop=1;
}
}while (stop != 1);
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JavaScript - Not working
var max=13;
var min=1;
var stop=0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is "+card+"... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do{
if((userinput !="H")&&(userinput !="L")){
console.log("Invalid input");
}
else if((userinput ="H")&&(upcommingcard > card)){
console.log("Correct!");
}
else if((userinput ="L")&&(upcommingcard < card)){
console.log("Correct!");
}
else{
console.log("You lost, it was "+ upcommingcard);
stop=1;
}
}
while(stop !=1);
Just to mention also that it registers that the user's input is correct although it fails to continue and just keeps on spitting out the same output until the browser crashes.
EDIT: Thanks for the responses! the loop works perfectly now, my only issue is that the logic is a bit flawed since sometimes I Input 'L' for 8 and upcoming int is 10.. Dispite this I get the Incorrect response.
It's not that your console isn't updating, it's that you never exit your loop if the input is incorrect, and you never offer them the option to try again.
Thus if they are incorrect, the loop will never end, the console won't be updated, and they can't retry.
I would recommend changing the code to the following, to alert the user to try again.
var max = 13;
var min = 1;
var stop = 0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do {
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input!");
userinput = prompt("Card is " + card + "... Higher or lower?");
} else if ((userinput == "H") && (upcommingcard > card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
There are some points I want to make on this:
Your Java and Javascript code logic differs. You had the variables and input reads inside do while in Java but outside in Javascript.
As your prompt right now is outside the loop, it will keep having the same input value everytime and not asking for another one, and will carry on until it's a wrong guess, or forever if it's an invalid input. And the next point worsens your problem:
Your if comparison operators are invalid. What you did, as mentioned in the comments, is a data assignment to userinput and will always return correct
That being said, I corrected it below while adding alert popups instead of console.log only:
var stop = 0;
do {
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input");
stop = 1; //Currently stopping if having invalid input, you can remove this later
} else if ((userinput == "H") && (upcommingcard > card)) {
//Note the '==' above, and also the next one for comparing equal values
console.log("Correct!");
alert("Correct");
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
Now, do compare the JS snippet above with your working Java code you've posted. If you compare again with your JS code, you should be able see what I meant by having different logic.

Javascript: Alert message after loop ends

This is a simple login excercise for school. It is meant to give you 3 attempts to log in. I would like to make it so after the loop stops (the three attempts were used), it alerts the user that he has no remaining attempts and his account will be blocked.
Something like:
alert("You don't have any attempts left. Your account is now blocked);
Here is the loop I made:
var tries;
for (tries = 2; tries !== -1; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
Thanks in advance.
You where very close. I think this is what you want.
var tries;
for (tries = 2; tries >= 0; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if (tries == 0) {
alert("You don't have any attempts left. Your account is now blocked");
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
You can achieve this recursively. Just decrease the number of Tries everytime wrong username or password is entered.
var TRIES = 3;
function ask() {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
return alert("Welcome.");
}
if (TRIES > 0) {
alert("Incorrect username and/or password. You have " + TRIES + " attempt(s) left.");
TRIES -= 1;
ask()
} else {
alert("You don't have any attempts left. Your account is now blocked");
}
}
ask()
var tries;
for (tries = 0; tries < 3; tries++) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
if(tries == 2)
{
alert("You don't have any attempts left. Your account is now blocked);
}
}
Perhaps you could achieve this by doing the following:
for (var attemptsRemaining = 3; attemptsRemaining > 0; attemptsRemaining--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if(attemptsRemaining <= 1) {
alert("To many failed attempts. Your account is now blocked.");
}
else {
alert("Incorrect username and/or password. You have " + (attemptsRemaining - 1) + " attempt(s) left.");
}
}
}
The idea here is to add an additional check to see if the number of attemptsRemaining has reached one (or less, for robustness) at which point all attempts are expired. In this case, you display a popup to alert notifying the user that their account is now blocked.
Hope that helps!

JavaScript weird issue with else if statement

I'm making a game of Guess the Number, and I want to test if a variable guess is greater than a variable difficulty. difficulty has been taken from my HTML page, and it is not comparing correctly with guess.
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = document.getElementById("difficulty").value;
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = prompt("Enter your guess: ");
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
body {
font-family: sans-serif;
text-align: center;
animation: background 10s infinite;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
animation: heading 10s infinite;
}
button {
height: 48px;
width: 250px;
font-size: 24px;
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
Read this: key info
This code works, but I want something to happen: When the guess is greater than difficulty, I want to print "Please enter a number between 1-" + difficulty. However, when I change this code:
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
into this:
else if (guess < 1 || guess > difficulty) {...}
(EDIT: the above code is to find out if the guess is greater than difficulty)
then what happens is that EVERY guess except 1, difficulty and anything more than difficulty is alerted by Please enter a number.
How should I fix this?
You're comparing strings not numbers. Convert your strings into numbers.
else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
Better way: Convert it directly after input and...
guess = parseInt(prompt("Enter your guess: "));
...get the difficulty value as number
var difficulty = parseInt(document.getElementById("difficulty").value);
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = parseInt(document.getElementById("difficulty").value);
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = parseInt(prompt("Enter your guess: "));
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1 || guess > difficulty) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
change else if (guess < 1 || guess > parseInt(difficulty))
to else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
or change the type at the input
guess = parseInt(prompt("Enter your guess: "));
You can also use the built-in Number function. See how I fixed your code below:
difficulty = Number(difficulty);
guess = Number(guess);
Try applying this after your variables are declared and it should work!
Change to this should help:
else if (guess < 1 || guess > parseInt(difficulty)) {

Delete user input if higher than assigned variable javascript

I'm a new programmer learning HTML/CSS/Javascript, and was fiddling around with it until I came across a bug. I was making the computer guess my number (0-5), but then realized if I put in a number higher than 5, the website just crashes. Is there any way I can make it so that if the user puts in a number higher than 5 it will just delete it automatically? Or is that not Javascript. Thanks in advance :)
document.getElementById("guess").onclick=function() {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Try this :
document.getElementById("guess").onclick=function() {
if(document.getElementById("myNumber").value > 5) {
document.getElementById("myNumber").value = "";
alert("Please provide a number that is with in 0 to 5");
} else {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Than define a onchange function to check length:
document.getElementById("myNumber").onchange = function (ev){
try{
var target = document.getElementById("myNumber");
if(parseInt(target.value) > x) { // can throw exception, when given a non number
target.value="";
}
} catch(ex) {
alert('Not a number');
}
};
IMPORTANT:
You have a greater problem here: You are generating a random number, and then comparing it to input( that does not change). This is an infinite loop. Because this is a random operation, and you can hit same number more than once.
You need to generate your number first (before click event on 'guess' button), before clicking on quess button. Like so:
var luckyNumber = x;
var guesses=1;
document.getElementById("start").onclick=function(){ //init counters once
guesses=0;
x=Math.floor(Math.random()*6);
gotit = false;
}
document.getElementById("guess").onclick=function() { // guess as many times as you want
if(document.getElementById("myNumber").value==x) {
gotit=true;
}
guesses++;
if(gotit){
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
}
But if you want to computer to quess your number, than you need to limit number of guesses (add a counter), or it will hang eventualy.
I took this as a little challenge and just went ahead and re-did your little game. Hope this helps.
Demo here
(function (guess, tryy, message) {
var comp = function () {
return Math.floor(Math.random() * 6)
};
var number = comp();
var count = 0;
var test = function () {
var val = guess.value;
if (!Number.isNaN(val) && val >= 0 && val <= 5) {
switch (true) {
case val > number:
message.innerHTML = 'Your guess was too high!';
count++;
break;
case val < number:
message.innerHTML = 'Your guess was too low!';
count++;
break;
case val == number:
count++;
message.innerHTML = 'Congratulations you found the number! It took you ' + count + ' guesses';
//Reseting game here
setTimeout(function(){
count = 0;
number = comp();
guess.value = '';
message.innerHTML = 'Your game has been reset';
}, 2000);
break;
};
}
};
tryy.onclick = test;
guess.onkeyup = function (e) {
if (e.keyCode == 13) {
test();
}
}
})(document.getElementById('guess'), document.getElementById('tryy'), document.getElementById('message'));

Categories