JavaScript Function not passing variable - javascript

My game here is a guessing game, which counts the number of guess and does not include any repeated guesses.
I am trying to pass the variable tries from function attempts to function tries but it will not work. The count remains 0, but when I pass sameGuess.length it work, why is this?
let random = Math.round(Math.random()*100);
let guess = false;
let sameGuess = []
let tries = sameGuess.length;
function game(){
while (guess === false){
let myGuess = prompt('Guess a number between 0-100:');
numCheck(myGuess);
if (myGuess == random){
guess = true;
repeats(myGuess, sameGuess);
attempts(tries, sameGuess);
}else if (myGuess < random){
repeats(myGuess, sameGuess);
alert('Your number was too small, try again!');
guess = false;
}else if (myGuess > random){
repeats(myGuess, sameGuess);
alert('Your answer was too big, try again!');
guess = false;
}
}
}
function attempts(tries, sameGuess){
if (sameGuess.length == 1){
alert('Well done, you got it frist try!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length <= 15){
alert('You took ' + sameGuess.length + ' tries');
alert('Well done, you didn\'t take too many tries!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length >=16){
alert('You took ' + sameGuess.length + ' tries');
alert('You got it, but lets see less tries next time!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}
}
function repeats(myGuess, sameGuess){
if ((sameGuess.indexOf(myGuess)) == -1){
(sameGuess.push(myGuess));
}else alert('You have already guessed that number! - Dont worry, i haven\'t counted it!');
}
function numCheck(myGuess){
if (isNaN(myGuess)){
alert('Enter a number, don\'t try and be sneaky!');
}
}
game ();

When you access array.length, that value is copied, meaning it won't update even after you add a value to the array:
var array = [];
var length = array.length;
console.log(length); // 0
array.push('Some value');
console.log(length); // Still 0, since it was copied, it is _not_ a reference to the live value
console.log(array.length); // 1, this is a live reference to the length of the array
As it stands now, your code works fine, although it looks like you can remove the tries aspect of it and use the sameGuess.length directly, as you are now.
See this post for more discussion on Pass by Reference or Pass by Value.

You should put tries = sameGuess.length; inside of your while!

Related

How to give "No more tries left" in a password-guessing loop

I've just started learning JS and I got stuck here.
What I need to do:
If you don't enter the correct password, you get the message "Try again".
If you don't enter the password 3 times, you get the message "No more tries left".
If you enter the correct password, you get the message "You may enter".
Here's my code:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else if ( i = 0 ) {
alert("No more tries left")
} else {
alert("You may enter")
}
}
I can't get it work properly as the message "No more tries left" doesn't show up. I know ( i = 0 ) is wrong but I don't know how to make it work.
Firstly, make sure that you're not using an assignment operator when you check if i == 0. You're currently using i = 0, which doesn't check if the two are equal as much as it assigns the left to the right. No bueno.
Secondly, your for loop is off just by a bit. It'll never get to 0 because you've asked it to loop while i > 0, not i >= 0. But wait - if you use i >= 0, it'll loop four times. That's not what you want either. We'll compromise and loop three times, but check if i == 1 instead of 0.
Here's my corrected code that works:
// loop three times
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
// if it's the correct answer then alert and break the loop
if ( password.toUpperCase() == "BINGO" ) {
alert("You may enter")
break
// if it's not, and the tries has elapsed, then alert and break the loop
} else if ( i == 1 ) {
alert("No more tries left")
break
// if it's not but the tries have not elapsed, then loop again
} else {
alert("Try again")
}
}
Try this.
for ( let i = 3; i >= 0; i-- ) {
if (i===0){
alert("No more tries left");
break;
}
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else {
alert("You may enter")
}
}
Give the user chance to enter the password 3 times but loop 4 times and check if the loop runs for 4th times(i === 0). if prompt No more tries left and break the loop.
You are using an assignment operator instead of a comparison operator.
Change this:
else if ( i = 0 ) {
alert("No more tries left")
}
To this :
else if ( i == 0 ) {
alert("No more tries left")
}
Try this. It will run the loop until they have entered the password correctly or the number of attempts is 3.
After the loop you can then just check if valid is true or false.
let valid = false;
let attempts = 0;
do
{
const password = prompt('What is the password');
valid = password.toUpperCase() === 'BINGO';
if (!valid && attempts < 2)
{
alert('Try again');
}
attempts++;
} while (!valid && attempts < 3)
if (valid)
{
alert('You may enter');
} else
{
alert('No more tries left');
}
You are asking the user to enter the password in each iteration
using a loop. So, showing that "you don't have anymore attempt left"
is useless here. Because if the value is greater than 3, the
instruction inside the loop will not be executed.
Do not use JavaScript for authentication. It is a client side
programming language and any one who knows how things work can
extract the password. Instead use a back-end language for
authentication such as PHP, Node.js
But if you only want to know about it just for the learning purpose
not because you wanna implement it, the below code will help you
for (let i=0; i<3; i++){
let password = prompt("what is the password: ");
if (password.toUpperCase() != "BINGO"){
alert("Try Again!");
}else{
alert("You may enter!");
i=3;
}
}
There are several ways you can do the "No more attempt left" is, one of the simple and basic is:
<input type="button" value="Enter Code" onclick="checkMe()">
<script>
let i=0;
function checkMe(){
if (i<3){
let password = prompt("Enter password!");
if (password.toUpperCase() != "BINGO"){
alert("Try Again! Attempt "+ (++i));
}else{
alert("You may enter!");
i=3;
}
}else alert("No more attempts left");
}
</script>
The above code can be implemented using input field, as i said, there are several ways. Hope it helps!
Your code is fine, what goes wrong is that it does not fall into the if condition (i == 0), because the loop only runs while i > 0,
just need to adjust like this:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if (password.toUpperCase() !== "BINGO" && i > 1 ) {
alert("Try again")
} else if (i == 1 && password.toUpperCase() !== "BINGO") {
alert("No more tries left")
} else {
alert("You may enter")
i = 0
}
}

alert does not process user input

I'm working on conditional statements in js. But ran into 2 problems with this script.
1) regardless of user input, the script doesn't process the else clause.
2) my alert method prints first the if alert(), then secondly an undefined alert(). Idk why this is.
<script>
function temperature (temp)
{
var message="";
var temp = 70;
if(temp <= 69) {
alert(message = "Turn on the heat.");
} else {
alert(message = "It is hot enough.");
}
}
</script>
Then my body script is:
<script>
var myTemp=prompt("Please enter your current temperature."); //prompt is ok
//alert fails to process else clause and then prints an undefined alert()
alert(temperature(myTemp));
</script>
I have tried removing the alerts from the function itself. That, however, kills my prompt.
PS I use Sublime 3 with jshint but this problem is out of jshint's jurisdiction, obv.
Please advise and thanks all.
you are using 2 alerts: one inside the another.. and also resetting your temperature value.
Use this:
function temperature (temp)
{
if(temp <= 69) {
return "Turn on the heat.";
} else {
return "It is hot enough.";
}
}
A couple of things:
1) You are setting the variable temp to 70, so it overrides your input.
2) The prompt() function returns a string, which you are then passing into your temperature function where you are trying to compare it to integers. Use parseInt().
3) You are also nesting alerts since you put temperature() in an alert and your temperature() function itself also creates alerts. Choose one or the other.
This is how I'd change it.
<script>
function temperature (temp){
var message="";
var temp = temp || 70;
if(temp <= 69) {
message = "Turn on the heat.");
} else {
message = "It is hot enough.");
}
return message;
}
</script>
and then:
...
alert(temperature(parseInt(myTemp)));
...

Codecademy lesson troubles

I am learning JavaScript through Codecademy, but I have an issue. The code below is supposed to search through the text variable for my name in the myName variable and then push all of the individual letters to the hits array. The code that I have written is not correct but Codecademy says that it is correct and is going to let me move on in the lesson.
I have been trying to solve the issue that I am having with no luck. The problem is that when I run the hits.push(text); line it will output the entire variable but I have tried hits.push(text[i]); and get undefined for the result. Can someone please help me understand where I have made the mistake?
/*jshint multistr:true */
var text = "XsddfasASSFABrandonSFsdfdasBrandonsddfadfaBrandon";
var myName = "Brandon";
var hits = [];
for (i=0; i<=text.length;i++){
if (text[i]===myName[i]){
for(var x=i; x<i+myName.length;x++){
hits.push(text);
}
}
}
if (hits.length===0){
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
The best way I can think to explain your mistake is simply by walking through a bit of the logic of what you have written.
for (i=0; i<=text.length;i++){
Your for loop will iterate i for as many characters as there are in your text variable, so: 49 times.
if (text[i]===myName[i]){
The first run through your for loop, where i=0, you are checking to see if text[0] is strictly equal to myName[0]. text[0] = X and myName[0] = B. The strictly equals condition is not met, so the loop proceeds to increment i repeat: text[1] = s and myName[1] = r. This continues 47 more times, and the condition is never met. myName[i] is undefined after the first 7 loops.
Normally you would do this kind of thing using indexOf, match, search, substr or substring, which are all string methods.
However for the purpose of this exercise you can do:
var text = "XsddfasASSFABrandonSFsdfdasBrandonsddfadfaBrandon";
var myName = "Brandon";
var hits = [],
namePosition = 0;
for (var i = 0; i < text.length; i++) {
if (text[i] === myName[namePosition]) {
hits.push(text[i]);
namePosition ++;
if (hits.length === myName.length) {
break;
}
}
else {
namePosition = 0;
hits = [];
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}​
(See it working at http://jsfiddle.net/wCWxr/1/). The problems with your original code include:
you try to compare text[i] to myName[i] but the indices of the two strings won't match up.
you try to push the entire string text into hits instead of one character at a time
your logic doesn't deal with the possibility that the beginning but not the end of myName is in text, e.g. if text was aerwerBrasdfsgars
My suggestion fixes this by recording (with namePosition) what position we are currently at within the string myName, and incrementing that when we find a character in text that matches the relevant character in myName. If the characters do not match then it's not a true hit, so we reset hits = [] and namePosition = 0. If the characters all match then hits eventually reaches the length of myName and so we break out of the loop.
If you are trying to find if myName is in text here is what you do:
RegExp:
var pattern = new RegExp(myName);
if (pattern.test(text)){
console.log(myName);
}else {
console.log("Your name wasn't found!");
}
indexOf:
if (text.indexOf(myName) != -1){
console.log(myName);
}else {
console.log("Your name wasn't found!");
}
if (text[i]===myName[i]){
this line should create an error, because myName[i] is not the first letter of myName.
if (text[i]===myName[0]){
Change to this line should work.

Count the number of times an input has been made javascript

What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.

Removing a string return after a function has been processed

I'm a beginner and a student and I'm hoping someone can help me out. I have an assignment where I need the program to be broken up into 3 functions. The first takes a sentence from the user, the second converts the sentence into a new "pig language" depending on the length of each word, and the third displays the results in the console. I have the heart of this program done, but I have a problem with clearing out the return string. Specifically, once the user has gone through all 3 steps, I don't want them to be able to enter into the 3rd part of the program and see the results again. I want them to have to go back to the beginning. Sorry for drawing this out so much, but I'm just not sure of how else to explain it.
Here's my code:
function prog1(){
var userLang = prompt("Type in your sentence");
//If the user enters an empty string
if(userLang == ""){
console.log("You must enter a sentence");
}
//If the user presses cancel
else if(userLang == null){
wantToQuit = true;
}
//If the user enters in a good string
else {
console.log("Thank you, now go to program 2");
been2prog1 = true;
return userLang;
}
}
function prog2(){
//sets newLang = userLang and splits the string
var newLang = prog1Lang.split(" ");
//enters loop to find length of each split word
var x = 0;
for( x = 0; x < newLang.length; x++ ){
//if it's 5 or less words, add -oink
if ((newLang[x].length) <= 5){
newLang[x] += "-oink";
}
//if it's more than 5 words, add -a
else {
newLang[x] += "-a";
}
}
**newLang.join(" ");**
//put the string back together
console.log("String converted");
been2prog2 = true;
return newLang;
}
function prog3(){
var endLang = prog2Lang;
console.log(endLang);
**delete prog2Lang;**
}
I was thinking "delete" might work, as seen above, but I didn't do anything all all. Then I was thinking a Boolean, but I am not sure how to go about doing so. Any help would be much appreciated.
One last thing, I am also stuck on how to join my string back together. Currently it logs it in the console as being a part of the array and separates each word with quotes and a comma. I've looked up the .join(); and I thought it would do the trick, but it doesn't seem to work either. I put it inside of the if else statements in function 2 but, it just freaks out when I do that, so pointers on this issue would also be much appreciated.
Thank you!
Try assigning the newLang.join to itself..
newLang = newLang.join(" ");
I wasn't sure what the other bit was that you were having trouble with was, I was a bit confused.
if all you are trying to do is clear out a string variable then..
prog2Lang = null;
or
prog2Lang = "";
null is a null object and "" is an empty string.
Is that what you were after?

Categories