I am making a game of 21 (also known as blackjacks), and I am not sure why my program is ignoring this conditional statement, where if the user gets their card value above 21, the loop ends, can someone tell me what the problem here would be? Thank you. (This code isn't finished, so excuse the messiness.) (also see comment that says "problem below")
let cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random()*cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random()*cardRange.length)];
var cardTotal = cardOne + cardTwo;
var comScore = 18;
var i;
var extracard;
alert(`Your card numbers are ${cardOne} and ${cardTwo}!`);
//user gets to draw 5 cards in total
for(i = 0; i<3;){
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null){
i+=3;
window.location.replace("http://stackoverflow.com");
}
else if (input === "1"){
i++;
extraCard = cardRange[Math.floor(Math.random()*cardRange.length)];
alert(`This card's number is ${extraCard}!`);
cardTotal = extraCard + cardTotal;
}
else if (input === "0"){
i+=3;
}
//problem below
else if (cardTotal >=22){
i+=3;
}
//not working, loop will not end.
else{
alert("Lmao wrong input you rart");
}
}
function pontoonOutput(){
if (cardTotal > comScore && cardTotal < 22){
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You win!`);
}
else if (cardTotal === comScore){
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... It is a tie!`);
}
//this outputs if the user gets above 22
else if (cardTotal >= 22){
alert("BUST!");
document.write(`Your card number is ${cardTotal}, which is above 21. Which means.... You lose!`);
}
//what should happen if line 29 is picked up. ^
else{
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You lose!`);
}
}
pontoonOutput();
The problem is it is part of an else, so as long as they input 1 or 0 or null, it won't ever hit. Your probably just want to move it into it's own condition at the end:
let cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTotal = cardOne + cardTwo;
var comScore = 18;
var i;
var extracard;
alert(`Your card numbers are ${cardOne} and ${cardTwo}!`);
//user gets to draw 5 cards in total
for (i = 0; i < 3;) {
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null) {
i += 3;
window.location.replace("http://stackoverflow.com");
} else if (input === "1") {
i++;
extraCard = cardRange[Math.floor(Math.random() * cardRange.length)];
alert(`This card's number is ${extraCard}!`);
cardTotal = extraCard + cardTotal;
} else if (input === "0") {
i += 3;
} else {
alert("Lmao wrong input you rart");
}
//problem below
if (cardTotal >= 22) {
i += 3;
}
//not working, loop will not end.
}
function pontoonOutput() {
if (cardTotal > comScore && cardTotal < 22) {
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You win!`);
} else if (cardTotal === comScore) {
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... It is a tie!`);
}
//this outputs if the user gets above 22
else if (cardTotal >= 22) {
alert("BUST!");
document.write(`Your card number is ${cardTotal}, which is above 21. Which means.... You lose!`);
}
//what should happen if line 29 is picked up. ^
else {
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You lose!`);
}
}
pontoonOutput();
The problem is that you are checking the card total in the same if...else statement, but AFTER checking for the "0" or "1" input. So if the user enters "0" or "1", your code will process those conditions, and it will never get to the card total check.
There are many ways to fix this problem. One solution is to move the card total check into a separate if condition, after the main if...else logic. Something like this:
for(i = 0; i<3;){
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null){
// ...
}
else if (input === "1"){
// ...
}
else if (input === "0"){
// ...
}
// Keep separate from the main if...else logic to ensure it always gets run.
if (cardTotal >=22){
i+=3;
}
}
Try using the break statement.
Try this instead:
for(i = 0; i<3;){
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null){
// ...
}
else if (input === "1"){
// ...
}
else if (input === "0"){
// ...
}
if (cardTotal >=22){
//i += 3;
break;
}
}
now i see, it needed to be splited
Related
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
Please tell me what is wrong with my code. It seems like after continue; it still loops over the same block even if I use the largest number as an input. Here it still wants me to input a larger number:
// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)
// 2) Ask the user input (reference: prompt())
let userInput = prompt(`Give me a number`)
const userInputInt = parseInt(userInput)
console.log(userInput)
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))
if(isNaN(userInput)){
prompt(`Give me a freaking number`)
}else{
let x = 0;
while (x < 4) {
console.log('hi')
console.log(userInputInt)
console.log(RanNum)
if (userInputInt == RanNum) {
console.log(`win`)
prompt('YOU GOT IT MAN')
break;
}
else if (userInputInt < RanNum) {
x = x+1 ;
prompt('Larger please')
continue;
}
else if (userInputInt > RanNum) {
x= x+1
prompt('Smaller please')
continue;
}
}
if(x > 3){alert('More than 3 times')}
}
However, this one works fine. Can someone point to me what's wrong?
// Guess the number
const randomNumber = Math.floor(Math.random() * 11);
let trials = 0;
while(trials < 4){
const guess= parseInt(prompt("Give me a number(0-10)!"));
if(isNaN(guess)){
alert("You are not inputing a number");
// Works for while-loop, for-loop, do-while loop
continue;
}
trials++;
if(guess === randomNumber){
// Equal
alert("You win!!");
// If the player wins, terminate the game
// Works for while-loop, for-loop, do-while loop
break;
}else{
// Unequal
if(guess > randomNumber){
alert("Too large!");
}else{
alert("Too small");
}
}
}
if(trials > 3){
alert("You loses");
}
You can use switch-case except if-else:
let i = 0,
solution = Math.floor(Math.random() * Math.floor(11)),
max_tries = 3;
while (nmb !== solution && i < max_tries + 1) {
if (i < max_tries) {
var nmb = Number(prompt("Put number (1 - 10): "));
switch(true) {
case nmb > solution : console.log("Smaller please"); break;
case nmb < solution : console.log("Largest please"); break;
default : console.log("YOU GOT IT MAN");
}
}
else { console.log("You lose! Number was: " + solution) }
i++
}
You only need to add outputs to the console as in your variant.
Given these 9 words, display on the page the word corresponding to their chosen number
1.mercury
2.venus
3.earth
4.mars
5.jupiter
6.saturn
7.uranus
8.neptune
9.pluto
Im not sure what I'm missing here Ive done a lot of trial an error and nothing seems to work.
I've tried using numEntry as my comparison for all the if statements and it hasn't worked. When I made var numEntry = true; only Mercury would display. When I made var numEntry = 1,2,3,4,5,6,7,8,9 only pluto would show. I then tried to create a variable for each number and use each once in a comparison like below but every planet shows up instead of the corresponding number to planet.
var numberOfPlanet = prompt("Please enter a number between 1 and 9");
function thePlanets(){
var numOne = 1;
var numTwo = 2;
var numThree = 3;
var numFour = 4;
var numFive = 5;
var numSix = 6;
var numSeven = 7;
var numEight = 8;
var numNine = 9;
//do I need to define numberEntry if I use it in my comparisons below? what do I define it as after the = //// I tried defining as true but only mercury will appear, i tried inserting numbers 1 through 9 but only pluto worked//
if(numOne = 1 ){
document.write("mercury");
}
if(numTwo = 2 ){
document.write("venus");
}
if(numThree = 3 ){
document.write("earth");
}
if(numFour = 4 ){
document.write("mars");
}
if(numFive = 5 ){
document.write("jupiter");
}
if(numSix = 6 ){
document.write("saturn");
}
if(numSeven = 7 ){
document.write("uranus");
}
if(numEight = 8 ){
document.write("neptune");
}
if(numNine = 9 ){
document.write("pluto");
}
}
thePlanets();
I just need a number to correspond with the right planet when the user enters that number eg. ( user enters 1 and it displays mercury)
Some notes:
Use numberOfPlanet as the function argument to compare with (it becomes num inside the function).
Convert numberOfPlanet to Number as prompt() returns string.
Use === (strong comparison) instead of = (assignment).
Use else if instead of next if if you need only one variant from some so that the comparing stops when the right result is found.
var numberOfPlanet = Number(prompt("Please enter a number between 1 and 9"));
function thePlanets(num){
if(num === 1){
document.write("mercury");
}
else if(num === 2){
document.write("venus");
}
else if(num === 3){
document.write("earth");
}
else if(num === 4){
document.write("mars");
}
else if(num === 5){
document.write("jupiter");
}
else if(num === 6){
document.write("saturn");
}
else if(num === 7){
document.write("uranus");
}
else if(num === 8){
document.write("neptune");
}
else if(num === 9){
document.write("pluto");
}
}
thePlanets(numberOfPlanet);
I am trying to let the game only let the user have 3 guesses to guess correctly. The problem is that it lets the user guess a 4th time, but even if user guesses correctly on 4th attempt I get a wrong answer message. I tried changing the number of guesses, changing that i = 0 start position, subtracting one from maxGuesses in the for loop. No matter what I try the relationship is off by one. Here is my code so far.
let readlineSync = require("readline-sync");
let hint = "";
let maxGuesses = 3;
const maxRange = 10;
const minRange = 1;
let userGuess = readlineSync.question(
"I have chosen a number between " +
minRange +
" and " +
maxRange +
". You have " +
maxGuesses +
" tries to guess it!\n"
);
const randomNumber = Math.floor(Math.random() * maxRange + 1);
function handleGuess(userGuess) {
if (userGuess != null && userGuess != undefined && (userGuess <= maxRange && userGuess >= minRange)) {
for (i = 0; i <= maxGuesses - 1; i++) {
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
return;
} else {
if (userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
}
console.log("Dude...YOU SUCK!");
return;
} else {
userGuess = readlineSync.question("Fix your answer fool! \n");
handleGuess(userGuess);
}
}
I assume your first call is handleGuess() with no parameter.
Then, your program asks the user for its first guess (withe the message "Fix your answer fool!"). If you call handleGuess() with a parameter, the following still applies.
After that, the loop will begin.
if the first answer is wrong, the console will display the message "Think [higher/lower] you fool.", and then request the second guess. Still in the first loop iteration.
Do you see where the problem is ?
If the second guess is still wrong, the console will display the second wrong message and request the third guess while still being in the second loop iteration.
Finally, If the third guess is still incorrect, the third "wrong" message will appear and your code will request a fourth guess before ending the loop and display the message "Dude...YOU SUCK!" without verifying your input.
To prevent that, you can do something like this :
function handleGuess(userGuess) {
i = 0;
do {
if(i > 0) {
if(userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
while(isNaN(userGuess)) {
userGuess = readlineSync.question("Correct you guess. \n");
}
} while(userGuess != randomNumber && i < maxGuesses);
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
} else {
console.log("Dude...YOU SUCK!");
}
}
Just set the condition for your loop to be i < maxGuesses not i <= maxGuesses -1:
var maxGuesses = 3;
for (i = 0; i < maxGuesses; i++) {
console.log("Guess " + (i + 1)); // Only adding 1 here so output is 1-based
}
Im doing this for a dice game where the player is switched if either dice rolled is a 1 or if 6 is rolled twice in a row. My friends code worked but mine didn't, It looks like my if statement accomplishes the same thing.
This code works(friends code):
if (dice === 1 || diceTwo === 1) {
nextPlayer();
} else if (doubleSix === 6) {
if (dice === 6 || diceTwo === 6) {
roundScore = 0;
score[activePlayer] = 0;
nextPlayer();
}
} else {
roundScore += (dice + diceTwo);
document.querySelector('#current-' + activePlayer).textContent = roundScore;
doubleSix = dice;
}
This code does not (my code):
if (dice !== 1 || diceTwo !== 1) {
//Add score
if (doubleSix === 6 && dice === 6) {
roundScore = 0;
score = 0;
nextPlayer();
} else if {
roundScore += (dice + diceTwo) ;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
doubleSix = dice;
}
} else {
//Next Player
nextPlayer();
}
Firstly your friends code only requires one dice to be a 1. You require both dice to be a 1 to run nextPlayer
This is because of what is called De Morgan's laws
Your code should have
if (dice !== 1 && diceTwo !== 1) {
Suggested Improvements..
As a general rule it is a bad idea to call items of a similar nature dice, diceTwo etc. It is much better to have an array of dice, as if you increase the number of dice, the code still works without modification.
Also, I am not sure why you are only looking for a six with the first dice of the previous round, joined with any dice of the current round. I would have thought you were looking for any six in the previous round with any six in the current round...
Your friends code would be better as...
var foundSix = false;
// method to sum array
function sum(total, num) {
return total + num;
}
// ... more code
// check for a 1...
if (dice.indexOf(1) >= 0) {
nextPlayer();
} else if (foundSix) {
// check for a 6
if (dice.indexOf(6) >= 0) {
roundScore = 0;
score[activePlayer] = 0;
nextPlayer();
}
} else {
// roundScore += (dice[0] + dice[1]);
// use array reduce here...
roundScore = dice.reduce( sum, roundScore);
document.querySelector('#current-' + activePlayer).textContent = roundScore;
// doubleSix = dice[0];
// check ALL dice for a six..
foundSix = (dice.indexOf(6) >= 0);
}
Read up on De Morgan's rule. The negation of dice === 1 || diceTwo === 1 is not dice !== 1 || diceTwo !== 1, but rather dice !== 1 && diceTwo !== 1.
In words: the opposite of "one of the dice is 1" is not "one of the dice is not 1", but rather "both of the dice are not 1".
Your if statements do not do the same thing.
Your friend's code:
if (dice === 1 || diceTwo === 1) {
// dice is 1, or diceTwo is 1.
} else {
// neither dice nor diceTwo is 1.
}
Your code:
if (dice !== 1 || diceTwo !== 1) {
// dice is not 1, or dice2 is not 1. In other words this will match all cases except snake eyes.
} else {
// both dice and diceTwo === 1
}
Just a quick look, but shouldn't this: (dice !== 1 || diceTwo !== 1) be changed to an AND like this: (dice !== 1 && diceTwo !== 1) because you are checking that a one was not rolled by both dice and diceTwo?