I want to make it so when someone answers the prompt they can answer a number 1 through 6 and to exit to just enter 0. After that I want them to be able to enter a number and that number will be correlated to an image or a link. Example: I have 3 different kinds of candy and I want 1 to be skittles, 2 to be m&ms, and 3 to be jolly ranchers. When the user enters 1 they will have an image come up that is skittles, and when they enter 2 an image of m&ms will come up. This is the code I have so far. If anyone could help me I would greatly appreciate it!
var stop = '0'
while(true) {
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === stop){
break;
}
}
You can have an array of image urls and select any of them by the number the user has entered.
var images = ['xxx.jpg','yyy.jpg', 'zzz.jpg']
var stop = '0'
while(true) {
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === stop){
break;
}
else{
if (!IsNaN(input) && images.length >= input)
showImage(images[input - 1]); //a mock function
}
}
I would approach your problem like this. Just catch the input and process it inside your while loop.
var pictures = [...] // array of pictures
while(true){
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === '0'){
break;
}else{
if(pictures.length >= input) {
showMyImage(pictures[input - 1])
// or do anything else with your image (e.g. error handling etc.)
}
}
}
Hope this can help!
Related
I am writing a number guessing game. The guessing game starts by prompting a user for a maximum number (this is not their guess yet--it's the top range for their guess). The prompt should be in a loop with validation, making sure the max number is a (rounded) positive integer. The loop should reprompt the user if the input is 0, <0, or a non-number. I am having trouble getting the validation loop to work.
This is what I have so far, and the prompt works, but the function does not work as I need it to.
let suggestion = parseInt(prompt("Help me come up with a range from 1 to a higher number. Type in a number greater than 1."));
function get_suggestion(prompt) {
let validInput = false;
let initial_ans, input;
while(!validInput) {
input = window.prompt(prompt);
initial_ans = parseInt(input);
if(initial_ans != NaN && initial_ans > 0) {
validInput = true;
message.innerHTML = "Guess a number!"
}
}
return(initial_ans);
}
I cannot for the life of me figure out how to close the prompt altogether upon pressing cancel in my code for a guessing game. I've tried several things, but each time either the code ignores what I'm trying to do, or ends in an error. Here's the code in question:
let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);
let numTries = 1
console.log(numGuess);
numGuess = parseInt(numGuess)
if (prompt == null) {
alert (`Press F5 to play again.`)
}
if (numGuess === num) {
alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);
}
else while ((numGuess !== num) && (numTries <3))
{
numTries = numTries++
alert (`Incorrect guess. Try again.`)
}
Check for the user input value, not for prompt. And also don't use while loop here .Loop is used for the traverse.
let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);
let numTries = 1
console.log(numGuess);
numGuess = parseInt(numGuess)
if (!numGuess) {
alert (`Press F5 to play again.`)
}
else if (numGuess === num) {
alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);
}
else{
numTries = numTries++
alert (`Incorrect guess. Try again.`)
}
The main issue with your code is using "++" after numTries which make the numTries variable value doesn't change and the while loop continues working without stopping, you need to insert it before.
ex:
++numTries
The code below is a working example of what you want to do.
let numGuess;
let numTries = 0;
let num = 4;
const guessFunction = () => {
if (numTries >= 3) {
alert("Sorry you Failed in the 3 tries! Press F5 to play again.");
return;
}
numGuess = parseInt(
prompt(`Guess the number I am thinking of (between 1 and 10):`)
);
numTries = ++numTries
if (numGuess === num) {
alert(`Correct! You guessed the number in ${numTries} try! Press F5 to play again.`);
return;
}
if(numTries <= 2) {
alert(`Incorrect guess. Try again.`);
}
guessFunction()
};
guessFunction()
I am trying to write a function that gives a user 4 choices, does what they choose and then asks them the first 4 choices again and again until they exit.
I have tried using an if/else loop inside a while loop, but that just takes the first user input and loops at that point. It also concatenates the balance when I try to add the two numbers. I assume that due to the fact that the prompt is a string and assigns a string to the variable. I am using console.log() to try and see what is happening while everything is running, but to no avail.
Sorry if this is a lengthy post and redundant.
let balance = 0;
let deposit = 0;
let withdraw = 0;
function bankFunction (banked) {
alert('Hello, how can I help you today?');
let input = prompt('Q to quit the application \nW to withdraw \nD to deposit \nB to view balance');
while (input != 'Q') {
if (input === 'W') {
withdraw = prompt("Withdraw how much?");
console.log(withdraw);
balance = balance - withdraw;
console.log(balance);
} else if (input === 'D') {
deposit = prompt("Deposit how much?");
console.log(deposit);
balance = balance + withdraw;
console.log(balance);
} else {
alert("done");
break;
}
}
}
If you want to continuously prompt the user for inputs, then the prompt function should be inside your loop too. The essential pseudo code is: "While the input is not "Q", continue to prompt for a user choice".
Implementation:
let input = "A" // Initial input to get the loop working
while (input !== "Q") {
// Get actual user input
input = prompt("Choose Q or W or D or B");
if (input === "W") {
// Withdraw logic
}
else if (input === "D") {
// Deposit logic
} else if (input === "B") {
// ...
}
}
Note that there is a bit of a little gimmick here: I needed to have an initial input ("A") to get the first round of the loop working - since in the first round of the loop, user input has not been received yet. Once it get past that initial first round, the input variable is being continuously re-assigned through the user prompt, and the loop will exactly how the pseudo-code described it.
If you don't like that gimmick, there is another way, called the While-True-Break loop. The essential idea is that: The loop will automatically run forever, until you explicitly stop it (via break statement)
let input;
while (true) {
input = prompt("Choose Q or W or B or D");
if (input === "Q") {
// Stop the program loop
break;
} else if (input === "W") {
// ...
} else if ...
}
**I'm stuck on this part of my code, I want to generate a random number and compare it to the number who selected the player and depending on the result give a message **
this is a picture of the program
let butons=document.querySelectorAll(".btn");
let result=document.getElementById('result');
let eleccionPc=document.getElementById('elP');
let eleccionPlayer=document.getElementById('elPlayer');
butons.forEach((button)=>{
button.addEventListener('click',()=>{
eleccionPc.textContent=Math.floor(Math.random()*3)+1;
if(button.textContent==='1' < eleccionPc.textContent) {
eleccionPlayer.textContent='1';
result.textContent='You are Loser';
}
else if (button.textContent==='3' > eleccionPc.textContent) {
eleccionPlayer.textContent='3';
result.textContent='You win MotherFucker';
}
/*else if (button.textContent=="2" > eleccionPc.textContent ){
}*/
})
})
PD:I still don't know how to make a decent publication
The problem is in the if statement, you need to use && in the if statement
if(button.textContent === '1' && button.textContent < eleccionPc.textContent)
else if (button.textContent === '3' && button.textContent > eleccionPc.textContent)
This will solve the problem, If you have any question just ask me
this doesn't make any sense:
button.textContent==='1' < eleccionPc.textContent
the first half of the statement returns with "true" or "false" and then tries to see if that is less than a number?
Maybe you mean this?
button.textContent < eleccionPc.textContent
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.