Search code examples
javascriptswitch-statementprompt

How to return to last prompt after spelling mistake?


So I am trying to create little text based game. The problem is that when someone makes a spelling mistake, it will always end the game via the "default" clause where I had to put an alert. Is there any way to make it go back to caveAnswer prompt when someone type incorrect answer?

var caveAnswer = prompt("you are in the cave", "type GO or EXIT").toUpperCase();
        switch(caveAnswer){
            case "GO":
                prompt("some text...", "type blabla");
                break;
            case "EXIT":
                alert("COWARD! HAHAHA!");
                break;
            default:
                alert('I dont understand ' + caveAnswer);
                break;
        }

Solution

  • Wrap in inside a function and have the default case call itself to show the prompt again.

    function ask() {
        var caveAnswer = prompt("you are in the cave", "type GO or EXIT").toUpperCase();
    
        switch(caveAnswer){
            case "GO":
                prompt("some text...", "type blabla");
                break;
            case "EXIT":
                alert("COWARD! HAHAHA!");
                break;
            default:
                alert('I dont understand ' + caveAnswer);
                ask();
                break;
        }
    }
    
    ask();