Press "Enter" to skip to content

Lesson 04.1 – Creating the Player class and its properties

Lesson Objectives

At the end of this lesson, you will know…

  • How to determine the properties for a class.
  • How to select the correct “datatype” for each property.
  • How to create a class.
  • Two different ways to store property values.

 

What are properties?

The properties of a class, or object, are the pieces of information about it that can be different in each object, or could change while the program is running.

In an RPG, that would be things such as the amount of gold, experience points, items in inventory, etc. We need a place to hold those values for the object, and the ability to change those values.

 

What are datatypes?

The datatype is just a geeky way to answer the question, “What kind of information are we going to store in this property, or variable?”

To start out, we’re only going to look at two datatypes: integers and string.

An integer, if you remember back to math class, is a whole number – one that doesn’t have any decimal value. This is what we need for the player’s experience points, gold, and level.

A string is letters, miscellaneous characters (such as, @#$%^&*), or numbers treated as letters.

We don’t need any strings for our Player class, but we will have them in other classes. If you want to save a number to a string property or variable, it needs to be in quotes (“1”, instead of 1), or you need to convert it from a number to a string (we’ll see that a little later).

Once you declare the datatype for a property or variable, you can only store that type of data in it. So, you can’t say that ExperiencePoints has an integer datatype, then try to save a string in it.

Note: Adding together strings that contain numbers in them acts differently from adding together numeric datatypes.

For example, if you try to add together the integers 1 and 2, you’ll get an answer of 3. But when you add the strings “1” and “2”, you get “12”. This is called “concatenating strings”.

 

The properties of the Player class

Our Player class is going to be very simple. The only things we care about it (for now) are:

  • The player’s current hit points (in case they’ve lost any during battle)
  • The player’s maximum hit points (when they are fully healed)
  • The amount of gold the player has
  • The amount of experience points the player has
  • The player’s current level
  • The datatype for all these properties will be “integer”, since we only need to store whole numbers in them.

In a future lesson, we’ll add their items in inventory and the quests they have.

 

Creating the Player class

 


Link to video on YouTube

 

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

 

Step 2: In the solution explorer, right-click on the “Engine” project. Select “Add”, then “Class”. Change the name of the class from “Class1.cs” to “Player.cs” (be sure to keep the original “.cs” at the end, but don’t add a second “.cs”). Press the “Add” button.

Now you are editing the code for the Player class.

 

Step 3: Change line 9 so it says “public class Player”. We’ll discuss why in a minute.

 

Step 4: Go to the end of line 10 (to the right of the “{” character) and press the enter key, to make some space to add the properties.

 

Step 5: Type in these lines:

public int CurrentHitPoints { get; set; }
public int MaximumHitPoints { get; set; }
public int Gold { get; set; }
public int ExperiencePoints { get; set; }
public int Level { get; set; }

Notice that we don’t have a space between the words “current”, “hit”, and “points” (along with the MaximumHitPoints and ExperiencePoints). You can’t have a space in the middle of a property, or variable name. So, we use upper-case letters to show where each word starts. This isn’t a requirement of C#, but it is how many programmers write property names. It’s known as the “Pascal case” style.

NOTE: In C#, matching upper and lower case is important. A variable, or property, named “test” is different from one named “Test”.

 

What did you just do?

OK, you’ve typed in the code, but what does all of it mean?

First, we’ll start with “public”. This is known as the “scope”. It signifies what other parts of the solution can see the class or property. “Public” means that it is visible throughout the whole solution. This way, the UI project will be able to create a Player object and read the values of its properties.

We’ll talk about some of the other scope options in later lessons.

Next, what’s happening on lines 11 through 15?

These are the properties of the Player class. They’re public, since we need to have them visible everywhere. The “int” says that their datatype is an integer. Then we have the name of the property. Finally, there is a “{ get; set; }” after each property. Those signifies that we have a property where we can “get” a value (read what is stored in the property) and “set” a value (store a value in the property). We’ll see these in action soon.

What’s on lines 1 through 5?

That is a bunch of stuff we don’t need for this class. But, when you create a new class in Visual Studio, it adds that in automatically, in case you will need it. For now, don’t worry about it.

 

Summary

Now you’ve created the Player class. Once your program creates (instantiates) a Player object, it will be able to read and change the values of the object’s properties.

 

Source code for this lesson

Source code on GitHub

Source code on DropBox

 

Next Lesson: Lesson 05.1 – Creating objects from classes

Previous lesson: Lesson 03.1 – Building the first screen

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

20 Comments

  1. rajath
    rajath July 7, 2016

    This is the best way to learn a language or its concepts. Amazing.

    • vassilios simeonidis
      vassilios simeonidis August 6, 2021

      He is wrong in 0 ways. I always had trouble coding before this and this has helped a lot thank you.

  2. Simeon
    Simeon October 9, 2017

    After i completed the steps in SuperAdventure.cs, CurrentHitpoints and MaximumHitpoints are still red.

    • Scott Lilly
      Scott Lilly October 9, 2017

      Check the CurrentHitPoints and MaximumHitPoints properties, to make sure they are “public”. If they are, check if the Player class is public (step 3).

      If those are all public, the problem could happen if the SuperAdventure project does not have a reference to the Engine project. The instructions for that are in step 6 of Lesson 02.2.

      Please tell me if none of those fixes the problem.

  3. josh
    josh October 27, 2017

    Thank you very much for this. I’m making a pong clone using MonoGame as a learning experience.

    I wanted to make a separate class to define values for my Player and Enemy, such as texture and position, but I was not sure how to do it correctly.

    So, I searched “C# make player class”, and this post was the first result.

    • Scott Lilly
      Scott Lilly October 29, 2017

      You’re welcome. I hope the lessons help you make your game.

  4. Pendrake
    Pendrake December 20, 2017

    When you make references to particular lines of code “Change line 9…” mines seems to be off by one…and it ends up that way later also. I’ve taken the tutorial farther than this step but then started over because I thought I had done something wrong….but I followed each step and it remains the same.

    • Scott Lilly
      Scott Lilly December 20, 2017

      The lessons were written for Visual Studio 2013 (because that was the most-recent version, when I wrote them). With a newer version, Visual Studio might include a different number of “using” statements, which would change the line numbers. If you look at the source code in each lesson’s Gist page, it should help you see which lines need to be changed.

      • Pendrake
        Pendrake December 21, 2017

        The “Using.System.Threading.Tasks;” is the line missing from all my classes and the entire project…is this a necessary line?….it seems to still run without it.
        VS 2017 Community.
        P.S. Thank you for taking your time to answer my posts. I’m very excited to get to a point where I actually understand what I’m looking at and typing. I understand some aspects of coding but other aspects still have me utterly confused.

        • Scott Lilly
          Scott Lilly December 22, 2017

          You should not need anything from System.Threading.Tasks. So, you should be able to all complete the lessons without that “using” line.

          You’re welcome. When going through the lessons, it always help to take time to understand what the code is doing. If there is something you don’t understand, you can use the debugger to follow through the program as it executes the code. Here is a demonstration of how to use the debugger: https://www.scottlilly.com/how-to-use-the-visual-studio-2013-debugger/.

  5. NotARobot
    NotARobot January 24, 2018

    I’m sorry but would you explain what does mean UI project, i got that it is a the first project that was created with the solution. But are there any futures that are important.

    • Scott Lilly
      Scott Lilly January 24, 2018

      When you write a program with Visual Studio, you create a “solution”. The solution can have one or more “projects”. Programmers often create a project to hold classes that do the same type of work. For example, you might put all your classes that read or write to a database in one project. Then, if you ever need to make a change to the database classes, you know where they are. If you have all your classes in one project, it can be difficult to find the correct class. This is extremely helpful when you have solutions with a million lines of code, in thousands of classes.

      For this game, we have two projects. The “Engine” project to hold the logic for the game, and the “UI” project to hold the information about the screens (colors, size, where the labels are located, etc.). At the start of these lessons, we have some game logic in the UI project. But, we move that to the Engine project later.

      Is that clear?

  6. Noname Nips
    Noname Nips March 20, 2018

    Is there any difference between using a getter and setter
    (public void SetLevel(int Level) {
    this.Level = Level;
    }

    public int GetLevel() {
    return Level;
    })
    compared to using the get; set; within the Gold methods you’ve written?

    Thank you btw, this is a great tutorial for understanding C# 🙂

    • Scott Lilly
      Scott Lilly March 20, 2018

      You’re welcome. You could use GetLevel and SetLevel methods, but that convention is more common in Java. C# programmers normally use the “public int Level { get; set; }” style.

  7. NotAsmartOne
    NotAsmartOne June 10, 2018

    Good evening.

    About {get; set;}
    Why can’t we just declare them simply like:
    public int level = new int;
    Then just simply change the level like:
    level+=1; //like here we set a new value and then something like that
    Console.WriteLine(level); //There we get the value.

    In short, what remarkable changes {get; set;} system gives over just declaring in a simple way : public int x =new int; ???

    Thank You.

    • Scott Lilly
      Scott Lilly June 10, 2018

      In C#, if you have “public int Level;”, then Level is a “field”. When you have “public int Level { get; set; }”, Level is a “property”.

      You can do some things with properties that you cannot do with fields. For example. you can bind a property to the UI. Then, when the property value changes, it can automatically update the UI. Also, we can add more code into the get and set logic. Right now, they don’t do anything special. But, we will add code to some of the properties “setters” in future lessons.

      For example, we will eventually make Level a derived property. We will remove the “set” and it will only have a “get”. The value for the “get” will be calculated from the ExperiencePoints value.

  8. JamesU
    JamesU February 17, 2019

    Dear Scott,

    I like watching your videos as I am just starting to learn C# using visual studio. I have no experience with visual studio in terms of building anything. The videos are very basic which is great.

    I have twoproblems with my program currently, more not understanding visual studio likely.

    1) In the video you deleted the buttontest code, and I did that too, however I might have missed where you took the button control off the first form that was created. (so button code deleted, but button form object not deleted.) When I tried to view the form, it gave a warning, which I ignored 🙂 and now the form is blank in form design view. The form is Superadventure.cs [Design]. When I run build, it fails, saying something about a button. The button control is still on the form, but the button code is deleted. Now I cant view the form in design view anymore, its completely blank.

    2) The second problem is private Player, this word Player is red underlined in my program. Under engine section in solution explorer, I have correct case Player.cs and in your video after private Player, this word Player goes blue, but mine remains red underlined and I’m not sure why.

    Any help appreciated, in the meantime, I will likely start from scratch with the code, I was just hoping something easy was available in case I mess up later with a similar delete code but not form object issue.

    Thanks

    • Scott Lilly
      Scott Lilly February 17, 2019

      Hi James,

      When you build your solution, do you see an error message at the bottom of Visual Studio, in the “Error List” tab? It will say something like “‘SuperAdventure’ does not contain a definition…”. If you see that, double-click on the error and it should take you to the line in SuperAdventure.Desinger.cs where it has a “new System.EventHandler” for the button (with the button function name underlined with a red squiggle). You can delete that line. It’s the line that tries to connect from the button to the (deleted) function that was supposed to run when the button was clicked. You can read more about eventhandlers in Lesson 21.3, if you want.

      for the player variable, there are four things that are likely to be the source of the problem.
      1. Make sure the Player class (in the Engine project) is defined as public, with “public class Player” near the top of the class file, and that the “P” in Player is upper-case.
      2. In the SuperAdventure project, did you add a reference to the Engine project (step 6 of Lesson 02.2)?
      3. When you created the Engine project, did you give it a different name (including if the upper and lower-case letters are different)?
      4. In SuperAdventure.cs, did you add “using Engine;” with the other “using” statements at the top of the class file?

      Let me know if that doesn’t help you fix the problems, or if you have any other questions.

Leave a Reply

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