Lesson 16.1 – Writing the function to move the player

Lesson Objectives

At the end of this lesson, you will know…

  • How to plan a function
  • How to write the code/logic for a function
  • Some of the most common C# commands

 

Ok, we’ve spent all this time building up the pieces we need for our game. Now it’s time to actually get the game to do something. The first thing we’re going to add the code to handle when the player moves to a new location.

By the way, this is a long lesson, and covers a lot of new things. So make sure you have some time to complete it.

Outline of the function

The first thing we need to do is figure out what’s going to happen during a move.

When I write a function that needs to do a lot of things, like this one, I like to do some planning first – so I don’t miss anything.

When the player moves to a new location, we’ll completely heal them, we’ll check to see if the location has any quests (and if the player can complete them), and if there are any monsters to fight there.

Here is an outline of the logic for a player move function. Something like this is often called “pseudo-code”. It isn’t C# code, but it represents what the code will do.

Each indentation level is where we handle a different condition – for example, the steps to follow if the location has a monster, and the steps to follow if the location doesn’t have a monster.

  • If the location has an item required to enter it
    • If the player does not have the item
      • Display message
      • Don’t let the player move here (stop processing the move)
  • Update the player’s current location
    • Display location name and description
    • Show/hide the available movement buttons
  • Completely heal the player (we assume they rested/healed while moving)
    • Update hit points display in UI
  • Does the location have a quest?
    • If so, does the player already have the quest?
      • If so, is the quest already completed?
        • If not, does the player have the items to complete the quest?
          • If so, complete the quest
            • Display messages
            • Remove quest completion items from inventory
            • Give quest rewards
            • Mark player’s quest as completed
      • If not, give the player the quest
        • Display message
        • Add quest to player quest list
  • Is there a monster at the location?
    • If so,
      • Display message
      • Spawn new monster to fight
      • Display combat comboboxes and buttons
        • Repopulate comboboxes, in case inventory changed
    • If not
      • Hide combat comboboxes and buttons
  • Refresh the player’s inventory in the UI – in case it changed
  • Refresh the player’s quest list in the UI – in case it changed
  • Refresh the cboWeapons ComboBox in the UI
  • Refresh the cboPotions ComboBox in the UI

 

Creating a shared function

We have four different functions for movement, one for each direction. And we need to do the steps shown above for moving in each direction.

We could do that by writing the same code in each function. But then, if we ever want to change that logic, we’d need to make the change in four places – and that often leads to mistakes.

So, we’re going to create a new shared “MoveTo” function to handle movement to any location. Each of the four movement functions will call that one new function.

Storing the player’s location

We also need a place to save the player’s current location. Since this value will change, we need to store it in either a variable or a property.

In this case, we’ll make a property in the Player class. It makes sense to do this because a player’s location is a “property” (in the general sense) of the player.

Storing the current monster

We also need a place to store the current monster that the player is fighting, in case they move to a location that has a monster there.

In the World class, we have a list of all the monsters in the game. However, we can’t use the monsters from there to fight against. We only have one “instance” of each monster. So, if we fought against the rat in the World.Monsters list, and killed it, the next time we fight against it, it would already be dead.

When we move to a new location, if it has a monster there, we’ll create a new instance of that type of monster and save it to a variable. Then, the player will fight against that instance of the monster.

 

Now that we know what we want to accomplish, we’re ready to add the code.

 

Creating the functions to move the player

Step 1: Start Visual Studio Express 2013 for Desktop, and open the solution.

Step 2: First, let’s create the new property to store the player’s current location.

Double-click on the Player class, in the Engine project. Add a new property named CurrentLocation, with a datatype of Location.

Note: You don’t have to put the properties in any specific order. I just like to like to keep my List properties at the end of the properties. I find it a little easier to read when they’re grouped in the same place in every class.

Step 3: Right-click on the SuperAdventure.cs form, in the SuperAdventure project, then select “View Code”.

Step 4: Because we have a lot of code to write, and it’s easy to mistype something, copy the new code for the SuperAdventure form from here (https://gist.github.com/ScottLilly/208630cfcdded1cbfdc0) and overwrite all the existing code in SuperAdventure.cs with it.

 

What’s in the code you just added?

On line 18, we added a new variable to hold the monster that the player is fighting at the current location.

In the form’s constructor, we do a couple things to start the game.

On line 25, we “move” the player to their home. Since the MoveTo function expects a location as the parameter, we need to use the World.GetLocationByID() function to get the correct location. This is where we use the constant World.LOCATION_ID_HOME, instead of using the value 1. It’s much easier to look at the code with the constant and know what it’s supposed to be doing when we use this clearly-named constant.

On line 26, we add an item to the player’s inventory – a rusty sword. They’ll need something to fight with when they encounter their first monster.

We added the new MoveTo function to handle all player movement.

We’ve also gone into each of the four functions that handle moving in a different direction and had them call the MoveTo function.

The MoveTo function

The first thing you may notice in this function are the lines that have a “//” in them. These are comments. Comments are ignored by the computer. They only exist for programmers to read, to know what the program is supposed to be doing. Everything after the double-slashes, until the end of the line, is ignored by the computer.

I used a lot more comments in this function than I normally would. That’s to make it easier for you to follow along with what is happening, and see how the code ties back to the pseudo-code we have above.

The second thing you may have noticed is that this function is long – over 300 lines long.

That’s really too long for a function.

When a function is that long, it’s difficult to keep track of what exactly it’s supposed to be doing. But we’re going to clean this up in the next lesson. Personally, I like to keep my functions around 10 to 40 lines long.

We’ll break this function into smaller functions in the next lesson.

What’s happening in the MoveTo() function?

On line 57, we have our first “if” statement.

In this case, we check if the new location has any items required to enter it.

The “!=” is how C# says “not equal to”. The exclamation point, when doing any sort of comparison in C#, means “not”. And “null” means nothing/empty.

So, if the ItemRequiredToEnter property of the location is not empty, we need to check if the player has the required item in their inventory. If it is empty, we don’t need to do anything – there is no required item, so the player can always move to the new location.

On line 72 we see if we found the required item in the player’s inventory. If we didn’t find an item with a matching ID, the “playerHasRequiredItem” variable will still be “false”.

Notice the exclamation point in front of playerHasRequiredItem.

Let’s assume the player does not have the required item in their inventory. The “playerHasRequiredItem” variable will have a value of “false”. Doing a “not” on a Boolean variable, reverses its value: “!true” equals “false”, and “!false” equals “true”.

Thinking “if not false” is not as clear as thinking “if true”. But they both mean the same thing.

On line 75, we display the message that the player is missing the item required to enter this location. This line has a new “+=” symbol.

“+=” means, take the value from the variable/property on the left, add the value on the right to it, and assign the results back into the variable/property on the left.

When you use “+=” with a string, it means, “add the string value on the right to the end of the existing string”. When you use it with a number, it means, “add the value on the right to the value on the left”.

Here, we take the text in the rtbMessages RichTextBox, and add our new message to the end of it. That way, the player can still see the old messages. If we used the “=” sign instead, it would replace the existing “Text” value with our new message.

We also have “Environment.NewLine”. This adds an “Enter” to the text, so the next thing we add to it will be displayed on the next line, instead of the end of the current line.

Line 76 has “return”. This means “exit out of this function”.

Since this function is a “void” function (see line 54), it doesn’t return a value. We can “return” here and not do the rest of the function. We want to do that in this case, because the player does not have the item required to enter the location. So, we don’t want to do the rest of the function, which would actually move them to the location.

On lines 84 through 87, we make the movement buttons visible, or not, based on whether or not the new location has a place to move to in each direction. We do this by checking if the property for the location is empty or not.

The “Visible” property of the buttons expects a Boolean value: true or false.

So, on line 84, if the LocationToNorth property is not empty, the value to the right of the equal sign will evaluate to “true”, and the button will be visible. If the LocationToNorth property is empty, this will evaluate to “false”, and the button will not be visible.

On line 100, we check if there is a quest at this location. If so, we need to do some more work.

Lines 106 through 117 are where we look through the player’s quest list, to see if they already have the quest at this location and if they already completed it.

Lines 128 through 163 looks at each item required to complete the quest, then checks each item in the player’s inventory, to see if they have it, and have enough of it, to complete the quest.

There are some “break” statements in this “foreach”. Those are used to stop looping through the items and exit the “foreach” loop. If we discover that the player doesn’t have one item, or enough of it, to complete the quest, we can stop checking for any other items.

Line 180 has a “-=”. The “+=” means, “add the value on the right to the variable/property on the left”. So, a “-=” means, “subtract the value on the right from the variable/property on the left”. You can only use this with numbers, and not strings, unlike the “+=”.

In this case, we are using it to remove items from the player’s inventory that they turn in to complete the quest.

On line 204, there is a “++”. When you have this after a variable or property, it means “add 1 to this variable or property”. There is also a “–“, for when you want to subtract 1 from a variable or property.

At lines 264 through 273, we create the new monster to fight, by making a new monster object, using the values from the standard monster in our World class.

Updating the DataGridViews in the UI

From lines 290 through 321 we update the DataGridView controls in the UI.

The player’s inventory will have changed if they completed a quest. The items needed to turn in were removed from their inventory. The reward item was added to their inventory. So, we need to update the UI with their current inventory.

Also, if they received a new quest, or completed an existing one, their quest list would change.

Updating the ComboBoxes in the UI

For the ComboBoxes in the UI, we create new lists to hold the specific datatype of items we want to show in the list (lines 324 and 353). Next, we go through all the items in the player’s inventory and add them to these lists, if they are the correct datatype (lines 326-335 and 355-364).

On lines 328 and 357, there is a new comparison: “is”. This is used to see if an object is a specific datatype.

Remember how we created the Weapon and HealingPotion sub-classes of the Item class? When you create a Weapon object, its datatype is both Weapon and Item. When you create a HealingPotion object, its datatype is both HealingPotion and Item.

If the lists are empty (weapons.Count or healingPotions.Count are equal to 0), we hide the ComboBox and “use” buttons, since there is no weapon or potion for the player to use.

If the lists have items in them, we “bind” the list to the comboboxes (lines 345-349 and 374-378). The “DisplayMember” determines what property will be displayed in the comboboxes. In this case, we want to display the value of the Name property. The “ValueMember” is the behind-the-scenes value we’ll use a little later, to know which item was selected.

NOTE: There are better ways to connect your list properties to DataGridViews and ComboBoxes. But we’re just concentrating on the basics in these tutorials.

NOTE: Hopefully you noticed something about the variable names. They are generally long and descriptive. That makes it easy to understand what values they are supposed to hold. By making your variable names descriptive, it will be easier to work with your program – especially when fixing bugs or making changes in the future.

There are a couple cases in the “foreach”s where I use short variables like “qci” and “ii”.

Since the foreach loop is only a few lines long, I sometimes use a shorter variable name. The variable has a very short life – it only exists within those few lines of the loop. You can display the whole loop on your screen, without scrolling. So, it’s easy to keep track of where the variable is populated and where it is used. If the loop was longer, I’d use a longer, more descriptive name.

 

Summary

Now you’ve seen how to plan out your logic in pseudo-code, and then create a function in the program to perform that logic.

You’ve seen how “if”s, “else”s, and “foreach”s are used in a function.

You’ve also seen what a huge function looks like, and you probably have an idea how difficult it would be to work with it. The next lesson will cover how to clean up that function and make it easier to understand.

We covered a lot in this lesson. If there was anything that wasn’t clear, please leave a comment below and I can update this lesson with some more details.

 

Source code for this lesson

Get it from GitHub: https://gist.github.com/ScottLilly/208630cfcdded1cbfdc0

or DropBox: Lesson 16.1 – https://www.dropbox.com/sh/mklgy3fjvixg9xg/AADp47PdxOYk_V7f7IvfLdS3a?dl=0

 

Next lesson: Lesson 16.2 – Refactoring the player movement function

Previous lesson: Lesson 15.1 – Getting random numbers for the game

All lessons: Learn C# by Building a Simple RPG Index

73 thoughts on “Lesson 16.1 – Writing the function to move the player

  1. Just fyi, it looks like the source code from Github uses “dvgInventory” rather than “dgvInventory”. I’m assuming it should be the latter, since it is supposed to represent a DataGridView. Kinda messed me up because I had it the other way in my original code, and I overwrote everything in this lesson with the recommended code, and it didn’t match the UI project.

  2. Hi Scott,

    Happy 2017!

    I’m getting the ‘System.NullReferenceException’ with reference to this part:

    foreach(QuestCompletionItem qci in newLocation.QuestAvailableHere.QuestCompletionItems)
    {
    if(qci.Quantity == 1)
    {
    rtbMessages.Text += qci.Quantity.ToString() + ” ” + qci.Details.Name + Environment.NewLine;
    }
    else
    {
    rtbMessages.Text += qci.Quantity.ToString() + ” ” + qci.Details.NamePl + Environment.NewLine;
    }
    }

    Could help me out?

    Best

    L

      1. Awesome, that helped, thank you!

        NamePl was missing, because it was referring to a loot item I added later on to the loot table, but not to the Items list.

        NamePl is initiated only while adding an item to the list and hence the exception.

  3. Hi Scott

     

    I have no error but when I run the game this pop up

    NullReferenceException was unhandled

    An unhandled exception of type ‘System.NullReferenceException’ occurred in Rpg.exe

    What is the problem and how do I handle it

        1. You need to add this line as the first line in the Rpg.cs constructor:

          InitializeComponent();

          This calls the InitializeComponent function in the Rpg.Designer.cs file, which instantiates the buttons (and other controls on the form). This must be done before the line “MoveTo(World.LocationByID(World.LOCATION_ID_HOME));”, because the MoveTo function tries to set the visibility on the buttons. So, the buttons must be instantiated first.

          Let me know if that does not fix it, or if you have any other questions.

Leave a Reply

Your email address will not be published. Required fields are marked *