Lesson 07.5: Monster and Combat Refactoring

After adding in a lot of new code, it’s a good to do some refactoring and cleanup. This lesson will help us keep our code easier to work with in the future.



Lesson Steps


Step 1: Edit Engine\ViewModels\GameSesssion.cs

When we added the HasMonster property, we didn’t use a getter and setter. Instead, the value of that property is determined by checking if the CurrentMonster property is null.

We’ll do the same with the four “HasLocation” properties (on lines 59 through 69 below), and replace the “get” and “return” with “=>”.

This doesn’t change the code. But, it is a little easier to read – which will help us.





Step 2: Edit Engine\Factories\ItemFactory.cs

In the current code, we initialize _standardGameItems inside the constructor. However, we can do that where we declare it, on line 9, and remove the initialization from the constructor.

I’ve also set _standardGameItems as “readonly”. We don’t need to ever set this to a new list – we only ever add to the initial list. So, we can make the code more restrictive by making the variable readonly (where you can only set it once).

It’s usually a good idea to make your code as restrictive as possible. This prevents you from accidentally doing something later that you didn’t want to do.





Step 3: Edit Engine\Factories\WorldFactory.cs and Engine\Models\World.cs

When we create each location, we pass in the same string “/Engine;component/Images/Locations/” for each location’s image. We can move that to the AddLocation function in the World class.

You generally don’t want to repeat code, including values. If you add more locations to the game, it would be easy to accidentally mistype this information. So, it’s safer to move it to one place (like we do in the Monster class).

In WorldFactory.cs, remove that string from all the calls to newWorld.AddLocation.

Then, in World.cs, change line 20 to include the common string.

We’ll also make the _locations list readonly, like we did with _standardGameItems in ItemFactory.cs (in step 2).






Step 4: Edit Engine\Models\Monster.cs

In World.cs, we used “string interpolation” to combine the image file name with its resource location information. So, let’s stay consistent, and make the same change to line 35 of Monster.cs.





Step 5: Edit WPFUI\MainWindow.xaml.cs

See that private _gameSession variable on line 13? It’s only set once, in the constructor. So, that’s another variable we can make readonly.

We can also initialize it on line 13, and remove the line that was initializing the variable in the constructor.





Step 7: Test the game, to make sure it still works.



Return to main page

Leave a Reply

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