Javascript random number generator with function() - javascript

alright, so I have an assignment here where I need to generate a random number but its not working so well. I've done it before but things aren't working for me; basically even tho we are generating rnadom numbers it needs to show the user to go up or down if the guess isn't correct and at least one random time the nuber the user guesses is supposed to be correct. Apparently i have things misplaced but my coding is right. I'm trying to figure out how to get this working and an explanation why i was wrong because i'm still learning a lot. Thank you.
<html>
Number guessing game
Welcome to number guessing game. Please make a guess between 1 and 10 to find the hidden number
Make a guess
// 1. Generate a number between 1 and 10 - done
// 2. Create a function named guess so that when button is clicked function is executed. - done
// 2.1. Inside the function get the value user entered from the input box. - done
// 2.2. Inside the function check if the number is smaller than randomNumber, if so display "Go up" in the div with result id. - done
// 2.3. Inside the function check if the number is bigger than randomNumber, if so display "Go down" in the div with result id. - done
// 2.4. Inside the function check if the number is equal to randomNumber, if so display "You guessed right!" in the div with result id. - done
//If working correctly your page should allow the player to guess the correct number by getting instructions from your code.
function guess() {
var userInput = parseInt($("#guess").val());
console.log(userInput);
var randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(randomNumber);
if (randomNumber == userInput) {
$("#result").html(`you guess correctly!`);
console.log(result);
} else if (randomNumber < userInput) {
$("#result").html(`higher!`);
} else {
$("#result").html(`lower!`);
}
}
</script>

Related

How do I output a new random number to an HTML doc(via innerText) in JavaScript?

I am doing a simple math game in HTML and JavaScript for school, this is just a small part of it. Basically I have a button that I want to be able to press, and each time I press it I want it to output a new number to the innerText of a div in the HTML document.
Right now I get the random number, but I have to refresh the page to get a new one since it keeps outputting the same one if I press it again.
const mathQuestion = document.getElementById('math-question')
const newNumbers = document.getElementById('new-btn')
newNumbers.addEventListener('click', setQuestion)
function setQuestion () {
mathQuestion.innerText = calc.toString();
console.log(calc);
}
var calc = Math.floor(Math.random() * 100) + 1;
Yes, it's very simple and probably not the easiest or even the correct way to do it, but I am at a loss here.
I suspect I need to run another function for reseting the text or something after ive set the innerText, but I don't really know where to start.
Currently, you only generate the random number once and when you click the button, you set the same number in the HTML. That is why you see the same number irrespective of how many times you click the button.
Number changes on page reload because each time page reloads, new random number is generated.
You need to re-generate the random number every time the button is clicked. To do this, move the random number generation code inside the event handler function and it should work as expected.
function setQuestion () {
var calc = Math.floor(Math.random() * 100) + 1;
mathQuestion.innerText = calc;
}
Also, there's no need to explicitly convert the number into a string.

Tracking Number Guessing Attempts using JavaScript

I'm trying to build a simple number guessing game numberGuess() that tracks the # of attempts a player takes, but does not track an attempt if the player guesses a number that has already been guessed.
The only bug that keeps happening is if the player guesses the 1st number he guesses more than once - the game then logs that attempt when it shouldn't. However, if the player guesses any other number, but the first one more than once, it works perfectly.
For example, if player guesses in this order: 2, 5, 2, 3, the total attempts SHOULD show 3, but it shows 4.
However, if player guesses in this order 2, 5, 5, 3, the total attempts correctly shows 3.
I have hours and hours tinkering with this code and trying to figure this out before asking here, but have hit a wall. It seems to be a simple fix that I cannot figure out. Please let me know if you have spotted the error to fix this small bug!
function numberGuess () {
var number = Math.floor(Math.random() * 100 + 1); // Generates a random number between 0 and 100
var totalGuesses = []; // Array to stores all the guesses
var guess = Number(prompt("Welcome to number guess! Guess a number between 1 and 100")); // Prompts guessor to guess first number
while (guess != number) { //loop runs while user has not guessed the number
if (!guess) { // User cancels prompts
return;
}
else if (totalGuesses.indexOf(guess) >= 0) { // Checks to see if guess has already been guessed
guess = prompt ("You already guessed that number before. Give me another guess.");
}
else {
totalGuesses.push(guess);
if (guess > number) {
guess = prompt ("Your number is too high. Try Again. Don't give up!");
}
else {
guess = prompt ("Your number is too low. Try Again. I know you can do it!");
}
}
}
// Guess is correct!
alert("Congratulations! You guessed the number! It took you " + (totalGuesses.length +1) + " attempts!");
};
numberGuess();
The problem is with the following branch of your if statement:
else if (totalGuesses.indexOf(guess) >= 0) { // Checks to see if guess has already been guessed
guess = prompt ("You already guessed that number before. Give me another guess.");
}
In this code, you're not adding the guess to the totalGuesses array because it has already been guessed. As a result, the number of items in the totalGuesses array remains the same even though the number of guesses has increased by one.
A hacky solution would be to add the guess to the totalGuesses array anyway. But a better solution would be to use the totalGuesses as a set (unique values only) and make use of a counter variable which starts at 0 to track the number of guesses a user has made.
Furthermore, although you're correct in assuming that indexes in an array begin at 0, the length property of the array returns the number of items in the array, which, even if the index starts at 0, will always return the correct number of items. Therefore you don't need to add 1 to the result.
alert("Congratulations! You guessed the number! It took you " + totalGuesses.length + " attempts!");
Something that I've also noticed is that if the user enters something other than a number on his/her first guess, the code will correctly convert it to a number, however if the user then enters something that isn't a number after his/her first guess, it will remain as a string.

How do I get this JavaScript number guessing game to work without a "while" or "for" loop?

Here are the rules to the challenge:
Generates and stores a secret, random number
Prompts the user for a number between 1 and 100
Responds to the user's number:
If higher, it says to pick lower
If lower, it says to pick higher
Repeats steps 2 and 3 until the user picks the correct number
Congratulates the user when they win!
Do not use a 'while' or 'for' loop. Use only functions.
I would normally use a loop to do this, but the rules state otherwise. My code is below
var secretNumber = parseInt(Math.random() * 100, 10) + 1;
var guessNumber = function(){
var userNum = prompt("Pick a number between 1 & 100!");
if(userNum > secretNumber){
prompt("Pick Lower!");
}
else if(userNum < secretNumber){
prompt("Pick Higher");
}
else{
alert("Congratulations!!! You win!")
}
};
Naturally my code stops after it runs through the "if else" statements. How can I refactor this code to make the number guessing game work without loops?
Thanks in advance!
Make your function receive an argument, which you will use as the prompt message.
When the user fails, call your function again, but with another message. And voilĂ  - Recursion :)

My 1 page web app reduces a variable by 2 instead of 1 after completing a certain level

For some reason after the user guesses the right number and follows the confirm to play the game again but with fewer guesses (2 less than original), each time a user guesses a number the guesses remaining is deducted by 2 and sometimes just random numbers instead of the usual 1. I tried changing the code to deduct in various different ways but to no avail:
j--;
j -= 1;
j = j - 1;
Full code in Fiddle, if anyone could help that would be awesome I've been at this for hours! Thanks
partial for guess button click event
if (currentGuess < numberToGuess) {
$hintBox.html('<p class="blue">Try higher</p>');
} else {
$hintBox.html('<p class="blue">Go lower</p>');
}
j = j - 1;
$('.numberGuesses').html(j);
} // end of if guess is not correct
else if (currentGuess === numberToGuess) {
alert('Well done the correct number was '+ numberToGuess);
var playAgain = confirm("Let's see if you can do that again with less guesses.");
if (playAgain){
$('#gameDiv').hide('pulsate', 100, function(){
$('#mode').delay(200).show('pulsate', 500);
});
lowerGuesses = lowerGuesses - 2;
$('.numberGuesses').html(lowerGuesses);
} else {
location.reload();
}
}
You don't reset the counter j to lowerGuesses after you get the number right.
The code is very difficult to follow, and IMO a bit broken. Things need to be broken out much better. Isolate the "new game" code into something you call when there's actually a new game. Create a new random number. Clear out the numbers it remembers; after I fixed it it was the same number again (possible but unlikely, so I'm assuming that logic is also broken) so it both warned me that I'd already guess the number, and told me I guessed the number correctly.
Basically your game loop should be just for the game, not for preparing a new game, etc. Consider passing in the number of guesses the player should get into a newGame function (along with many other refactorings).

Displaying wrong answers

I have created a spelling game where the user spells the word by clicking on letters. To show the user how many they have wrong and right I count the amount of times the right and wrong message is displayed and print it to the user.
This works perfectly for correct answers but not for wrong answers. Can someone tell me why?
This is the script for the correct answers (works fine)...
var completeLetters = $('.wordglow2').length;
var completeWords = (completeLetters / 3);
if ($(right).show()) {
$('.counter').html("Right Answers = " + completeWords).show();
}
Here is the one for incorrect answers (exactly the same logic, but won't work!)...
var incompleteLetters = $('.wordglow4').length;
var incompleteWords = (incompleteLetters / 3);
if ($(wrong).show()) {
$('.counter2').html("Wrong Answers = " + incompleteWords).show();
}
So basically "wordglow4" is the style added to the letter when it is incorrectly spelt and "wordglow2" is the style added to the correctly spelt letters.
All the words are 3 letters long, hense the "(incompleteLetters / 3)"
Here is a fiddle to help http://jsfiddle.net/smilburn/Dxxmh/34/
the 'complete words' counter works because you always leave the '.wordglow2' style on the table cells when the word is completed. Therefor $('.wordglow2').length will always return the total completed letters (and hence words)
However, the incorrect words won't work, because as soon as the user gets it right, the style is changed (from '.wordglow4' to '.wordglow2' - p.s. you might want to think about using more descriptive class names - e.g. '.correctLetter' and '.wrongLetter'). Thus, you'll never have more than 3 '.wordglow4' letters on screen, so the incompleteWords counter will never get past 1.
To make the incorrect word counter work, you'll need to declare the counter outside the function, and do something like:
var incompleteLetters = $('.wordglow4').length;
incompleteWords += (incompleteLetters / 3);
This should then keep track of previous failures, and give you the behaviour you want
There is only ever one wrong answer indicated on the board by the table cells with the class .wordglow4, unlike the correct answers which maintain the .wordglow2 class after they have been guessed correctly.
So the count of .wordglow2 will always be correct, whereas the count of .wordglow4 will only ever be 3.
You should move the count variable outside of the .click() event and increment it when a word is guessed incorrectly.
So, in your example code, add...
var animation = false;
var incompleteWords = 0; // <-- this line
$('.drag').on('click', function(e) {
and change
var incompleteWords = (incompleteLetters / 3);
to
incompleteWords += (incompleteLetters / 3);

Categories