Repeat the switch statement until it receives a valid response
I am starting to try to create a text adventure game in JavaScript and I need to repeat a switch statement until the user enters the correct 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 not an option.");
}
Any answers would be very helpful - thanks!
+3
source to share
2 answers
Wrap your code with some function and a callback
function in a 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 not an option.");
run() //callback
}
}
run()
+5
source to share
You can use a simple structure do ... while
.
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)
+2
source to share