Lesson 16.3 – Functions to use weapons and potions

Lesson Objectives

At the end of this lesson, you will know…

  • Nothing new. We’re just finishing the program, using the same things you learned in the previous lessons.

 

Now we’ll write the functions the player will use when fighting monsters.

We have two things they can do (besides click on one of the direction buttons, to run away from the battle): use a weapon on the monster or use a healing potion on themselves – if they have one in their inventory.

Here is the pseudo-code for the two functions:

Use a weapon function

  • Get the currently selected weapon from the cboWeapons ComboBox
  • Determine the amount of damage the player does to the monster
  • Apply the damage to the monster’s CurrentHitPoints
    • Display message
  • If the monster is dead (zero hit points remaining)
    • Display a victory message
    • Give player experience points for killing the monster
      • Display message
    • Give player gold for killing the monster
      • Display message
    • Get loot items from the monster
      • Display message for each loot item
      • Add item to player’s inventory
    • Refresh player data on UI
      • Gold and ExperiencePoints
      • Inventory list and ComboBoxes
    • “Move” player to current location
      • This will heal the player and create a new monster
  • If the monster is still alive
    • Determine the amount of damage the monster does to the player
    • Display message
    • Subtract damage from player’s CurrentHitPoints
      • Refresh player data in UI
    • If player is dead (zero hit points remaining)
      • Display message
      • Move player to “Home” location

 

Use a potion function

  • Get currently selected potion from cboPotions ComboBox
  • Add healing amount to player’s CurrentHitPoints
    • CurrentHitPoints cannot exceed player’s MaximumHitPoints
  • Remove the potion from the player’s inventory
  • Display message
  • Monster gets their turn to attack
    • Determine the amount of damage the monster does to the player
    • Display message
    • Subtract damage from player’s CurrentHitPoints
      • Refresh player data in UI
    • If player is dead (zero hit points remaining)
      • Display message
      • Move player to “Home” location
  • Refresh player data in UI

 

These are much simpler functions than the MoveTo() function.

We’ll be able to use some of the smaller functions we created during the refactoring lesson – for example, the AddItemToInventory() function, from the Player class, if the player defeats the monster and receives loot items.

 

Adding functions for monster battles

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

Step 2: Right-click on the SuperAdventure.cs form in the SuperAdventure project, to start working with the code for the UI.

To add the ability to use weapons and potions in combat, you can add in the code below, or replace the code for SuperAdventure.cs with the code here: https://gist.github.com/ScottLilly/b20787650f2ab2a78362

 

For the btnUseWeapon_Click function, add this:

 

Then, for the btnUsePotion_Click function, add this:

 

There isn’t really anything new in these two functions. Just more “if”s and “foreach”s to handle the player’s actions in battle.

 

Summary

Now you have a working game. The player can move around in the world, get quests, battle monsters, receive loot, and complete quests.

These new functions could use some refactoring, since they are long and do several things. I’ll leave that to you to figure out what refactoring you’d do.

 

Source code for this lesson

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

or DropBox: Lesson 16.3 – https://www.dropbox.com/sh/pjus6771thkyw8c/AABPapeJr_ady82-prXZSeVja?dl=0

 

 Next lesson: Lesson 17.1 – Running the game on another computer

Previous lesson: Lesson 16.2 – Refactoring the player movement function

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

140 thoughts on “Lesson 16.3 – Functions to use weapons and potions

  1. Addendum:

    Can you add the following topics to your tutorial:

    Automatic tests
    How to create a setup and install option
    (deployment)

    So we have a whole possible workflow in building a program.

    Greetings Sascha

    1. For automated tests (and continuous integration), I have two separate guides here: https://scottlilly.com/creating-unit-tests-with-mstest-and-visual-studio-community-2015/ and https://scottlilly.com/installing-teamcity-for-continuous-integration-of-a-visual-studio-solution/. The videos do not use this RPG program. But, you can use the same principles to add unit tests to any C# program.

      I added a note on my “to do” list, to show how to create an installer. But it might be a while until I can create that.

  2. Hey Scott,
    How exactly do you get the weapons to appear in the combo box? Most of my code is similar to yours despite a few modifications. The game would crash in a battle without having anything equipped, so I defaulted to give the player the rusty sword. Another thing too is after you defeat an enemy, the battle doesn’t end and another one just spawns. If you have any ideas, I’d be grateful to listen.

    1. Hi Ren,

      In the SuperAdventure.cs here on GitHub, the player should get a default rusty sword on line 26. If you don’t want a new monster to appear, after the player wins a battle, you could comment out (or remove) line 377 of SuperAdventure.cs. After winning a battle, that line “moves” the player to their current location – which spawns a new monster. If you remove that line, there should not be a new monster until the player really moves to a new location, by using the direction buttons.

      Please tell me if there are any problems with trying that.

      1. The issue regarding stopping the monsters from continuously spawning has been resolved. Though, while the player does have the weapon, it still does not appear in the combo box for weapons.

        1. I managed to resolve both issues with a little bit of tampering with some if-else statements. Everything is working as intended other than the only monsters appearing are rats.

          1. The way the game world is set up, you should only see rats at the Alchemist’s Garden. Are you seeing rats at the Farmer’s Field also? The Farmer’s Field should have snakes. If you see rats in the Farmer’s Field, the most likely place for the problem would be in the World class – in the PopulateLocations function.

  3. Thank you Scott for developing this great tutoral. I have learned so much from it. I have one problem: when running the program, the form seems inactive, and I cannot get anything to work on the form window. The labels and buttons seem grey, and as if I need to toggle something in the properties of the form. The btnNorth_Click method in SuperAdventure.cs class is correct. The btnNorth Click property is set to btn_North_Click, And the btnNorth section in the SuperAdventure.Designer.cs has all the proper code just as you mentioned in a previous post to another user who had the same issue. I copied and pasted into the solution the latest Player and SuperAdveture classes. I’m using VS2015. Any suggestions? Thanks again.

      1. Scott, Thank you for your help. Yes, the deleting the this.Enabled = false on line 286 in the SuperAdventure>designer.cs completely solved my problems. The program functions normal now. Thanks again and for this ‘Super’ tutorial!

  4. I have a little problem with my code. This line -> this.Load += new System.EventHandler(this.RPGAdventure_Load);

    The error massage says Error 2 ‘RPGAdventure.RPGAdventure’ does not contain a definition for ‘RPGAdventure_Load’ and no extension method ‘RPGAdventure_Load’ accepting a first argument of type ‘RPGAdventure.RPGAdventure’ could be found (are you missing a using directive or an assembly reference?) c:\users\kevin\documents\visual studio 2013\projects\rpgadventure\rpgadventure\rpgadventure.designer.cs 282 55 RPGAdventure

    I have followd the entire guide, did i miss something earlier on ?

    p.s i named my game RPGAdventure that’s why it says that.

    1. Hello Kevin,

      This might have happened if you were in the design mode of the screen, and accidentally double-clicked on the screen. That would create this eventhandler in the RPGAdventure.Designer.cs file, and a function in RPGAdventure.cs, which would run when the screen was loaded. If you pasted in code from one of the lessons after that, it would not have the RPGAdventure_Load function, which would give this error about the missing function.

      To fix it, you can edit RPGAdventure.Designer.cs, and delete the line that says “this.Load += new System.EventHandler(this.RPGAdventure_Load);”.

      You can learn more about how eventhandlers work by looking at Lesson 21.3.

      Please tell me if that does not fix the problem, or if you have any other questions.

  5. Hi Scott

    This is an amazing tutorial I have been following along and really enjoying myself. I’m having problem on step 16. The Solution works when I use my code to before this lecture. However when I use your code from

    https://gist.github.com/ScottLilly/208630cfcdded1cbfdc0
    https://gist.github.com/ScottLilly/6670da749c4ad7e7bff7
    https://gist.github.com/ScottLilly/b20787650f2ab2a78362

    For the SuperAdventure.cs I get many errors and I looked at my code and it is very different to yours.

    My code is found here – LINK REMOVED FOR PRIVACY

    I would really appreciate some help please.

    Thank You

      1. Hi Scott

        Thank you kindly it did work. I’m now carrying on with the rest of the tutorial as its great to learn from.

        Once more Thank You

        Alwin

  6. Hi Scott,

    thank you for your wonderful tutorial. I really like this way of learning. I hope to learn a lot more from you. 🙂

    It seems that I didn’t get all the reward things for completing a quest.
    E.g. for the alchemy quest I receive the potion, but neither the experience points nor the gold.
    I can’t trace back and figure out where exactly something is missing.
    My SuperAdventure.cs looks like yours on the “//Give quest rewards” part.
    Also the World.cs and the Quest.cs are the same as yours.
    Maybe I’m looking at the wrong lines…

    1. Hi Anjelica,

      You’re welcome. The first thing to check is the World class, where you create the Quests. Ensure the parameters are correct, when creating the Quest objects. If that looks correct, double-check the Quest class, and make sure the constructor parameters and properties are the correct casing (upper-case first letter for properties, lower-case first letter for parameters). If that does not help you find the problem, can you upload your solution (including all the files in the directories under it) to GitHub or Dropbox, so I can look at it?

      1. Okay, i had the same problem as Alwin, and did the same fix. Visual studio showed no errors, but trying to build the game gave this error
        Error CS0246 The type or namespace name ‘Super_Adventure’ could not be found (are you missing a using directive or an assembly reference?)

        1. This Issue is in Program. cs which had this code using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Threading.Tasks;
          using System.Windows.Forms;

          namespace WindowsFormsApplication2
          {
          static class Program
          {
          ///
          /// The main entry point for the application.
          ///
          [STAThread]
          static void Main()
          {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new Super_Adventure());
          }
          }
          }

          1. You should be able to fix the error if you change line 19 of Program.cs to this:

            Application.Run(new SuperAdventure.SuperAdventure());

            That line tells the program which form to run, when the user starts the program. I’m guessing that you renamed your project, or form, and that name did not get updated. So, the program was trying to start a form that does not exist (Super_Adventure).

            Please tell me if that does not fix the error, or if you have any other questions.

    1. Hi Anjelica,

      It looks like you have some changes from Lesson 19.2 in the source code.

      In SuperAdventure.cs, you have the function UpdatePlayerStats() – which is added in Lesson 19.2. If you are at that lesson, you also need to add a call to UpdatePlayerStats() on line 181 of SuperAdventure.cs (see here: https://gist.github.com/ScottLilly/f6e3153d1bf2b6c1caac). If you are not at that lesson yet, you can still add a call to UpdatePlayerStats() before the call to UpdateInventoryListInUI() (inside the MoveTo function in SuperAdventure.cs). That will fix the problem until you get to lessons 20, when we use databinding to update the values.

      Please tell me if that does not work, or if you have other questions.

  7. Ah yes, I continued the lessons a little bit after my request but stopped then because I didn’t want to mess anything up.
    So the problem was there before.

    But now it all works fine.
    Thank you for your help.

Leave a Reply

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