General Coding improvement query

Hi there, I am playing around with the terminal, early doors. I just added a little extra to get the user choice to print the particular choice as well as the level. I have chosen to set a string and pass it through to the StartGame, you’ll see below.

Is there a more efficient way of doing this? I was trying to use a CASE for this specific bit but couldn’t work it out. Not sure if would be any more efficient anyway. Any thoughts from more expert programmers out there? I am pretty new, though I have done the sister course, I am still learning to implement concepts on my own.

   int level;
    string gameName;

    void OnUserInput(string input)
    {
        if (input == "1")
        {
            level = 1;
            gameName = "NSA";
            StartGame(gameName);
            
        }
        else if (input == "2") {
            level = 2;
            gameName = "CIA";
            StartGame(gameName);
            
        }
        else if (input == "3")
        {
            level = 3;
            gameName = "BPA";
            StartGame(gameName);
           
        }
        else if (input == "menu")
        {
            ShowMainMenu();
        }
        else 
        {
            Terminal.WriteLine("Please choose an option....");
        }
    }

    private void StartGame(string gameName)
    {
            Terminal.ClearScreen();
            Terminal.WriteLine("You have chosen level " + level);
            Terminal.WriteLine("Let's break into the " + gameName);
    }

Hi Andy,

You have declared a member variable, e.g. a variable which belongs to the instance of the class. As such, this variable will be available within all of the methods within that class without you needing to specify it within the method defintions, e.g.

private void StartGame(string gameName)

You will just need to make sure that you reset it and the correct point so that it reflects the correct game, should a player return to the main menu for example.

As such, you can change your StartGame method definition to;

private void StartGame()

…and the instances where you call it and pass the variable in can be simplified to just;

StartGame();

Hope this helps :slight_smile:


See also;

Ah ok thanks Rob, good point.

1 Like

You’re welcome Andy :slight_smile:

Privacy & Terms