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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With