while loop giving strange results - javascript

This while loop works sometimes and sometimes it doesn't. can anyone see why?
I feel like it should start looping, and keep looping till the dealers total is greater than 17 and hit the else block. once it goes into the else block it should update the outcome value. however, sometimes it jumps into the else block and then jumps straight to the console.log(outcome) and tells me it is undefined. sometimes it will return the correct outcome. e.g. it outputs 'dealer wins!'
I feel like I have met every condition?
I have even put in console.logs and the line dealersTotal = total gets updated correctly. why is it not continuously looping?
dealerTwisted = () => {
let dealersTotal = this.state.dealersOverallTotal;
let playersTotal = this.state.playersOverallTotal;
let looping = true;
let outcome = '';
while(looping){
if(dealersTotal < 17){
this.deal2Dealer();
let dealersDeck = this.state.dealersDeck;
let newDealersDeckTotal = [];
for (var i=0; i < dealersDeck.length; i++){
newDealersDeckTotal.push(dealersDeck[i].rankValue)
}
let total = newDealersDeckTotal.reduce(function(a, b) {
return a + b;
},
0);
dealersTotal = total;
}
else {
if(dealersTotal > 21){
outcome = 'player wins!';
break;
}
else if(playersTotal > dealersTotal){
outcome = 'player wins!';
break;
}
else if (playersTotal == dealersTotal){
outcome = 'tie!';
break;
}
else if (dealersTotal > playersTotal){
outcome = 'dealer wins!';
break;
}
else {
console.log('got here');
break;
}
}
console.log(outcome);
this.setState({resultOutcome: outcome})
break;
}
};
EDIT: Think I have figured it out. It must go into the first if and then it hits the break at the end of the big else. HOWEVER, problem is still that I need it to loop around and only break once all conditions have been covered. solution?

Do you set looping to false anywhere? I can't see it. If not, try setting looping to false at the end of the big else block.
Example:
else {
if(dealersTotal > 21){
outcome = 'player wins!';
}
else if(playersTotal > dealersTotal){
outcome = 'player wins!';
}
else if (playersTotal == dealersTotal){
outcome = 'tie!';
}
else if (dealersTotal > playersTotal){
outcome = 'dealer wins!';
}
else {
console.log('got here');
}
console.log(outcome);
this.setState({resultOutcome: outcome});
looping = false;
}

Related

Programming a game of guessing number - I can't get while loop to work (Javascript)

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';
}
}
});

Codewars JavaScript fundamental problem help (Arrays)

I've been trying to resolve the following problem:
You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block for each letter (direction) and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise.
Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!).
Here is the code I wrote:
function walkTime(walk) {
//insert brilliant code here
var walkLength = walk.length;
if (walkLength === 10) {
return true;
}
else {
return false;
}
}
findEndPosition = (Arr) => {
var y = 0
if (Arr.length > 10) {
return false
}
else {
Arr.forEach((x) => {
if (x === 'n') {
y++;
}
if (x === 's') {
y--;
}
if (x === 'e') {
y++;
}
if (x === 'w') {
y--;
}
})
};
if (y === 0) {
return true;
}
else {
return false;
}
}
const isValidWalk = (walk) => {
if(walkTime(walk) === true && findEndPosition(walk) === true){
return true
}
else {
return false
}
}
console.log(isValidWalk(['w','e','w','e','w','e','w','e','w','e','w','e']));
I keep trying to passing all the tests except for two. Unfortunately it's not telling me what inputs it's using that keep failing :/. Anyone think they know what's going on, this is driving me crazy! Thanks in advance!
If your goal is only to check if the walk will take exactly 10 minutes, it should be enough to test that the walk array is 10 in length and the walk steps are valid. Isn't it so?
In your code, you have a function for solving the end position. There is a clear mistake as steps to west and east are changing the y variable. Is your actual problem more related to this one?
Just wanted to let you guys know I found this solution. It worked through all the tests! I'm sure it could be written a lot better, if you guys got suggestions I'd appreciate it! Anyways here it is!
function walkTime(walk) {
//insert brilliant code here
var walkLength = walk.length;
if (walkLength === 10) {
return true;
}
else {
return false;
}
}
const findEndPosition = (Arr) => {
var y = 0;
var x = 0;
if (Arr.length > 10) {
return false
}
else {
Arr.forEach((movement) => {
if (movement === 'n') {
y++;
}
if (movement === 's') {
y--;
}
if (movement === 'e') {
x++;
}
if (movement === 'w') {
x--;
}
})
};
const newLocation = [x,y];
if (newLocation.toString() === '0,0') {
return true;
}
else {
return false;
}
}
const isValidWalk = (walk) => {
if(walkTime(walk) === true && findEndPosition(walk) === true){
return true
}
else {
return false
}
}
console.log(isValidWalk(['n','s','e','w','n','s','e','w','e','w']));

How to get the result of If/ If else statement

I don't know if I'm overseeing it or what, but I don't know how to get the result of an else if statement, for example, I have this code that I have been practicing:
In this case, the result would be "It's warm!", what I'd like to do is to create a code that would depend on the result, but the result it's not a variable, so how do I create a code responding to what was logged? for example if it logged: "It's warm!" I want to add something like "Turn on the AC." or "Turn on the heater" or something else. How do I do it?
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!");
} else if (temperature < 24) {
console.log ("It's cold!");
} else {
console.log ("It's cool!");
You could just save it as a variable:
let temperature = 36;
const isCold = temperature < 24;
const isWarm = temperature > 24;
if (isWarm) {
console.log("It's warm!");
} else if (isCold) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
if (isWarm) {
console.log("Turn on the A/C!");
}
you can set your code in the expresion block that are defined with {} after the if condition..
As example:
let temperature = 36;
if (temperature > 24) {
console.log("It's warm!");
console.log("Turn on the AC.");
// You can write coode base in this condition as much you want
// or you can call another function
} else if (temperature < 24) {
console.log("It's cold!");
} else {
console.log("It's cool!");
}
Not quite sure what you mean, but if you want to output the temperature:
let temperature = 36
if (temperature > 24) {
console.log ("It's warm!", temperature, "degrees");
} else if (temperature < 24) {
console.log ("It's cold!", temperature, "degrees");
} else {
console.log ("It's cool!", temperature, "degrees);
Put the result into a variable.
let temperature = 36;
let result = '';
if (temperature > 24) {
result = "It's warm!";
} else if (temperature < 24) {
result = "It's cold!";
} else {
result = "It's cool!";
}
console.log (result);
You can set a variable in a function - pass the temperature into the fucntion and output the result - note the use of the switch statement that compares the inputted temp to the conditions and update the result string. This is what switch statements are for - to provide an alternative to nested or complex if else statments.
function setTemperature(temp){
let result = "It's ";
switch (true) {
case temp > 24:
result += "warm!";
break;
case temp > 12:
result += "cool!";
break;
default:
result += "cold!";
}
return result;
}
console.log( setTemperature(36)); // gives "It's warm!"
console.log( setTemperature(16)); // It's cool!
console.log( setTemperature(6)); //It's cold!
You can make a function like so:
let temperature = 36;
function myFunct(temp){ // "myFunct" can be anything
if (temp > 24) {
return "It's warm!";
} else if (temp < 24) {
return "It's cold!";
} else {
return "It's cool!";
}
}
var t = myFunct(temperature); // get whether it's warm, cold, or cool
console.log(t); // tell the user if it's warm, cold, or cool
// do something!
if(t === "It's warm!"){
// run something here if it's warm
} else if (t === "It's cold!"){
// run something here if it's cold
} else {
// run something here if it's cool
}
Though you could just run something inside the function or original if statement instead.
Hope this helped!

Else if Statement ( the last condition is always picked

if (q1 == "1-25") {
score = 0;
}
else if (q1 == "26-40"){
score = 5;
}
else if (q1 == "41-60"){
score = 8;
}
else (q1 == "60+")
score = 10;
this is a segment of my code from a multi-choice test but no matter what option I pick, the score variable always chooses 10
A possible error in the format of my code?
The problem is this:
} else (q1 == "60+");
score = 10;
Thanks to ASI, (q1 == "60+") is the expression that is run in the else part, score = 10 is always executed after the if/else. Might do:
} else {
score = 10;
}
Or
} else if (q1 == "60+"){
score = 10;
}
And please always use semicolons to seperate statements and curly braces to annotate blocks.
else shouldn't be followed by a condition. Javascript doesn't require curly braces so it's probably executing the condition as a statement (since else doesn't accept a condition) and then the final score is a separate statement outside of the if-else logic.
If I add braces to your current code, you can see where the problem lies:
if (q1 == "1-25") {
score = 0;
}
else if (q1 == "26-40"){
score = 5;
}
else if (q1 == "41-60"){
score = 8;
}
else
{
(q1 == "60+");
}
score = 10;
So you can see that, because you're using else rather than else if, the "condition" is executed by the else, evaluated to true/false and then thrown away. And then, after the if statement is done, score is set to 10.
Here is problem
else (q1 == "60+")
score = 10;
You are missing if
Or remove this condition.
Else cannot have condition

Nested else if in javascript

In this random number guessing, after obtaining input from user, if its is wrong (it should go to else) it does not go to the else statement. I can't find where it went wrong.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
var random = Math.floor(Math.random() * 10) + 1;
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}
} else if (guessint < random) {
var guessless = prompt("Try again with value GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}
} else {
document.write("Oops Guessed wrong");
}
Assuming that both guessint and random are indeed defined numbers, then your else condition will never be reached, because when comparing one number against another the only three logical outcomes are that the first is equal, less to, or greater than, the second.
You have obscure { in last else if statement, i've hightlighted it with ___^___ in code snippet below, remove it and everything suppose to work as expected:
else if(guessint<random)
{
var guessless = prompt("Try Again With Valur GREATER than "+guessint)
if(parseInt(guessless)===random)
{
document.write("Guessed Correct Less")
}
}
___^___
else
{
document.write("Oops Guessed wrong");
}
Updated code, you need to have the else inside, updated code below.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
console.log(guessint);
var random = 4; //Math.floor(Math.random()*10)+1;
console.log(random);
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try Again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}else {
document.write("Oops Guessed wrong");
}
} else if (guessint < random) {
var guessless = prompt("Try Again With Valur GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}else {
document.write("Oops Guessed wrong");
}
}
You could use a while loop for guessing. Stay in the loop while the input value is not equal to the random value.
Inside the loop, you need to check for greater, then and prompt the user. after promting, you need to convert the value to an integer with base 10.
If the value is smaller (the else part) prompt for a new number.
If the loop id leaved, you know the guessed value is found and display the message.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !"),
guessint = parseInt(guess, 10),
random = Math.floor(Math.random() * 10) + 1;
while (guessint !== random) {
if (guessint > random) {
guessint = parseInt(prompt("Try Again with value LESSER than " + guessint), 10);
} else {
guessint = parseInt(prompt("Try Again With Valur GREATER than " + guessint), 10);
}
}
document.write("Guessed Correct");
Let's go through it step by step.
Let's say random is 10 and the user picks 9 (so guessint = 9).
Now let's replace those values on your if / else statements:
if (9 === 10) { // False!
} else if (9 > 10) { // False!
} else if (9 < 10) { // True!
/* Runs this part of the code */
} else { // It will never get to this else!
}
No matter what value the user selects, it will have to be either:
Equal to 10
Greater than 10
Lesser than 10
There is no number that will not match any of those conditions. So it will always enter one of your if statements, and never the last else.
You would need an else on every if, like Thennarasan said, or a control variable, like so:
var guessint = parseInt(prompt("Guess a value between 1 and 10!"));
var random = Math.floor(Math.random() * 10) + 1;
// Control variable
var guessed_correctly = false;
if (guessint === random) {
// Correct on first chance
guessed_correctly = true;
} else if (guessint > random) {
// Second chance
var guessgreat = prompt("Try again with a value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
} else if (guessint < random) {
// Second chance
var guessless = prompt("Try again with a value GREATER than " + guessint);
if (parseInt(guessless) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
}
if (guessed_correctly === true) {
// If the user was correct on any chance
document.write("Congratulations!");
} else {
// If the user was incorrect on both chances
document.write("Oops! Guessed wrong!");
}
Alternatively, there are other methods to implement the game you're making with whiles and such, but the example I've given is based on your format.

Categories

Resources