I was wondering if someone can help point me in the direction to use the .push() function to store a user's guesses in a higher or lower guessing game? And how would I be able to prevent duplicate guesses? I have the for loop commented because it would break my webpage. Thanks for any help!
let valid_input = false;
let number, input;
while(!valid_input){
input = window.prompt("Enter a positive number!");
number = Number(input);
if(number != NaN && number > 0){
valid_input = true;
}
}
let num = Math.floor(Math.random() * number) + 1;
console.log(num);
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
let totalGuess = [];
/*for(i = 0; guess != num; i++){
totalGuess.push(i);
}*/
if(guess == num) {
message.innerHTML = `You got it! Good Guess! </br> It took you ${totalGuess.indexOf(guess) + 2} to get it right and your guesses were ${totalGuess}`
console.log(`It took you ${totalGuess.indexOf(guess) + 1} guesses to get it right...`);
}
else if(guess <= 0){
message.innerHTML = "That number is out of range, try again."//Guess is negative
}
else if(guess > number){
message.innerHTML = "That number is out of range, try again."// Guess is higher than the range of number they inputed
}
else if (guess > num) {
message.innerHTML = "No, you guessed too high. Try a lower number!"// guessed too high
}
else if(guess < num){
message.innerHTML = "No, you guessed too low. Try a higher number!"// Guessed too low
}
else{
message.innerHTML = "Please enter a number!" //Guessed any non number
}
console.log(totalGuess);
}
You could use a Set data structure to store each guess. Set, unlike Array, ignores duplicate elements:
let totalGuess = new Set();
...
totalGuess.add(guess);
Always when there is a valid guess you just can push it to your array
totalGuess.push()
To check if the value is already in your array you can use Arrays includes method in combination with the Logical Not Operator !.
When the array is not including the number then push it.
if(!totalGuess.includes(SOMENUMBER)){
totalGuess.push()
}
The snippet shows how it works
let valid_input = false;
let number, input;
let totalGuess = [];
while (!valid_input) {
input = window.prompt("Enter a positive number!");
number = Number(input);
if (number != NaN && number > 0) {
valid_input = true;
}
}
document.getElementById('btn').addEventListener('click', do_guess)
const num = Math.floor(Math.random() * number) + 1;
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (guess == num) {
message.innerHTML = `You got it! Good Guess! </br> It took you ${totalGuess.length+1} to get it right and your guesses were ${totalGuess}`
console.log(`It took you ${totalGuess.length+ 1} guesses to get it right...`);
console.log(totalGuess);
totalGuess = [];
} else if (guess <= 0) {
message.innerHTML = "That number is out of range, try again." //Guess is negative
} else if (guess > number) {
message.innerHTML = "That number is out of range, try again." // Guess is higher than the range of number they inputed
} else if (guess > num) {
message.innerHTML = "No, you guessed too high. Try a lower number!" // guessed too high
if (!totalGuess.includes(guess)) {
totalGuess.push(guess);
}
} else if (guess < num) {
message.innerHTML = "No, you guessed too low. Try a higher number!" // Guessed too low
if (!totalGuess.includes(guess)) {
totalGuess.push(guess);
}
} else {
message.innerHTML = "Please enter a number!" //Guessed any non number
}
}
<input id="guess"></input>
<button id="btn">Click</button>
<div id="message"></div>
Related
I'm programming a game where a random number from 1-20 is generated, the user guesses the number. If he guesses wrong, his score is deducted by 1 everytime (score starts at 20). When score reaches 0, the game is over.
My difficulty is getting the game to keep going while score is above 0 and stop when it's 0.
At first, I put in the while loop within the click event:
//to generate a random number
const random_number = Math.trunc(Math.random() * 20) + 1;
//display random (only for testing purpose, not in the actual game)
document.querySelector('.number').textContent = random_number;
//every player starts with 20. Everytime they guess wrong it gets deducted by 1
let score = 20;
//player input their number. Check for player input against random number generated above
document.querySelector('.check').addEventListener('click', function () {
//I put while loop here so that when score is 0 it is game over but game continues as long as score>0
while (score > 0) {
//take the player's guess
const guess = Number(document.querySelector('.guess').value);
if (!guess) {
//if it's blank
document.querySelector('.message').textContent = 'No number';
//if guess is correct, break out of the loop.
} else if (guess === random_number) {
document.querySelector('.message').textContent = 'correct number';
break;
} else {
score--; //score gets deducted by one
document.querySelector('.score').textContent = score; //the score displayed on the html is set to score in script
if (guess > random_number) {
document.querySelector('.message').textContent = 'too high';
} else if (guess < random_number) {
document.querySelector('.message').textContent = 'too low';
}
break; //once it's deducted, should break out of while loop
}
}
if ((score = 0)) {
document.querySelector('.message').textContent = 'game over';
}
});
It only works once, so if I click "check" again, the game does doesn't continue.
So I tried to put while loop outside of the event:
const random_number = Math.trunc(Math.random() * 20) + 1;
//display random (only for testing purpose, not in the actual game)
document.querySelector('.number').textContent = random_number;
//every player starts with 20. Everytime they guess wrong it gets deducted by 1
let score = 20;
//putting while loop outside of event this time
while (score > 0) {
document.querySelector('.check').addEventListener('click', function () {
//take the player's guess
const guess = Number(document.querySelector('.guess').value);
if (!guess) {
//if it's blank
document.querySelector('.message').textContent = 'No number';
//if guess is correct, break out of the loop. Script works well up to here
} else if (guess === random_number) {
document.querySelector('.message').textContent = 'correct number';
//I want to put a break here but it says illegal break
} else {
score--; //score gets deducted by one
document.querySelector('.score').textContent = score; //the score displayed on the html is set to score in script
if (guess > random_number) {
document.querySelector('.message').textContent = 'too high';
} else if (guess < random_number) {
document.querySelector('.message').textContent = 'too low';
}
//I want to put a break here but it says illegal break
}
});
break;
}
if ((score = 0)) {
document.querySelector('.message').textContent = 'game over';
}
This time I can play the game multiple times, but I cannot stop the while loop from running if a guess is wrong so the score ends up getting to -1 on the very first wrong guess. I try to put the break statements like before but it keeps saying 'illegal breaks'. Not sure where I'm supposed to put the breaks?
No need for a while loop. Evaluate if the score is 0 at in the else block inside your event listener. You only want to evaluate the score again whenever you subtract from it.
At the start, evaluate if the .guess field's value is empty. Doing Number('') will produce 0. That means that even if I would enter the number 0, I would get the message No number.
document.querySelector('.check').addEventListener('click', function() {
const value = document.querySelector('.guess').value;
const guess = Number(value);
if (value === '') {
document.querySelector('.message').textContent = 'No number';
} else if (guess === random_number) {
document.querySelector('.message').textContent = 'correct number';
} else {
score--; //score gets deducted by one
document.querySelector('.score').textContent = score;
if (score === 0) {
document.querySelector('.message').textContent = 'game over';
} else if (guess > random_number) {
document.querySelector('.message').textContent = 'too high';
} else if (guess < random_number) {
document.querySelector('.message').textContent = 'too low';
}
}
});
I am having the user be prompted to enter a number which will be the maximum number that a random number will be in between. The code works if they enter a number when prompted the first time and the code picks a random number between 1 and the maximum number entered. If the user does not enter a number (i.e. enters a letter or symbol), I want the user to be prompted again to enter a number. I also need to add code to ensure the number entered is positive
let num_guess = 0
let tries = []
let max_num = Number(prompt("Enter a maximum number:"));
if (isNaN(max_num)) {
// need to reprompt user to enter a valid maximum number and make sure that the user will keep being prompted until a positive number is entered
}
let num = Math.floor(Math.random() * max_num) + 1;
console.log(max_num)
console.log(num)
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (tries.includes(guess)) {
message.innerHTML = "That number has already been guessed, try again"
} else if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
} else if (guess <= 0 || guess > max_num) {
message.innerHTML = 'That number is not in range, try again.';
} else if (guess > num) {
message.innerHTML = "No, try a lower number.";
num_guess++
tries.push(guess)
} else if (guess < num) {
message.innerHTML = "No, try a higher number.";
num_guess++
tries.push(guess)
} else if (guess == num) {
num_guess++
tries.push(guess)
message.innerHTML = "You got it! It took you " + num_guess + " tries and your guesses were " + tries + ".";
}
}
You can put your prompt in a do ... while loop
let max_num;
do {
max_num = Number(prompt("Enter a maximum number:"));
} while (isNaN(max_num))
let num = Math.floor(Math.random() * max_num) + 1;
console.log({max_num, num})
You can make a function that calls for the input. If the input is invalid, you call the function again from inside itself.
let num_guess = 0;
let tries = [];
let max_num = 0;
// Add this function to keep prompting user until a valid input is entered.
function getInput() {
var inputValue = Number(prompt("Enter a maximum number:"));
if (isNaN(inputValue)) {
return getInput();
}
else {
return inputValue;
}
}
max_num = getInput();
let num = Math.floor(Math.random() * max_num) + 1;
console.log(max_num)
console.log(num)
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (tries.includes(guess)) {
message.innerHTML = "That number has already been guessed, try again"
} else if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
} else if (guess <= 0 || guess > max_num) {
message.innerHTML = 'That number is not in range, try again.';
} else if (guess > num) {
message.innerHTML = "No, try a lower number.";
num_guess++
tries.push(guess)
} else if (guess < num) {
message.innerHTML = "No, try a higher number.";
num_guess++
tries.push(guess)
} else if (guess == num) {
num_guess++
tries.push(guess)
message.innerHTML = "You got it! It took you " + num_guess + " tries and your guesses were " + tries + ".";
}
}
I'm trying, and failing, to check for whether or not a 5-digit integer is a palindrome or not using javascript. I have gotten the code to correctly check for 5-digit strings (not integers yet). That part should be relatively easy to figure out.
My main question: Am I doing the structure for using functions in javascript? If so, how can I get the function call to work properly? It just quits the program upon receiving the desired input.
Code is as follows:
<script type="text/javascript">
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, '');
var len = userInput.length;
for (var i = 0; i < len/2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
while (counter < 10){
if (userInput.length == 5){
if (pandindrome(userInput) == true){
document.write("The input is a palindrome!");
}
else if (pandindrome(userInput) == false){
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
counter++;
}
else if (userInput.length != 5){
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
palindrome(userInput);
}
}
</script>
I have tested your code, everything works fine!
FIY, I set a variable isPalindrome to store the return value from the function palindrome. Then you can use it directly inside if statement, instead of compare to true.
var userInput;
var counter = 0;
function palindrome(userInput) {
var re = /[^A-Za-z0-9]/g;
userInput = userInput.toLowerCase().replace(re, "");
var len = userInput.length;
for (var i = 0; i < len / 2; i++) {
if (userInput[i] !== userInput[len - 1 - i]) {
return false;
}
}
return true;
}
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
var isPalindrome = palindrome(userInput);
while (counter < 10) {
if (userInput.length == 5) {
if (isPalindrome) {
document.write("The input is a palindrome!");
} else {
document.write("The input is not a palindrome! Try again!");
userInput = window.prompt(
"Please enter a 5-digit, numerical palindrome: "
);
isPalindrome = palindrome(userInput);
}
counter++;
} else if (userInput.length != 5) {
alert("The input you entered was not 5-digits! Please try again!");
userInput = window.prompt("Please enter a 5-digit, numerical palindrome: ");
isPalindrome = palindrome(userInput);
}
}
Hello i am very new to javascript and have been trying to make a random number guessing game. I think i almost got it except there is one thing i cant figure out. Everytime i run it i have to type in my number twice and it also only returns Lower no matter what number i type in.
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
{
while (randomNumber != readline())
if (readline() < randomNumber)
{
print("Lower");
}
else if (readline() > randomNumber)
{
print("Higher");
}
else if (readline() == randomNumber)
{
print("Good Job");
}
}
Your problem is you are calling readline multiple times per iteration of your while loop. Here I have stored the value of readline into a variable and use that to test:
var randomNumber = Math.floor((Math.random() * 100) + 1);
print("I have thought of a random number in the range of 1 to 100. Guess!");
var hasGuessedCorrectly = false;
while (!hasGuessedCorrectly)
{
var guess = readline();
if (guess < randomNumber)
{
print("Lower");
}
else if (guess > randomNumber)
{
print("Higher");
}
else if (guess == randomNumber)
{
print("Good Job");
hasGuessedCorrectly = true;
}
}
How can I continue prompting a user for a valid response using if... else if statements? My script currently works once, but then breaks:
var enterNum = prompt("Please enter a number between 1 and 100", "");
if (isNaN(enterNum)){
enterNum = prompt("You did not enter a valid number. Please try again", "")
}
else if (enterNum < 1 || enterNum >100){
enterNum = prompt("Your number is not between 1 and 100. Please try again", "")
}
else{
document.write("Your number is ", enterNum)
}
Thanks in advance!
var enterNum = prompt("Please enter a number between 1 and 100", "");
while(isNaN(enterNum) || enterNum < 1 || enterNum >100) {
enterNum = prompt("You did not enter a valid number. Please try again", "")
}
document.write("Your number is ", enterNum)
var valid = false;
var msg = "Please enter a number between 1 and 100";
while(!valid){
var enterNum = prompt(msg, "");
if (isNaN(enterNum)){
msg = "You did not enter a valid number. Please try again";
}
else if (enterNum < 1 || enterNum >100){
msg = "Your number is not between 1 and 100. Please try again";
}
else{
valid = true;
document.write("Your number is ", enterNum)
}
}
There are a bunch of other ways to do a similar thing, somewhat depending on style. This went for readability. Could also eliminate the valid variable and simply have while(true) then break once the input is correct. The document.write could also be after the while.
You can't with only if/else. Use a loop. Example:
var enterNum = prompt("Please enter a number between 1 and 100", "");
while(true)
{
if (isNaN(enterNum)){
enterNum = prompt("You did not enter a valid number. Please try again", "")
}
else if (enterNum < 1 || enterNum >100){
enterNum = prompt("Your number is not between 1 and 100. Please try again", "")
}
else
break;
}
document.write("Your number is ", enterNum)
use a while loop instead
http://help.dottoro.com/ljqepqhd.php#dowhile
or
http://help.dottoro.com/ljqepqhd.php#while
I hate javascript so my syntax is probably off but something like:
var isValid = false;
var message = "Please enter a number between 1 and 100";
while(isValid == false)
{
var enterNum = prompt(message, "");
if (isNaN(enterNum)){
isValid = false;
message = "You did not enter a valid number. Please try again";
}
else if (enterNum < 1 || enterNum >100){
isValid = false;
message = "Your number is not between 1 and 100. Please try again";
}
else{
isValid = true;
document.write("Your number is ", enterNum)
}
}
Using a do/while loop might be a little neater.