@ben mentions with regards to repeating yourself with the code to handle level 1 and level 2 that there might be “a cleverer way of doing things”. For fun I handled level 3 too but the repetitiveness didn’t sit well with me, so I decided to find a better way. Of course if none of this means anything to you, don’t worry I’m sure this will all be dealt with in a later lecture.
First of all, I earlier pre-empted that we’d be dealing potentially with a large number of conditions here so rather than stacking loads of if/else if statements, there is an alternative which is switch/case. I won’t go into exactly how it works other than I’ll share my alternative to the whole if (level == "menu")
block etc. using switch/case, this is before I started adding the level conditions:
switch (input)
{
case "menu":
case "m":
ShowMainMenu();
break;
case "007":
Terminal.WriteLine("Please select a level, Mr. Bond:");
break;
default:
Terminal.WriteLine("Please choose a valid level:");
break;
}
As well as being easier to read, this code theoretically should be more performant (more significant when you’re dealing with many more cases to be fair).
This also handles where different cases can run the same code, e.g. we can show the menu here whether the user types menu
or m
.
Of course a similar thing can be done with if statements as well but I’m sure that’s for a future lecture too, but that’d presumably be something like (assuming C# is the same as other languages like JavaScript and PHP):
if (input == "menu" || input == "m")
When it comes to adding the level number cases, the cleverest way I think to handle that is probably a bit advanced for this stage but I’ll share it anyway:
switch (input)
{
case "1":
case "2":
case "3":
level = int.Parse(input);
StartGame();
break;
case "menu":
case "m":
ShowMainMenu();
break;
case "007":
Terminal.WriteLine("Please select a level, Mr. Bond:");
break;
default:
Terminal.WriteLine("Please choose a valid level:");
break;
}
Here we execute the same code whether the user inputs “1”, “2” or “3” but we need to store that input in a member variable and ideally as an integer, but the value we have is a string.
As a side note, the Microsoft docs on C# really are quite good from what I’ve seen so far, and that is what brought me to the above solution.
level = int.Parse(input);
The Parse
function here converts a literal string representation of a number into an integer.
This is all totally optional and unnecessary at this stage and I’m sure it will get covered later but if it got you thinking already then hopefully you’ll find it interesting