Alternative way of changing the game state

    if (input == "1" || input == "2" || input == "3") // This checks if any of these conditions are met.
    {
        if (input == "1")
            level = 1;
        else if (input == "2")
            level = 2;
        else
            level = 3;
        StartGame();
    }

I forgot if we’ve done logical operators but there you go. The drawbacks to this is that the main if statement checks 3 conditions as opposed to 1 for each and it’s slightly harder to read, but this way, it’s actually still readable and more succinct.

EDIT

Also an important note; if your if statement only has one line of code to execute, then you can leave out the curly brackets and the if statement will just execute that one line of code. Therefore, the main if statement has curly brackets, while all the other statements don’t. StartGame() will execute no matter which condition is met.

The benefit to this is brevity, while the drawback is smaller flexibility (if you want to add more lines to the if statement, you must have curly brackets).

1 Like

Also an alternative way.
Use Switches.

switch(input){
    case "1":
        level = 1;
        StartGame();
    case "2":
        level = 2;
        StartGame();

etc

And then there is this.

int newLevel;
int.TryParse(input, out newLevel);
if(newLevel != null) if(newLevel > 0 && input < 4){ //or if((newLevel != null) && (newLevel > 0 && input < 4)){
    level = newLevel;
    StartGame();
}
2 Likes

Privacy & Terms