Having problems with a while counter - javascript

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

Related

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.")));

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.

Dart game level end

I require assistance with some logic concerning how a game of darts will end.
So far I have the following rules. A player has 3 throws per turn to whittle the score (501) down to 0. Each throw is added to an array (which holds up to three elements). Once the last dart has been thrown, the total value of all three elements is deducted from the score.
1 - if the player's score is less than zero or equal to one - bust,reset the players running total to the score at the start of the turn.
2 - player's score is equal to zero - finish the game.
3 - player must end the game on a double score (if 10 remaining, get a double 5 to finish)
This is what I have so far (pseudo code)
if(score < 0 or score == 1)
{
console.log("bust")
score = array[0];
}
else if(score == 0)
{
console.log("game finished")
}
else if(score -(scoreNumber * 2) == 0)
{
console.log("double out. game finished")
}
Fiddle added - https://jsfiddle.net/j7bzq5k7/
Score is not enough to solve this information.
When somebody throws 18, it can be single 18, double 9 or triple 6, so just knowing '18' is not enough. You have to know whether they threw doubles or trips. And if you have that information, the logic is easy.
One thing to have in mind: you don't have to throw three darts in the last turn. If you just throw one double and finish, you already have won. So you need to evaluate the win-situation after each throw.
#tba just add a variable ' isDouble = false ' so your fiddle example can run correctly. otherwise your program checks or calculate after 3 throws only as #GolezTrol said . the game would end in several scenarios . so consider them all , i mean calculate the score after every throw (mental calculation).to check if it ends the game or not . at the third throw you can always excute your current program . that's at least what i think .

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

Categories