I'm a beginner trying to make a text adventure game in JavaScript, and I need to repeat a switch statement until the user enters a valid answer:
opts = prompt("Do you want to TALK or LOOK?").toUpperCase();
switch(opts) {
case "TALK":
mes = "Is anyone in charge here?";
speech = "Our leader is in the big building.";
talkNot();
break;
case "LOOK":
window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
break;
default:
window.alert("That's not an option.");
}
Any answers would be super helpful - thanks!
Wrap the code with some function and callback the function in default statement
function run(){
opts = prompt("Do you want to TALK or LOOK?").toUpperCase();
switch(opts) {
case "TALK":
mes = "Is anyone in charge here?";
speech = "Our leader is in the big building.";
console.log('talk')
//talkNot();
break;
case "LOOK":
window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
break;
default:
window.alert("That's not an option.");
run() //callback
}
}
run()
You can use a simple do ... while structure.
let next = false
do {
let opt = prompt("Do you want to TALK or LOOK?").toUpperCase();
next = false
switch (opt) {
case 'TALK':
case 'LOOK':
break;
default:
next = true
}
} while (next)
Related
I used if, else if, and else statements before and today I've decided to use switch statements which really simplified my code. My question is, just like if statements, is there a way I can add multiple conditions inside a switch statement?
Here's an example:
<script>
var textInput = input.value;
switch (textInput) {
case "orange":
text = "You decided to eat an orange. Do you want to eat another fruit?";
}
document.getElementById("message").innerHTML = text;
</script>
But say I wanted to add a response to the question I added about if you wanted to eat another fruit. How would I add another condition inside that case to where I could get a response back if someone types in yes or no to the question?
Is something like that possible? I hope my question is easy to understand.
Thanks for your help!
You can put any ordinary code inside the case, so you can add if statements:
switch (textInput) {
case "orange":
if (some_other_condition) {
text = "You decided to eat an orange. Do you want to eat another fruit?";
} else {
text = "OK, that's the last fruit";
}
break;
...
}
As long as you don't break the case, it will continue through the switch statement.
switch (textInput) {
case "orange":
text = "You decided to eat an orange. Do you want to eat another fruit?";
// break; we won't break here since it's commented out
case "fruit":
text = "You decided to eat a fruit?";
break;
}
will assign You decided to eat a fruit? to text if textInput is orange or fruit.
This gives you a limited ability to merge certain context, but it is a very bad practice to do so.
you can do something like this although in general it's not the way to go:
function test(input1, input2) {
switch (true) {
case input1 > input2:
console.log(input1 + " is larger than " + input2);
break;
case input1 < input2:
console.log(input2 + " is larger than " + input1);
break;
default:
console.log(input1 + " is equal to " + input2);
}
}
test(5,6);
Yes, you can put If conditions inside a switch, try it here.
switch (true) {
case (dog === 'pet' && cat === 'pet'):
// execute
break;
case (foo === 'bar'):
// do something else
break;
default:
// text = "You decided to eat an orange. Do you want to eat another fruit?";
}
Absolutely!! Adding to your code:
<script>
var textInput = input.value;
switch (textInput) {
case "orange":
text = "You decided to eat an orange. Do you want to eat another fruit?";
break;
case "banana":
text = "Had a banana today";
break;
case default: // Which cannot be found in the case will drop to here
text : ""; // DO nothing as per OP request
break;
}
document.getElementById("message").innerHTML = text;
</script>
For more details, please refer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Well, as far as I know you can't add conditions into switch statement. Switch statement just work to catch different states or 'cases' that one variable can take.
Maybe you can try with something like:
var addMore = true
while(addMore){
var textInput = prompt("Select your fruit");
switch (textInput) {
case "orange":
addMore = confirm("You decided to eat an orange. Do you want to eat another fruit?") // Maybe a yes or no question
default:
addMore = false
}
}
But if you have a UI you should use a multiple input component like Checkbox or something like that.
I hope it was helpful
You can insert the switch statement in a do-while loop, so the question loops until some predefined termination string is entered which will terminate the loop. This way you don't need multiple conditions inside each switch statement.
Check and run below:
var text = "Pick a fruit you'd like to eat: apple, orange, banana or none if you don't want any more";
var eaten = [];
do {
var textInput = prompt(text);
switch (textInput) {
case "orange":
eaten.push("orange");
text = "You decided to eat an orange. If you'd like to eat more type apple, orange, banana or none to end";
break;
case "apple":
eaten.push("apple");
text = "You decided to eat an apple. If you'd like to eat more type apple, orange, banana or none to end";
break;
case "banana":
eaten.push("banana");
text = "You decided to eat an banana. If you'd like to eat more type apple, orange, banana or none to end";
break;
default:
text = "The selection made was not valid\n\nPick a fruit you'd like to eat: apple, orange, banana or none if you don't want any more";
break;
}
} while(textInput !== "none");
var msgText = "You ate: ";
for(var i=0; i<eaten.length; i++) {
msgText += eaten[i];
if(i != eaten.length-1)
msgText += ", ";
}
document.getElementById("message").innerHTML = msgText;
<div id="message"></div>
I want to collect user’s scores from my GitHub page (theratcoder.github.io). I have used the following JS code (embedded in my HTML document) to create my quiz.
var score = 0;
var times33 = window.prompt("3 x 3");
switch(times33) {
case "9":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var subtract5221 = window.prompt("52 - 21");
switch(subtract5221) {
case "31":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var add56 = window.prompt("5 + 6");
switch(add56) {
case "11":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var divide183 = window.prompt("18 / 3");
switch(divide183) {
case "6":
document.write("correct - ");
score++;
break;
default:
document.write("incorrect - ");
break;
}
var finishing_text;
switch(score) {
case 4:
finishing_text = "Great job!";
break;
case 3:
finishing_text = "Well done.";
break;
case 2:
finishing_text = "Better luck next time!";
break;
case 1:
finishing_text = "You need to work on your math!";
break;
default:
finishing_text = "You really need to work on your math!";
break;
}
var submit = window.confirm("Do you want to submit this quiz?");
var percent = score / 4 * 100;
if (submit) {
document.write("Your final score is " + score + " out of 4 (" + percent + "%). ");
document.write(finishing_text);
}
else {
location.reload();
}
I want to collect the values of the variable “score” so that I can get an idea of how people generally do on my quiz.
In order to do something like that, you'll need two things, a way to get the data to some form of storage, and the storage itself.
Unless some things have changed, github.io sites are static content only, so there's no server running in the background that you can access and communicate with your storage from, just your static content being served by the github.io service and running in the user's browser.
So the basic answer is you can't. But that's not true and there's always a hack if you're willing to do something gnarly. (I assume this is just for fun?)
If that's the case, you could run a server on your computer at home or something. Then when the user answers a question you add a call to the server on your computer at home and it takes that data and saves it and aggregates it however you want.
But end of the day if you want to store things about your users, you're probably going to want to have a dynamic website.
Although, maybe take a look at this if you're determined: https://medium.com/pan-labs/dynamic-web-apps-on-github-pages-for-free-ffac2b776d45 -- it's something like the "send data to your own computer" step, but using the free tier of firebase instead.
I wish to use case within a switch switch statement like so:
case 'transfer' + amount:
sql.get(`SELECT * FROM scores WHERE userId ="${userID}"`).then(row => {
sql.run(`UPDATE scores SET points = ${row.points - amount} WHERE userId = ${userID}`);
bot.sendMessage({
to:channelID,
message: `You have transferred ` + amount + ` points. You currently have ${row.points} points.`
})
break;
If it sees transfer10 I want the code to take that value 10 to be amount however I have no idea how to do that.
Thanks in advance :)
I do not think you can create switch statement with dynamic-generated case statements. I also do not see any real advantage of doing this, plus the logic behind this it would be hard to understand from anyone else who will be reading the code.
What about using the switch statement do determine the art of action and accessing the _amount_in the case statements ?
var amount, action;
// some code
...
amount = 2;
// some code
...
action = 'transfer' // or delete, update ...
// some code
...
switch(action) {
case 'transfer':
// do some SQL and access the amount
...
break;
case 'delete':
// do some SQL and access the amount
break;
default:
// some default action
}
If you really need something like a dynamically-created switch-statement look at the first answer from this question.
I am a beginner and i decided to make a game to practice, and i immediately ran into problems. This is my code. I think it explains itself.
<!DOCTYPE>
<html>
<body>
<script>
var user = {
name: this.name,
species: this.species,
stats: [this.strength=0, this.wit=0, this.magic=0, this.health=0]
}
user.name = prompt("What is your name?");
user.species = prompt("Hello, " + user.name + ". What is your species? Orc, Human, Elf, Troll, or Mage.");
user.species = user.species.toLowerCase;
//Sets the stats according to what the user said
switch(user.species){
case "orc":
user.stats=[user.strength=4, user.wit=2, user.magic=2, user.health=45];
break;
case "human":
user.stats=[user.strength=3, user.wit=3, user.magic=3, user.health=40];
break;
case "troll":
user.stats=[user.strength=5, user.wit=1, user.magic=1, user.health=50];
break;
case "elf":
user.stats=[user.strength=3, user.wit=4, user.magic=3, user.health=35];
break;
case "mage":
user.stats=[user.strength=3, user.wit=4, user.magic=3, user.health=30];
break;
}
//It is supposed to output the strength
document.write(user.stats[0]);
</script>
</body>
</html>
The problem is no matter what I enter it always prints "0".
Could someone please explain the problem?
user.species.toLowerCase needs to be user.species.toLowerCase(). By not calling the function you assign the function to user.species and thus it never matches any of the cases. You should also add a default case to catch these issues.
Replace your code with -
user.species = user.species.toLowerCase();
toLowerCase is a function.
Reference - http://www.w3schools.com/jsref/jsref_tolowercase.asp
You are missing () on user.species = user.species.toLowerCase;
There are five cases that are accepted. Still kind of a newbie to Java, so this is a slightly odd case. As far as I can tell (I've read the code at least twice) it should work perfectly fine, unless the double switch is making it not function... I get the error "SyntaxError: Unexpected token case"
var shouldWeapon = String("sword");
var user = prompt("There's a duck in a pond. It likes fish. What do you do? Would you like to feed it, kill it, skin it, buy it, or fight it").toLowerCase();
switch(user) {
case 'feed it':
var whatHaveFood = prompt("What do you have for food?").toLowerCase();
switch(whatHaveFood) {
case 'pancakes':
console.log("Great! Ducks love their pancakes!");
break;
case 'muffins':
console.log("I'm sorry what? You carry muffins? Ducks LOOOOOOOOOOOVE MUFFINS LIKE OMIGOSH I LOVE MUFFINS MMMM M M MMMM MMM IN MY TUMMY.");
break;
case 'dormant spiders':
console.log("You decide not to give them to the duck. They're yours. Nobody gets your dormant spiders.");
break;
case 'apple':
console.log("OH BOY I LOVE APPLES -said no duck ever.");
break;
default:
console.log("The Duck doesn't like that. He curses you to the pits of hell and walks away.");
break;
};
break;
case 'kill it':
var whatHaveWeapon = prompt("What sort of weapon do you have?").toLowerCase();
if(shouldWeapon || whatHaveWeapon){
console.log("Why Aren't you using a sword? Why are you using a " + String(whatHaveWeapon) + ". They Suck!");
}else{
console.log("Good choice. The Duck is vanquished.");
}
break;
case 'skin it':
var tempCat = prompt("What temperature is the cat?");
if(tempcat > 4){
console.log("Don't skin ducks.");
}
else{
console.log("That's a freaking cold cat.");
}
break;
case 'buy it':
var buyDuckCost = Math.floor(Math.random()*5 + 1);
var buyDucky = ("How much money do you have?");
var missingMoney = buyDuckCost - buyDucky;
if(buyDucky >= buyDuckCost){
console.log("You have bought a duck! congratulations!");
}
else{
console.log("I'm sorry you don't have that much money. You still need" + String(missingMoney) + "$! The duck pulls out a gun and shoots you.");
break;
case 'fight it':
var Smickle = true
var Donkey = false
if(Donkey || Smickle){
console.log("YOU CAN'T FIGHT THE DUCK. THE DUCK IS TOO STRONG");
}
else{
console.log("Ummmm... this is the only accessible answer..... OMEGA GOOD JOB*Cute anime loli voice.*")
}
break;
console.log("What? You're going to do what with the duck?")
default:
}
As far as I know, this should function....
In this part ("buy it" case), you are missing this end brace.
else {
console.log("I'm sorry you don't have that much money. You still need" + String(missingMoney) + "$! The duck pulls out a gun and shoots you.");
} //<<-- missing this end brace
break;
Code working here