Lesson 03.4: Creating the GameSession (ViewModel) Class

In this lesson, we will create a ViewModel. This is a class that will manage communication between the View (MainWindow.xaml) and the Models (currently, only Player.cs).

Using a ViewModel makes it easier to create automated tests (which we will do later), or create a different type of user interface (such as a web browser-based version of the game).

 

 

Summary

  • A ViewModel is designed to manage how the Views and Models communicate with each other.
    • We can use this class to manage different models. For example, when the player is in combat, we will need to manage a Player object and a Monster object.
    • By having the extra class, we gain the ability to create automated tests. So, we won’t need to manually (and slowly) test our program.
    • This also gives us the ability to easily create a different UI – to convert the program to a web game, or text game.
  • In the Player class, the property datatypes are “string” and “int”.
    • In this model class, we will use Player as the datatype for the CurrentPlayer property – because that property will hold a Player object.
    • If a class uses a class in a different namespace, you need to include a “using” statement at the top of the class, so it can “use” the classes in the other namespace.
  • When you need an object, you call the constructor on a class.
    • This is like “filling in” the “blank form” of the class.
    • If we don’t define a constructor, the class still automatically has a default constructor.
    • We can use the constructor to perform additional steps, when the class is created. For example, setting property values.
  • “Scope” is the visibility level of a class, property, or variable.
    • For now, we will use “public” – the most-visible scope. In the future, we will reduce the scope of some properties.
  • A single equal sign “=” is used when you want to assign a value to a variable, property, object, etc.
    • The value on the right of the equal sign is evaluated, and assigned to the variable on the left of the equal sign.

 

Source Code

In the Engine project, right-click on “Engine”, and add a new folder named “ViewModels”.

Right-click on the ViewModels folder, and add a new class named “GameSession.cs”.

 

Modify Player.cs, to look like this:

 

Return to main page

Leave a Reply

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