Tracking Number Guessing Attempts using JavaScript - 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.

Related

Having problems with a while counter

well this is the problem: """For this task you'll need to gain access to a target's account, which is password protected. We know the password is only four characters long, but we have no idea of what it looks like.
With today's computing power, brute-forcing weak passwords is not that hard and, as in any brute-force technique, it only requires time and luck.
Instructions
You know that your target's password is 4 characters long, so you'll just have to brute force 1 character at a time. We already declared the variable correctGuesses which you should use to keep track of how many characters you have guessed so far.
Bear in mind that your program does not need to guess the password, that is not your goal!
You need to create a loop that only stops when all 4 characters have been guessed. On each loop iteration you need to calculate a random number between 1 and 3, which will correspond to each of the bellow scenarios:
You guessed one character correctly, which increases correctGuesses by 1 and prints the message 'Found X characters' (where X is replaced with the current number of correct guesses).
You guessed incorrectly and your target's terminal has detected too many attempts, which resets correctGuesses to 0 and prints the message 'Starting over' to the console.
You guessed incorrectly, but have not been detected yet, correctGuesses is kept with the same value.
Once the password is cracked (that is, correctGuesses has a value of 4) you should print the message 'Terminal hacked!'.
Make sure all the messages in your code are in the correct format in order to advance!""""
And this is my code :
var correctGuesses = 0;
var randomNumber = Math.ceil(Math.random()*3);
console.log(randomNumber);
while (correctGuesses < 4){
console.log(correctGuesses);
if (correctGuesses === 4){
console.log('Terminal hacked!');
break;
}
if (randomNumber === 1){
correctGuesses = correctGuesses +1;
console.log('Found' + ' '+ correctGuesses+'characters');
break;
}
if (randomNumber === 2){
correctGuesses = 0;
console.log(correctGuesses);
break;
}
if (randomNumber === 3){
console.log(correctGuesses);
break;
}
}
so i am having a hard time to make my correctGuesses var to add 1 each time randomNumber var gives us 1. already tried out to the change the order of the comands lines, i am making instead of Math.random method put 1 and simply dont add that plus 1, what i am doing wrong if someone could help me i would be very glad

How to make my bot respond to someone after an initial response?

I'm making a bot command so when you type ,num-guess the bot says '[username] guess a number between 1 and 10, you have 3 guesses.'
which works but it also says '[username] you have not correctly guessed it, you have 3 guesses left' 3 times right after. Instead, I want it so when you guess it wrong it says '[username] you have not correctly guessed it, you have 2 guesses left,' then 1 guesses left, then 1 more wrong guesses it would say 'Sorry [username] you did not guesses they number', but it does not work
Here is my code:
module.exports = {
name: 'num-guess',
description: 'User has to guess a number between 1 - 10',
async execute(Client, message, args, Discord) {
NumberToChoose = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const Number = NumberToChoose[Math.floor(Math.random() * NumberToChoose.length)];
message.channel.send(`${message.author.username} guess a number from 1 - 10`);
var MaxGuess = 3
var CorrectAnswer = Number
var GuessesLeft = MaxGuess
var Guess = message.author.message
for (i=0; i<MaxGuess; i++){
if(CorrectAnswer == Guess){
message.channel.send(`${message.author.username} you have guessed the number correctly`);
break;
}
else {
var GuessesLeft = GuessesLeft--
message.channel.send(`${message.author.username} you have not correctly guessed it, you have ${GuessesLeft} left`)
}
}
}
}
Here is what the bot says:
[username] guess a number from 1 - 10
[username] you have not correctly guessed it, you have 3 left
[username] you have not correctly guessed it, you have 3 left
[username] you have not correctly guessed it, you have 3 left
What I want it to say:
[username] guess a number from 1 -10
[user]: 1
(if correct number) [username] you have guessed the number correctly
(if not the correct number) [username] you have not correctly guessed the number, you have [number of more tries] left
(repeat until lose or win)
The postfix decrement operator (n--) has a bit of a confusing feature that makes it more confusing than just using the subtraction assignment operator (n -= x). When using this operator, it will increment the variable, but return the original value. Here's an example:
let number = 1;
const increment = number--;
// number was decremented correctly and is now zero
console.log(`Number: ${number}`);
// but increment takes the value of the original number
console.log(`Increment: ${increment}`);
Since you're assigning n-- to a variable and using that, the number isn't actually going to change, since it's using the original value each time. There are many ways to prevent this:
The easiest way by far would just be not to reassign GuessesLeft to another variable by the same name. This operator will edit values in place, so there's no need to do anything but use the operator.
// original:
// var GuessesLeft = GuessesLeft--
GuessesLeft--
Use the prefix decrement operator (--n). It does the same thing, but this time actually returns the modified number.
Use the subtraction assignment operator. GuessesLeft -= 1. It might not be as short and sweet, but it's much easier to understand, and none of the confusing "post"/"pre" curveballs come into effect.
Also, I'm pretty sure that you'll never be able to guess the number correctly. message.author.message is not a thing, so Guess will be undefined, and it doesn't look like it's actually prompting you for further answers.

Javascript random number generator with function()

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>

My loop is supposed to return an average after a certain value is entered, but I cannot break out of the loop

I'm a beginner with javascript in my first class. I've spent the last few hours working on a homework problem:
"Code a web page to calculate average test scores entered by the user. User should enter 999 to indicate that they are done entering test scores. At this time the page should display the average of the entered scores."
I have the window prompt doing what I want it to do as far as entries go; however, whenever it comes to entering 999, the loop does not stop running and does not calculate the average.
I tried entering break statements at various parts of the code, most of which were illegal.
I've tried various logical operators.
I've searched around but a lot of the potential answers are in coding languages I do not know.
// declare variables
var score = [];
var average = (total / score.length);
var total = 0;
// run the loop
while (score !== 999) {
score.push(prompt("Please input a test score\nIf you are done, please
enter 999 to get the average."));
} for (var i = 0; i < score.length; i++) {
total += score[i];
} if (score === 999 ) { // display alert message
alert("The average of those scores is: " + average);
}
The window prompt is supposed to take any amount of numbers and put them into an array. Once 999 is entered, the prompt displays the average of all numbers that were previously entered into the array.
With
var score = [];
score is declared as an array.
Then values are pushed into the array.
while (score !== 999)
score is never equal to 999, since it is an array. You can instead compare an element of the array by indexing to it (e.g. score[0]).
Index instead to the last element of the array (the latest one, just pushed into it)
while (score[score.length-1] !== 999)
Check if the last element in the array is 999:
while (!score[--score.length] != 999)
However, for this to work, you need to use parseInt on your prompt:
score.push(parseInt(prompt("Please input a test score\nIf you are done, please enter 999 to get the average.")));

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 :)

Categories