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

160 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.

  8. Hey,

    I know it’s been a long time, but I’ve just found this great tutorial. I’ve finished this lesson, so I should have a working game, but actually it stops at the starting screen. All I can see is:

    http://imgur.com/a/5zTlu

    So seems like nothing is initialized, though I just always copied your code. And when I press the “North” button, nothing happens, no errors, plain nothing. :\ What did I miss?
    I use visual studio 2017 and the latest version of C#. Is there any significant difference to the older version that could be the reason of this?

    1. Now movements work, only I can’t use potions, when I click on that, nothing happens.
      Could be the problem that I forgot to click on the buttons while designing the form?

      1. That is probably what happened. If you do the same steps to fix the “Use” weapon and potion buttons, selecting “btnUseWeapon_Click” and “btnUsePotion_Click” for the functions, that should fix them.

    2. When you added the buttons, do you remember if you double-clicked on them? That is one way to connect the buttons to the functions in SuperAdventure.cs – it is how Visual Studio can create “eventhandlers”. You can read more about manually setting up eventhandlers in Lesson 21.3.

      If those eventhandlers are missing, you can add them by:
      1. Edit the SuperAdventure form, in Design Mode.
      2. Click on each button once. Don’t accidentally double-click, because Visual Studio will also try to create the functions in SuperAdventures.cs – and, we already have those functions.
      3. Look at the Properties section of Visual Studio (lower-right corner).
      4. Click on the lightning bolt symbol.
      5. Find the “Click” event. If it is empty, click in the dropdown box next to it and select the correct function for the button
      6. Repeat that for all the buttons, and see if the game works.

      Manually set Click eventhandler

      If that does not work, can you upload your solution (including all the folders and files underneath the main folder) to GitHub or Dropbox? Then I can look at it.

  9. Thank you very much for your quick help! This little reminder was really helpful. Now it works smoothly. I really did forget to activate some of the buttons by double clicking. And I only executed the program when it was supposed to be finished, so I could not figure out where exactly it went wrong… From now on I’ll definitely hit F5 more often. 🙂

    1. You’re welcome. Running the program often, to test your changes, is always a good idea. It is especially good when you use version control, to save the program after each successful change.

  10. hey Scott, I have a error in the program class. in Application.Run(new SuperAdventure());, “SuperAdventure” is causing an error.

    (I’m portuguese, so sorry for any English mistakes)

    1. Hello. Did you name your projects, or form, a different name? If yes, you might be able to fix the problem with the information in lesson 02.2B

      If that does not solve the error, can you please upload your solution (including the folders underneath it, and all the files in those folders) to GitHub or Dropbox, so I can look a it?

    1. Hi Idrees,

      I think that your buttons might not have “eventhandlers” to connect them to the movement functions in SuperAdventure.cs.

      To fix this, open SuperAdventure.cs in Design Mode (the graphic editor). Left-click on the “North” button one time. Look in the lower-right corner of Visual Studio for the “Properties” section (see the image below). Click on the lightning bolt icon, and look for the “Click” event, and look to its right. If it does not have “btnNorth_Click”, click on the empty space. You should see a list of the functions in SuperAdventure.cs. Find “btnNorth_Click”, and select it. If that is missing for the North button, you will probably need to check the other buttons, and connect them to their functions.

      You can read more about eventhandlers in lesson 21.3.

      If that does not fix the problem, please upload your solution (including the folders beneath it, and all the files in those folders) to GitHub or Dropbox, so I can look at it.

      1. Thank you Scott!! Yes the button was not linked. It is now working. Since i am not experienced in programming please bear the stupid questions that i may ask.
        When i want to use a weapon in a location it throws an Null reference exception in the HasRequiredItemToEnterThisLocation function.’Object reference not set to an instance of an object.’
        what did i miss?

        1. It sounds like the eventhandler for the Use Weapon button is connected to a movement function.

          Check the eventhandlers for your buttons (the same way you did for the North button), and ensure they are set up like this:

          Use (weapon): btnUseWeapon_Click
          Use (potion): btnUsePotion_Click
          North: btnNorth_Click
          East: btnEast_Click
          South: btnSouth_Click
          West: btnWest_Click

          Please tell me if that does not fix the problem.

  11. Hi, loving the tutorial it’s helped loads. I’m just wondering about something, with the rtbMessages text, when it loads new text it seems to just stay where it is and not scroll down. Any ideas on a quick fix? Thanks in advance

  12. Hi Scott,

    When you complete the quest and receive some rewards, Gold and Experience are not updated in UI. Probably it would be better to create a separate method for updating the UI since it is required in many places. What do you think?

    Question: How can I achieve that message box shows me the latest message without scrolling it down manually.

    Thanks for such great tutorial!

Leave a Reply

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