Lesson 21.1 – Adding a price to game items

If we want the player to be able to buy and sell items, we need to add prices to each Item object.

 

Step 1: In the Engine project, edit the Item.cs class.

Add an integer “Price” auto-property to the class, add a price parameter to the constructor, and set the Price property’s value in the constructor.

The Item class should look like this now:

 

Step 2: Now that the Item constructor requires a price parameter, we need to change the classes that use Item as their base class – Weapon and HealingPotion.

We will change their constructors to accept a “price” parameter, and pass it to the base (Item) class constructor. This is how they should look now:

 

HealingPotion.cs

 

Weapon.cs

 

Step 3: The next change will be to the World class, where we create instances of the items. Change the PopulateItems() function to this (you can use your own prices for the items):

 

NOTE: For the Adventurer pass, we set the item’s value to -1. We’re going to use that as a “flag” (indicator) value. In our code to display the player’s items, we won’t include any items that have a value of -1. Those will be unsellable items.

 

Step 4: So you can see how I think when I’m programming, I left the “Note” in step 3.

However, if I need to add a note for the lesson, that might also mean something is not clear in the code. I don’t want to make a change in the future, and forget why some items have a value of -1.

This is a “code smell” – a sign that the source code may have a problem.

Let’s make this easier to understand.

In the World class, add this new class-level, public constant, near the other constants at the top of the class:

Then, change the Adventurer pass line in PopulateItems() to this:

Now, it is very clear that we don’t want the player to be able to sell adventurer passes. We won’t ever be confused by a “magic number” – a hard-coded value that has a special meaning.

 

Step 5: Run your program, and make sure it still works. Right now, you won’t see the price anywhere. But, it’s good to check your program after each change.

 

Source code for this lesson

Get it from GitHub: https://gist.github.com/ScottLilly/259f1eed1799e9c4c642

Or DropBox: https://www.dropbox.com/sh/7xiig6wwd1yvd5z/AADvmfnae-931WEYYXziMA9Ya?dl=0

 

Next lesson: Lesson 21.2 – Create the vendor class and add it to locations

Previous lesson: Lesson 21.0 – Plans for adding a vendor to locations

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

Leave a Reply

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