Learn C# by Building a Simple RPG – Index

Giant Spider!
Mandatory Giant Spider!

If you want to write a Role Playing Game, but don’t know how to program, or just want to learn how to program in C#, then you’re at right the place.

These lessons will take you from a complete beginner, to being an author of a Role Playing Game, for free.

Now, this isn’t the world’s greatest game. In fact, it’s very short and kind of ugly.

However, as you create it, you’ll learn the most common C# programming practices and techniques. Then, if you want, you can improve the game, adding more features and your own special touch to it.

 

NOTE: One of the awesome students here created a PDF document of the lessons. You can get a copy of it here, or here. You can also download the source code files for the lessons here, or here. Thank you, Mark!

 

SECTIONS

Lesson 00.1 – What is in these lessons?

Lesson 00.2 – General information about programming in C#

Lesson 00.3 – The parts of Visual Studio

Lesson 01.1 – Defining classes and objects for the game

Lesson 02.1 – Installing Visual Studio Express 2013 for Desktop

Lesson 02.2 – Building the solution for the game

Lesson 03.1 – Building the first screen

Lesson 04.1 – Creating the Player class and its properties

Lesson 05.1 – Creating objects from classes

Lesson 06.1 – Creating the remaining classes

Lesson 07.1 – Inheritance and base classes

Lesson 08.1 – Setting properties with a class constructor

Lesson 08.2 – Using class constructors with derived classes

Lesson 09.1 – Using your classes as datatypes

Lesson 10.1 – Creating collections of objects

Lesson 11.1 – Using a static class

Lesson 12.1 – Add the remaining UI controls

Lesson 13.1 – Functions, procedures, and methods

Lesson 13.2 – Creating functions to handle user input

Lesson 14.1 – Variables

Lesson 14.2 – If statements

Lesson 14.3 – Foreach loops

Lesson 15.1 – Getting random numbers for the game

Lesson 16.1 – Writing the function to move the player

Lesson 16.2 – Refactoring the player movement function

Lesson 16.3 – Functions to use weapons and potions

Lesson 17.1 – Running the game on another computer

Lesson 18.1 – Future enhancements for the game

Bonus lessons (enhancements to the game)

Lesson 19.1 – Scroll to the bottom of a rich text box

Lesson 19.2 – Use a calculated value for a property

Lesson 19.3 – Clean up the source code by converting foreach to LINQ

Lesson 19.4 – Saving and loading the player information

Lesson 19.5 – Changing dropdown default values

Lesson 19.6 – Increase maximum hit points when the player gains a level

Improving SuperAdventure’s code quality by refactoring

Lesson 20.1 – Refactoring the SuperAdventure program

Lesson 20.2 – Binding a custom object’s properties to UI controls

Lesson 20.3 – Binding list properties to datagridviews

Lesson 20.4 – Binding child list properties to a combobox

Lesson 20.5 – Moving the game logic functions from the UI project to the Engine project

Adding a vendor to locations (with buying and selling items)

Lesson 21.0 – Plans for adding a vendor to locations

Lesson 21.1 – Adding a price to game items

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

Lesson 21.3 – Add a button and create its eventhandler in code, without the UI design screen

Lesson 21.4 – Completing the trading screen

Use SQL to save and restore player’s game data

Lesson 22.1 – Installing MS SQL Server on your computer

Lesson 22.2 – Creating database tables from classes

Lesson 22.3 – Creating the SQL to save and load the saved game data

Creating a console UI for SuperAdventure

Lesson 23.1 – Creating a console front-end for the game

Final refactoring (cleanup) of the SuperAdventure source code

Lesson 24.1 – Make the SuperAdventure source code easier to understand and modify

 

Share your personal, expanded versions of SuperAdventure here!

187 thoughts on “Learn C# by Building a Simple RPG – Index

  1. I like this tutorial a lot. It’s exactly what I was looking for. I’ve already finished through 13.1. I can’t wait for your future lessons as I’m trying to learn C#, while also building a simple text based game (although it doesn’t feel that simple yet). I think you’re doing a great job and I’ll keep checking back for the rest of your lessons. I bookmarked this website. Cheers.

    1. In case you haven’t seen, there are several new lessons available.

      Lessons 14.1, 14.2, and 14.3 cover variables, “if” statements, and “foreach” loops.
      Lesson 15.1 adds a class to let you create random numbers.
      Lessons 16.1, 16.2, and 16.3 add code to move the player around, let them get quests, fight monsters, and complete quests. These lessons are a bit long, since they cover a lot of code.

      At the end of lesson 16.3, you’ll be able to play the complete game, running it from within Visual Studio. The next lesson will be on how to run the game on other computers, without Visual Studio installed.

  2. I just finished this series, and I have learned so much! This series was amazing, and it was very well done. Thank you so much for making this series! It really gave me a huge boost in the right direction.

    1. Thanks for letting me know it helped you.

      If you want to see how the game would look with some more advanced techniques (such as, LINQ and raising events to communicate from the Engine project to the UI), I’m currently working on it here: https://github.com/ScottLilly/ShinyRockHunter. I don’t have any lessons for LINQ or event-handling (at least, not yet). But I may write some when the app is closer to being completed, if people are interested.

  3. I was looking for a website that teach C# by doing project. Seems like I come to the right place!

    Thanks for all your effort. Bookmarked this website and going to start learning now 🙂

    1. I see you offered to answer questions to another poster, I would love to ask a couple myself, if you are willing to answer them or explain some more about the language and class system.

      1. Certainly. I’m working on a few projects right now. So, if they’re difficult questions, it make take me a few days to write up an answer for them. But feel free to ask.

        1. Thanks Scott. Your WinForm RPG tutorial was great. I have taken your exampled and converted it to a WPF. I am still trying to wrap my head around how to set things up on the back end. I have been playing around with the code and got a very basic attribute system (strength, endurance, et cetera) and a class/role system (knight, wizard, et cetera). But I think I may have not set it up very well, because it is clunky and difficult to use/reference. My question is how can such a system be designed to be versatile enough to allow for the application of bonuses (from for example equipped equipment stacked on top a base build) but simple enough not to require too much coding. Forgive the newbie question, but this is probably just me not being fully versed in how C# class and objects propagate and get passed through loops of code.

          1. There are a few different ways you can implement applying bonuses. My first questions are 1) What things do you want to receive bonuses (attributes like strength and endurance, things like “to hit” percentage, etc.) and 2) What items do you want to affect the attributes (just wearable/usable items, or do you also want to be able to add gems to wearable/usable items – for customized bonuses)?

            Either way, I think the basics would be for you to have a list of the current items the player is using/wearing, within the Player class. You could do this with some class-level variables or properties for the Player class (e.g., CurrentWeapon, CurrentHelmet, CurrentNecklace), or add an “InUse” property to the Item class, and manage setting the player’s currently active items through the Player class, when they want to wear/use a different item. You could also add some new properties to the Item class for ToHitPercentBonus, ProtectionFromMagicBonus, etc. Set those values to zero, except for the properties you want that item to give a bonus for. Then, in your “AttackMonster” method (for example), you would check the player’s inventory for items that have bonuses that affect the battle.

            Let me know if that makes sense. If it isn’t clear, or you think your code still looks clunky, maybe you can put the relevant classes in a GitHub Gist for me to take a look at. Although, I may not be able to check it out until this weekend. I’ve got a lot of work and meetings this week.

  4. I’m new to coding and I really want to create my own RPG game and I think this tutorial will help. Bookmarked on my browser and thanks a lot.

  5. Hey, I was going to put a comment earlier about how none of the code you gave worked. I have a little bit of knowledge in other programming languages such as C++ so i was able to understand the code to a certain extent. I found nothing that was wrong with the programs that I had made but there were still errors in a lot of the coding. I just could not figure it out. Since i am new to C# and visual studio, I am not too familiar with the default settings and some of the other things that go along with these two things. I saw how in one of the early lessons that you said that visual studio would automatically put some code into a new class. When i created a new class, that coding didn’t even show up so i just took the code from the source code you gave and tried it out. it still didn’t work. Well, after doing all of that trying to figure out what was wrong with it I just gave up and went on to try to find a different tutorial for C# thinking that these tutorials might have been out of date or something like that. After a few minutes of searching for something else about programming in visual studio, I found out that visual studio has more than just C#. At first that was all i thought it had but after I figured out that it also had C++ and visual basic, i thought that maybe I was not using the right language when i made a new project. So, I went into the project that i was working on with these tutorials and it turns out that it was the problem. By default, visual studio set the language to visual basic and that was what it was trying to compile in but I was trying to write in C++. So, anyway, just wanted to say that these are great tutorials and i really like them. I just have one question though. Is there a way tp change the language the project is set to after it has been created?

    1. Hi Levi,

      Yes, Visual Studio supports several languages: C#, VB.Net, C++, and F#. I’ve heard there are ways to use it for some other languages, like Ruby and Python – although I’ve never used it for that. So, when you create a project, you need to be sure to select the correct language for the classes you’ll create in the project.

      Unfortuntely, there isn’t really a way to change the language of a project after it’s been created. It’s best to delete the project with the incorrect language and create it again with the correct one.

  6. Hey!

    I wrote an e-mail about 2 hours ago (about 2015.02.02 19:20). Before this tut i could do nothing in windows form, just console. Now i won’t say i’m good at it, but i could add picture for every location, add new location, items, monsters, and stuff. My next goal will be talking with ,,npcs” (meaning more quest and shop). Thanks for everything. 🙂

      1. Hey-hey!

        Did you get my e-mail? I know i’m a bit unpatient, but because last time you didn’t i ask to be sure. 🙂 Used the ,,contact me” down there.

  7. Great tutorial. I am having a few issues in running the program. Hope you can help. I got through all the lessons and ran the program. The program starts successfully. However, when I move around, I noticed that the combo boxes did not appear when there was something to do in a room such as an Item to pick up. It didn’t pick up the sword at the fountain and when I get to the rats, there is nothing to use against them. Any idea where I should look to make the combo boxes visible at the appropriate time? Not sure if you have enough info to answer this question.

    Thanks.

    1. Thanks Tom.

      Did you start the tutorial a while ago? In an older version, I had a sword at the fountain, but don’t have that in the current one. Instead, I have this line in the Player class constructor:

      player.Inventory.Add(new InventoryItem(World.ItemByID(World.ITEM_ID_RUSTY_SWORD), 1));

      That gives the player a starter weapon at the beginning of the game.

      You can double-check the Player and World classes here: SuperAdventure on GitHub. Let me know if that doesn’t help you. I’m going to be offline until next Tuesday, but can help you after then, if there is still a problem.

  8. Hi Scott,

    Thanks a million for the tutorial. I thoroughly enjoyed revising the basics, and watching the final product evolve. It’s always an exciting thing to watch the project compile and pop up on the screen.

    Keep up the great work!

  9. I dont know where to put this but i got an error message that says Error 2 ‘VerySimpleGame.VerySimpleUI.Dispose(bool)’: no suitable method found to override C:\Users\Peter\Documents\DoFE\C#\VerySimpleGame\VerySimpleGame\VerySimpleUI.Designer.cs 14 33 VerySimpleGame

    1. This error usually happens if you rename a form – in this case, changing SuperAdventure.cs to VerySimpleUI.cs. In Visual Studio’s solution explorer, double-click on the “VerySimpleUI.Designer.cs” file and make sure the line near the top says “partial class VerySimpleUI”, and not “partial class SuperAdventure”. Also, make sure the code behind VerySimpleUI.cs has “public partial class VerySimpleUI : Form”, and not the SuperAdventure name.

      The *.Designer.cs file contains some of the methods the *.cs form class uses. That’s why they are both “partial” classes, since they each contain “part” of the logic needed by the whole class. And you need to be sure their class names match.

      Let me know if that isn’t the problem.

  10. thanks for the tutorial! I am new in this and i want to ask how to create a boss monster (i haven’t figure out how create a monster than only appear one time then disappear after you defeat it), raise the life when the player level up and add a item shop.

    1. Hi Rodrigo,

      I’m sorry it’s taken me so long to reply. I didn’t have Internet in my new apartment until last night.

      To have a boss monster that could only be fought once, I would do this:

      1. Add a “BossMonster” property to the Location class (with a datatype of Monster).
      2. Add a “KilledBossMonster” property to the Location class (with a datatype of boolean).
      3. In the SuperAdventure.cs “MoveTo()” function, before the section where you see if there is a monster at the location, add some code to see if there is a boss monster at that location that has not been killed. If so, set the boss monster as the _currentMonster and skip over the section of code that looks for another monster at that location.

      To raise the player’s health when they are a new level, I would create an “AddExperience(int experiencePoints)” function in the Player class. Whenever the player gains experience, use that function, instead of directly adding the experience to the player’s ExperiencePoints property. Then, inside that function, you would add the points to the player’s ExperiencePoints property and increase their MaximumHitPoints if they gained a level.

      For an item shop, I would add an inventory list to the Location class. It would work similar to the Player’s inventory list, but you’d need to add an extra button column to the inventory datagridviews to let the player buy or sell items.

      Let me know if you have any other questions. I should have some time this weekend to go into more details.

      1. Hi again, yeah xD

        if (newLocation.KilledBossMonster == false)
        {
        newLocation.BossMonster = _currentMonster;

        }
        else
        {
        _currentMonster = null;
        }

        been trying to get the boss thingy working, but i just cant make anything work, sigh…. I’ve been also trying to make some monsters only happear if the player has the quest, but it always fails.

        1. I think you probably want something like this:

          if (newLocation.KilledBossMonster == false)
          {
          _currentMonster = newLocation.BossMonster;
          }
          else
          {
          _currentMonster = null;
          }

          This way, if the BossMonster was not killed, you will set the currentMonster to the BossMonster. Otherwise (if the BossMonster was killed), there won’t be a monster to fight (_currentMonster = null).

          You could also write it in the reverse order. Sometimes that makes if/elses a little clearer.

          if(newLocation.KilledBossMonster) // This is the same as “newLocation.KilledBossMonster == true”
          {
          _currentMonster = null;
          }
          else
          {
          _currentMonster = newLocation.BossMonster;
          }

  11. Great tutorial, i have been building up an great idea for an RPG for quiet some time, but was waiting to learn the basics of c# in school. I am really glad i found this, it will give me a huge boost in school, and for the game. But i will probably need to watch more tutorials since the game has some really complicated stuff, cause its gonna be a sort of RPG that i have never seen done before. will take me a long time to make thats for sure. Thanks! will start learning soon probably.

  12. Great tutorial! But.. I can’t get past step 2.. because I don’t have Visual Studio and it doesn’t run on Windows Vista. Any workarounds? I’m using SharpDevelop. Lots of problems trying to follow along, and I can’t get VS without getting a new computer, which isn’t happening for a LONG time.

    1. I couldn’t find a good solution. I’m going to keep looking and see if I can find anything, but it doesn’t look like the odds are very good. If anyone reads this and has an idea, please post a comment.

  13. Hey there Scott,

    i can’t figure out how to properly add the health scaling per level. I tried the “AddExperience(int experiencePoints)” function you mentioned in another comment but I can’t get any further.
    While im adding new Items, Monster, Location and Quests, i really need to be able to raise player health at some point.
    A source code for the health increase per lvl would be awesome if that’s not too much to ask :p

    I really enjoyed your tutorial and it tought me a lot so far.

    Thank you!

  14. Hi Scott,

    i’d like to show all the movement buttons at any given time but grey out those, that can’t be used for the current location. How do I do this? Would be cool if you could help me with some specific source code :p.

     

    Thank you!

    1. woops, never mind, just changed .Visble to .Enabled, didn’t think it would be that easy, sorry :p

      But another thing:

      I’m trying to get the UI resized when the user is changing the window size, can’t get it to work as I want it to D:

      thanks again!

      1. Hi Sarah,

        Good job on finding the property! If you’re going to work a lot with the UI, you should take a look at the other properties and events on the different UI controls. That will make you familiar with what you can do to them.

        To resize items, you’ll want to use the “Anchor” property. That will let you say something like (for example), “no matter how big the form is, I want this button to stay 10 pixels from the right edge and bottom edge”. You may run into a problem if you want controls to stay a certain size from the center of a form. Then you’d need to do something like put a splitter control on the form, and put the other controls (buttons, datagrids, etc.) inside the splitter panels.

        There is also the form’s OnResize event. You can hook an event handler to that event. Then, when the user changes the form’s size, you can have a function that will adjust the controls. However, that can get a little complex – especially if you have a lot of controls on the form.

  15. Have been away from from C# for  several years. I am a retired truck driver. I wrote a small simple wargame about 4 years ago, VS express has changed a lot and my mind is like a sieve. Am going to try to get my feet wet with VS 2015 using your tutorial.

    wish me well, Joe

  16. This is exactly what I needed before I step into unity.  This will give a great foundation I can use in the future.  Thanks

  17. Hi,

    I followed this a little while ago and added simple levelling and then tried using progress bars to represent health and exp (which is pretty bad when moving OS enviroments. it worked fine on vista did what I expected then on windows 7 it didn’t behave the same which is a shame) unfortunately I lost all that code due to a HDD failure and have only now some years later download your source code to start again. So thank you for the work you have done it is definitely the only resource of this type available and if time permits it you should do more!!

    Now, I’ve been toying with the idea of having a map for the locations shown to you. I was thinking of drawing a few small square tiles that just have a solid border but then gaps that show the directions you can move too. Do you reckon this is possible without completely re-doing your location and movement code?

    1. Thanks. I’m currently working on a series of videos for setting up a .Net development environment, with Visual Studio Community 2015 and Windows 10. Once that’s done, I’m going to continue on with a more advanced version of the game that I started on a while back (you can see it here on GitHub).

      To add a simple graphic map to the game, I started playing around with an idea of adding an X and Y coordinate to the Location class. Then, I’d also have property to hold the name of a graphic file to use for the location (forest, house, lake, mountain, etc.). Then, I’d add a control to the UI to hold a 9 x 9 grid of these images (each one probably a 50 pixel square). The player would always be drawn in the center square, and I’d display the graphics for the nearby locations. You can see the idea I had here: http://scottlilly.com/shiny-rock-hunter-c-rpg-26-august-2014-update/. I want to do this app in WPF, so I can get more experience with doing front-end XAML work.

  18. Hello Scott,

    I have no xp in programming of any kind, however, I have decided to make my own rpg. I found your tutorial while searching for a way to do this. What all do I need make the rpg to run C# (per your tutorial) in Windows 7? Just Visual Studio? pardon me for being an absolute beginner

    1. Hello James,

      To follow this tutorial, the only tool you need is Visual Studio Express 2013. If you are using Windows 7, you need to have Service Pack 1 (for Windows 7) installed on your computer. You can get that by running “Windows Updates” from the “Control Panel”, if you haven’t already installed it (or if Windows hasn’t already done an automatic update).

      Please let me know if you have any questions while using the tutorial.

  19. Thanks so much. I was afraid there would be all kinds of things to get. I do have SP1 and forgot to mention, my system is Ultimate Edition. Now, I will acquire VSB13 and give her a test run.

  20. Hey,

    I’m really excited to try this out, but I don’t have Visual Studio Express 2013 and can’t get it as my computer (Win7) will absolutely not install Service Pack 1. It’s been like this for a while and no matter what I’ve tried, it simply won’t install. So my question is, must we use Visual Studio Express 2013 for this or would VS2010 work, too?

    1. I think everything will still work with Visual Studio 2010, as long as you have the .NET Framework 3.5 (or more recent) installed. The lessons cover the basics, which should be the same. If you do have a problem, please leave a comment and I will try to help.

  21. Thank you so much for this, currently on lesson 12. see you in lesson 19 and I hope you will make even more! thank you again ! you are awesome

    1. You’re welcome! I plan to make some more lessons and videos during the Thanksgiving holiday this week. At least one on writing unit tests for your code, and I have some ideas for more refactoring lessons for SuperAdventure (to make the code cleaner, and more like how I would write it in a real project).

  22. Hello Sir, I just finished creating this game but for some reason I cant see my weapon use button and potion use button…. And I cant see any items in my inventory all i can do at the moment is go north west east south… I cant do any quest… Please help me…

    1. Hello. You only see the weapon “use” and potion “use” buttons when you are at a location with a monster, and if you have a weapon or potion in your inventory. Try deleting the PlayerData.xml file. It should be in the SuperAdventure\SuperAdventure\bin\Debug folder (or, \bin\Release folder, if you compile the program in “release” mode). When you delete this file, the game will reset the next time you play it, and should give you a weapon to use.

      Please let me know if that does not work, and we can check other things.

      1. When I go to the location with a quest in it, I cant see a monster living there. Hence, I cant do any quest. I have no clue what the reason is for this……

        1. There aren’t any monsters at the locations with quests. When you get the quest at the alchemist hut, you need to go north to the Alchemist’s Garden location. That location has monsters. If you check the PopulateLocation() function, in the World class, you’ll see the locations with monsters.

  23. Hey again,

    Finished the game ! at least the basic of it, I really want to add more things to it but I have some space issues, is it possible to create another form that will pop up when i click a button. I want to add like inventory button and by clicking on it, it will open an inventory screen where you can equip, drop, sell your items, armor, weapons, etc.

    The problem I can’t get it to work. I don’t know how to show the form, I added a new form to SuperAdventure.

    can you please help me how to show up the form by clicking a button and from there I think I will be fine. thank you so much

  24. I managed to get the second form to show up but there’s an entire new problem.

    _player doesn’t exist in the second form. is there a way to declare it to be available to the entire program?

    1. The _player variable is a class-level variable in the SuperAdventure form, and can only be seen in the SuperAdventure class – unless you pass it to the new form. In the constructor of your new form, you can add a parameter, to pass in the _player object when you create your new form. Then, you can use the player’s inventory, quests, etc. in the new form. So, you probably have code to handle the button press that looks somthing like this:

      MyNewForm myNewForm = new MyNewForm();
      myNewForm.Show();

      When you add a Player parameter to your MyNewForm class, you can pass the _player object by changing your code to this:

      MyNewForm myNewForm = new MyNewForm(_player);
      myNewForm.Show();

      Let me know if there are problems getting that to work.

  25. Thank you! it does work but is there a way to update and change the text labels in the main form via the second form (by clicking on a button for example), it doesn’t let me. apart from that it works very well! I am planning to really expend the game just for practice and fun and eventually release the open source for it here so maybe more people can look at it and maybe learn  something new. but I want to add all sort of new things first!

    1. You’re welcome! I’m finishing a new lesson to show a way to update the labels when the player properties are changed from any place. I should be able to post it tomorrow, after I edit and double-check it.

  26. Sorry I ask to many questions but I am going to ask one last question.

    I’ve been looking for hours for a way to draw simple 2d sprites. I found it’s possible with XNA. Do you recommend using it? I’ve read somewhere that it is dead.

    And when I try to add the XNA libraries to the game, it gives me a warning:

    Warning    2    There was a mismatch between the processor architecture of the project being built “MSIL” and the processor architecture of the reference “Microsoft.Xna.Framework.Graphics, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553, processorArchitecture=x86”, “x86”. This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.    RPGAdventurePlus

    How do you recommend to implement very simple 2d graphics into the game?

     

    1. I’ve also heard that XNA is dead. Unfortunately, I don’t do a lot of work with graphics. I did write a chess-like game that used the built-in System.Drawing library. You could probably use that, and PNG or BMP graphic files, for a simple 2-D game. That’s what I’ll probably do when I re-start working on my more advanced game engine, starting next month.

      Many C# game developers use Unity 3D to handle their graphics. It can make professional-looking games.

    1. I saw some Unity code, and it doesn’t look like it would be easy to get SuperAdventure to work in Unity. Once I have all the logic code out of the UI, I plan to show how to have the Engine project work with Windows Forms, WPF, and ASP.Net front ends (without any changes). I’ll try to get it to work with Unity, but I’m not sure if that will be possible.

  27. Hey Scott, so I finished up your tutorial and now I am working on making the game on my own and adding more features. Couple questions. First is how would I go about adding a hit/miss feature, that has different things affect it (player stats, monster stats, and weapon stats). Also I would like to add a way to use armor. Where if hit, then the armor takes away a fraction of the damage. Like instead of taking 5 damage I might take 2 damage. Thank you for your help!

    1. Hi Matthew,

      The btnUseWeapon_Click function of SuperAdventure.cs is where we do the combat. So, you’d want to change that.

      To add a hit/miss, I’d change the code near this line:
      int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);
      to be surrounded by an “if” statement, to see if the player hits the monster. A simple one could be like this:
      if(RandomNumberGenerator.NumberBetween(1,100) > 50)
      {
      int damageToMonster = RandomNumberGenerator.NumberBetween(currentWeapon.MinimumDamage, currentWeapon.MaximumDamage);
      _currentMonster.CurrentHitPoints -= damageToMonster;
      rtbMessages.Text += "You hit the " + _currentMonster.Name + " for " + damageToMonster.ToString() + " points." + Environment.NewLine;
      }
      else
      {
      rtbMessages.Text += "You attacked the " + _currentMonster.Name + " and missed." + Environment.NewLine;
      }

      That would give the player a 50% chance of hitting the monster. You could make it even more complex by doing something like giving the monsters levels, and changing the 50 (for the “hit” percentage) to be 50 +/- the difference between the monster’s level and the player’s level, or bonuses on weapons/armor/jewelry/etc.

      To change the amount of damage the player takes, because they’re wearing armor, you’ll need to change this line:
      int damageToPlayer = RandomNumberGenerator.NumberBetween(0, _currentMonster.MaximumDamage);

      1. Okay, thank you! Do you think it would be helpful to create a hitmiss function, that calculates whether or not the player hit the monster and then sends that value to the combat function? Or do you think having this as its own class in the engine library, since there will be different properties to be applied? I ask this because I want to have monster level, player level, intelligence level (I am trying to add in stats as well), to all have an influence on whether or not the monster is hit. And then to see if the monster hits the player it will be monster level, player level, and dexterity level.

        Thanks again!

        1. I saw your other comments, and that you got this working. I think this is a good way to handle combat. If you expand the game to include things like magic spells, poisons, etc., you can add new functions to the class to handle those different ways of attacking.

  28. Hi, I first want to thank you for doing this, it has helped me greatly in learning how to code and just the basics of making a game. I am trying to add a button to my form that basically resets your progress in the game, but I cannot figure out how to reset your inventory/level/experience/quest progress etc on the button click. What would I need to do to get them to all reset back to the default on a button click. Thanks!

    1. The easiest way would be for your button’s OnClick function to set the _player variable (in SuperAdventure.cs) to a new Player object. Then, call the functions that display the _player variable’s properties in the UI (since you have a new “player”). If you’ve gotten to the refactoring lessons (20.0 and higher), you’ll need to reset the bindings, since you’re binding the UI to a new object.

      If you try that, and have any problems, please post the code for the OnClick function, and I’ll look at it.

  29. Thanks! Got it working in no time with your help. If anyone else wants to do this or is wondering how here is the source code.

     

    private void btnReset_Click(object sender, EventArgs e)

    {

    _player = Player.CreateDefaultPlayer();

    MoveTo(_player.CurrentLocation);

    UpdatePlayerStats();

    }

     

    1. Thanks for sharing!

      For anyone else doing this, remember to create this function by double-clicking on your “reset” button in the UI/form editor. That will create the empty function in SuperAdventure.cs and also add in a line you need in SuperAdventure.Designer.cs – which connects the button click event to the function.

  30. Hey Scott,

    I’ve run into another problem. So I have a create a player form under the SuperAdventure project where the user can change the ability levels of the player. I want to make it so when they click a create character button then the engine sets the DefaultPlayer ability values to the ones set in the CreatePlayer screen. However when I try to add a reference in player.cs to do this it says it can’t because it would create a circular dependency. Can you give any insight into this?

    Thanks

    1. Are you trying to add a reference to the SuperAdventure project, inside the Engine project? If so, the circular reference is because you would be saying, “SuperAdventure requires the Engine project to be built first, and Engine requires the SuperAdventure project to be built first”. That’s a circular reference, which is not allowed.

      Since your new form is in the SuperAdventure project, you shouldn’t need any new references. What you probably need is a new constructor for the Player class. Currently, there are two constructors in the Player class. So, you can only create a Player object by creating a default player, or passing in the XML from a saved game file. You’ll need a new constructor that accepts values from your new form, and creates a Player object from them. You’ll also probably need a way to pass this new Player object to the SuperAdventure.cs form, so the game uses it, instead of trying to create a default player, or restore one from a saved game (which are currently the only options in the SuperAdventure.cs constructor.

      Exactly how you would pass the new Player object to SueprAdventure depends on how you set up your new form – whether it is the starting form for the program, or whether SuperAdventure is still the starting form, and you have a way to popup the new form.

      If your new form is the starting form, you could create a parameter in SuperAdventure.cs’s constructor, so you can pass in the Player object. Then add some logic in the constructor to use that object, instead of the default player.

      If SuperAdventure is still the starting form, you could add a public Player property to your new form. When you are done generating the player on that page, set the property to the new Player object. Then, in the SuperAdventure.cs method where you create and show this new form, you can look at the new form’s Player property. If it isn’t null, set _player to its value.

      Let me know if that makes sense, or if you try one of those solutions, and are not able to get it working.

  31. Hello Scott,

    I want to add a shopkeeper in the game with a message box. So, how the shopkeeper works is  – the mood of the shopkeeper depends on the time of the day, for instance from 5 in the morning to 12 noon the mood of shopkeeper is happy so, when the player goes to the shopkeeper to by an item he has a conversation in a friendly way (Hey!! long time no c……..), when the time is from 12noon to 10 in the evening, the shopkeeper’s mood is very angry so he replies in a angry way and when the time is from 10 in the evening to 5 in the morning, he is in a scared mood and replies in that way.

    Can you please help me add this character. I would really appreciate it.

    Thank you,

    Som

     

    1. There are many things you need to do, to add this feature. (Add a new vendor class, add a Vendor property to the location class, add the code to buy and sell item, etc.) That’s why I will be doing several lessons for this feature, in January. If you follow those lessons, you will be able to add in a vendor.

  32. Hello 😀

    I expanded the project in my free time, i just want to share, everyone are free to do whatever they want with the code, and thanks again for the tutorials, looking forward to the SQL guide !

    https://github.com/Sh0keR0/RPGAdventurePlus

    Features I’ve added to the game:

    Main menu – you can create or load a game, there’s no limit to the number of saves.

    Options, but it doesn’t really effect the game in anyway right now

    Character creation.

    Races, Armour, spells, stats, combat based on stats, levels and items.

    Enemy can also use magic spells. and there are some more but I don’t remember right now.

    the code may look different because I don’t like to copy paste and I changed some of the code. The code is a bit messy (at least it feels like to me) and the way I coded things may not be the best way  but I am just learning 🙂

     

    1. Very cool! I’m going to check it out this weekend.

      The SQL guide should be up at the end of January. I decided to do the lessons to add a vendor first, and SQL second. Otherwise, I would need to have some extra SQL lessons to include the changes for the vendor.

    2. I like the additions you made – especially the multiple save/load game function and the player creation form (with the picture for human/dwarf/etc.). Thanks for sharing it here!

    3. Hello there,

      Could you help me add a shopkeeper to the game plz….
      This shopkeeper has 3 different moods (happy, angry and sad) which depends on the time of the day. So, from 5 in the morning to 12 noon, the mood of the shopkeeper is happy and it gives out the message like “Hey! Long time no see!”, from 12 noon to 10 in the evening his mood is angry and shouts at you and finally from 10 in the evening to 5 in the morning he is scared and says something scary.

  33. Dont worry about it… I found a solution on how to do it..
    By the way Scott, Thank you for your awesome tutorial 🙂 It was so good and i learned a lot from this tutorial. XD

    1. You’re welcome. For anyone else interested, the 21.X lessons will show how to add a vendor to the game. I’m working on Lesson 21.3 right now, the final piece for adding the vendor.

  34. Hey Scott,

    I have a question about object oriented programing.

    Let’s take the player class for example, we want to change the gold value so we simply code:

    Gold += 10;

    but what is the different between this code to this:

    this.Gold += 10;

    1. Both lines do the exact same action.

      “this.Gold” means, “use the Gold property on this object” – the object where that line of code is located. However, the line that does not include the “this.” still uses the Gold property of the object where that line of code is located. Some people like to use “this.”, because it makes the code a little more specific. But most programmers don’t use it, and many refactoring tools suggest removing the “this.”.

      Some of the automated code that Visual Studio creates includes the “this.”, but it is not needed.

  35. Asking another question, sorry haha!

    I’ve added a new variable to the Player class called Damage Bonus, and I’m sure I’ve copied the code everywhere I needed to, but it’s no longer loading the XML save file, any idea why?

    1. No problem. 🙂

      There are a few things I can think of that might cause a problem. Probably the easiest way to track down the problem is to use the debugger. Here’s a post on How to use the Visual Studio debugger, in case you aren’t familiar with it.

      Set breakpoints in the SuperAdventure constructor, where it tries to find and load the XML file, and other breakpoints in the Player class method that tries to construct a Player object from the XML string (especially in the “catch” section that will run if there is an error parsing the XML).

      If it has an exception when parsing the XML (where I suspect the problem may be), the exception’s Text and StackTrace should give you a little more information about how/where the error is happening.

      Let me know if that doesn’t point you to the problem.

  36. Found the problem, I’d created another variable called Strength which I didn’t add to the XML so it wasn’t loading it back in! Thanks for all your help!

     

    One last question – how do I make a quest give more than one reward item? I added a new line in the World class for a reward item, but it just gives me the last one.

    1. Great!

      To give more than one item, you would change the datatype of the Quest class’ RewardItem property from “Item” to “List” of “Item” (like QuestCompletionItems). In the Quest constructor, set that property to a new “List” of “Item”, similar to how the QuestCompletionItems property is initialized. Then, you would change World.cs, to Add items to the reward items list, when populating the Quest objects. Finally, when the player completes a quest, loop through the list of reward items, to give each item to the player.

  37. I have completed the first ten lessons. This is an absolutely terrific tutorial and I am learning quite a bit from it.

     

     

  38. Thank you, I’m struggling with the loop however! I’ve created the list and changed the World.cs to add items to the list, I just can’t get the loop to give the player the items to work! This is what I have but I know it’s wrong 🙁

     

  39. Typically I figure it out before I saw the reply, I followed the loop created to show the QuestCompletionItems and then did another loop to add all the RewardItems to the inventory!

    I’m currently just playing about, adding extra functionality in and trying to make it my own, thank you so much for this tutorial, it’s helped so much!

    1. Hello Aviv,

      I’ve been working on it, and was going to wait until all of them were finished before posting them. However, I think the first two won’t need any more changes. So, you can start building the database with this lesson: Lesson 22.1 – Installing MS SQL Server on your computer I should finish the rest (saving, and reading the data from the database) this week.

      Are you going to use Microsoft SQL Server, or a different SQL engine? If you use a different one, and have any problems, please tell me. I can change the lesson to to include specific changes for different SQL engines.

  40. thanks for all of the help I needed to learn c# for the game my friends and I are coding for our TSA competition and I learned it all from here thanks very much

  41. Thank you for writing this wonderful tutorial series that builds up into SQL! I learned Basic C# last semester in college and now I am learning “Advanced” where we learn SQL and other miscellaneous things, however, I feel I haven’t quite grasped some of the fundamentals since a lot of what we learned didn’t really apply to real world scenarios or fun adventures like this! I’m going to start this series this weekend and hope to have a better overall understanding when done.

  42. Hello and thank you for these great tutorials, I just wanted to ask a question if that’s OK.

     

    Could I combine this entire game by using Microsoft XNA to create a more, Graphical game using a similar interface? I wanted to make a game where there is maybe just a world map for example but once you get to locations this UI opens maybe with a bit of pictures and looking a bit better. Would I be able to combine this with XNA and maybe provide more control method support etc.

    1. Thank you, Jan.

      If you want to build a graphic front-end for the game, you might want to use Unity (https://unity3d.com/) or MonoGame (http://www.monogame.net/). Microsoft stopped updating XNA about three years ago.

      I think you could also use a WPF/XAML project, if you want to build a 2-D, J-RPG style game. I was thinking of maybe doing that some day. You could use a grid, with each square a specific size (maybe 50 x 50 pixels). In each square, you could place a background image (grass, sidewalk, water, etc.). Then use the Z Index to draw more graphics over that image – for example, a house, castle, trees, etc. Those images could have a transparent background, to let you still see part of the background image. This shows a little bit about how to use the Z index: http://stackoverflow.com/questions/5450985/how-to-make-overlay-control-above-all-other-controls.

      If you got to lesson 23.1, all the game logic will be in the Engine project. That should make it easy to connect a different type of front-end to the game.

  43. Hi, Scott.

    I couldn’t find a direct email so I’m posting this here.

    I guess it won’t hurt to say again what a great tutorial this is. Really appreciate the effort you’ve put into it, as well as answering all the comments.

    I’ve been learning Adobe InDesign for the past few weeks (as if learning C# wasn’t enough), and decided to convert the first 18 lessons of your tutorial into a kind of beginner’s manual that people can quickly search through or print out. Here’s the end result: LearnCSharpRPG.pdf

    I will add the rest of the lessons when time permits.

    I made a few changes to the text here and there, mostly to better fit the format, and some additional text was added for easier navigation through the pages. Nothing too drastic, I think.

    It’s not perfect, there are bound to be errors, typos and the like. If you or anyone finds any egregious mistakes, let me know. Any sort of feedback is welcome.

    Thanks.

    –mr

     

    1. WOW! That is awesome!

      I tried to make a PDF of the lessons, but it turned out ugly, so I deleted it. But yours looks great! I need to hire you when I create my next tutorial.

      Thank you for creating this and sharing it!

  44. Loved the tutorial, right up to the point where I had to start pulling code from GitHub… I peruse tutorials like this to kill downtime at work, and GitHub is blocked on our firewall.

    Plus, I take tutorials to learn how to write code, not download code someone else already wrote…

    Other than that, great showing all around!

  45. I’ve been self-learning C# and doing simple games using MonoGame for almost half a year and it was full of struggles trying to understand C# to create games. Just happened to find your tutorials and it looks promising. Hopefully, i’d be able to improve my C# and game programming after going through all your tutorials. Thank you.

  46. I’ve just completed all the tutorials within the pdf and I have to say that you are absolutely phenomenal in helping those with little understanding of programming really get a grasp at what it is you are talking about and how to use it. Thank you so much, bookmarked and following!

  47. If I may, will you be writing a tutorial about making the game multiplayer? I believe it is beyond the scope of the provided material but it is my ambition to write mine to be multiplayer. I have (currently) a rather limited understanding of coding (enhanced now thanks to your excellent teaching) and I cant think of a better teacher than yourself. I have seen the tutorials for sql database and making player/world objects save but I do not believe the current scope supports unique characters. Any insight you could provide on the subject will have every byte of wisdom consumed!

    Also, making buttons to pull up another window in the UI, after following these tutorials, I have the knowledge base to get this accomplished? Anything in particular I am lacking that would stop me from accomplishing this?

    Thanks again for all the time and effort,

    Michael

    1. When you say “multi-player”, do you mean the ability for more than one person to play the game at the same time – so they could fight enemies together, trade with each other, etc.? Or, do you only want to have the ability to load and save different versions of XML/SQL saved game data?

      The first would be very complex. There is a lot of communication and timing code that would need to be written.

      The second method would be fairly simple to do. In the game’s startup, and closing code, popup a new form to let the user select a file to load or save. You could use the OpenFileDialog class to let them select the saved game file to load from. Then use the SaveFileDialog class to let them save their game data.

      If you want to do this with SQL, there is a little more worked involved. My first thoughts are that you’d want to add a Name and ID property to the Player class. Then, save the Player information to a new Player table. The SavedGame table would need to store the Player.ID, so you know which player the SavedGame row belongs to.

      I’d probably also add the ability for the players to save multiple games. To do this, I would add a new column to SavedGame that would store the saved game datetime. In the Inventory and Quest tables, you would need to add the Player.ID and the unique datetime of the SavedGame, to store the player’s inventory and quests at the time of the save. You would also need to change the DELETEs in the Inventory and Quest update SQL statements to include a WHERE clause, so you only delete the items and quests for the SavedGame they belong to.

      Let me know if you want to try those and if you have any questions.

      I don’t have any immediate plans to make the game multi-player. I might try that with the WPF version of the course I’m creating, as an additional set of intermediate lessons.

  48. Hey, probably a really simple question here, but i’ve finished the tutorials, up until the bonuses and stuff (excluding lessons 19.1 and 19.4-6) but I’ve gone off and added a lot of new areas, loot, monsters, etc. Anyways the issue i’m having is with the inventory grid. there are more items than can fit in the grid (around 20 or so), once i get enough loot for the list to go off the grid, i can’t seem to scroll down to look at what’s off the screen. i looked through to properties of the grid and couldn’t find anything that looked right, but who knows maybe i’m just blind, haha.

    Anyways thank you for the incredible tutorials, I’ve really enjoyed them and have learned quite a bit from them!

    1. You should be able to set the datagrid’s “Scrollbar” property to “ScrollBars.Vertical”. You can do that through the design view of SuperAdventure.cs, by looking for the property in the “Layout” section:

      Or, you should be able to set it in the constructor for SuperAdventure.cs, after you define the columns for the datagrid. Add this line:

      dgvInventory.ScrollBars = ScrollBars.Vertical;

      You may also need to make the Width value for your datagrid columns a little smaller, to ensure there is space for the scrollbar.

      Let me know if that doesn’t work.

  49. I must say: This is a very good tutorial. I loved the creation of a game like this and I’m improving it day for day.

    But I want to ask something: Could you maybe describe, how to add stats like Strengh to improve the game feeling?

    Would be very awesome.

    1. Thank you, Dennis.

      I have different program where the combat is a little more difficult – you can pick a class and have a “to hit” bonus, or an additional damage bonus. I’ll try to show some similar modifications for this game, but I probably won’t be able to work on that for a couple of weeks.

      1. No need to hurry. At the moment I’m working on a spawnrate modification for several monsters in the same location. And creating my own world of course. Would just be nice to know how that system would work in this game (I’m a learning by seeing person).

  50. This is an incredible tutorial.  This gave me the idea to make an rpg for a project for one of my classes. My partner and I used your tutorial to help us with traveling and saving and loading a game.

    We finally got the project to a point where it is playable and presentable. We wanted to thank you for the tutorial and provide a link to our project on Github.

    https://github.com/lpbearden/reswobs_revenge

     

  51. Hey Scott!

    Just wanted to say thanks for all your help and your amazing tutorial. I’ve been working on building this game for about 8 months now. The first 4 months I spent learning the architecture and adding new features and locations. After that I realized the game was a giant mess so I scrapped it and started a rewrite. I’m now 4 months into it and I thought it would be cool to share my progress with you. Currently there is only 3 dungeons out of the planned 8 but there is enough content to keep you busy for an hour or two. Let me know what you think! You’ll probably recognize some of it (like the main town) but I’ve expanded it quite a bit and added alot of neat little features. Let me know what you think! Use the link below to go the a small website I’ve built for releasing it.

    homepages.uc.edu/~ronekm

    Thanks again,

    Kyle

     

     

    1. Awesome! You’ve really added a lot to the game. The graphics give it a great feel.

      I need to create a page with links to all the versions of the program that everyone has created.

  52. Hi. I love your tutorials!
    I have finished all of them, and added a few things like a background picture for all the locations and some onscreen buttons with images of NPC’s and chests to interact with. But after adding the chests I had to add the chests to the locations to check whether I am in the same location as the chest. When I finished adding the chest and wanted to test the game, the game doesn’t seem to set my location. Whenever I check the debugger to see what my currentLocation variable is set to it shows null. I don’t know why my code for locations look exactly like yours except I just added chests to the constructor. Debugger is not much helpful except it only shows me that my currentLocation value is null. I use this to set my location:

    player.CurrentLocation = World.LocationByID(World.LOCATION_ID_VILLAGE_OF_THE_NORTH);

    I am out of ideas on how to fix the problem. Any tips would be appreciated.

      1. I think I sorted the location issue out. But now that I’ve completed that step, when looting the chest I can’t add the item to my inventory because the item = null. I tried putting the Item.Details.ID/Name into a messageBox and it does return an ID and Name value. But the line where it adds the item gives me a null reference exception. Not sure if my syntax to add the item is quite right. I simulate my chests as if they where a monster, so I used the same code from the monster, only the chest is of type Chest and not of type Monster. I also tried adding the actual item directly to my inventory and I also get null reference exception but this time at the property in the InventoryItem class :
        public Item Details { get return _details; } // nullReferenceException

        I uploaded my whole solution. Hope it’s not too messy >.< haha. I basically took your engine and incorporated it into my own RPG. Still working through it converting bit by bit of the engine into my RPG so far I completed the player creation. Working on my first area.

        Thanks in advance.

        LINK REMOVED – FOR PRIVACY

          1. Opps my bad. Didn’t build the engine.

            Here you go:
            LINK REMOVED – FOR PRIVACY

            It starts in MainForm.cs at the bottom there is an event Btn_NPC_Click and the last “if” statement in that event calls the Player.OpenChest() method. If you start a new game and go to Village of the North Tab, at the bottom of map there is a red chest, click on it and open. Then you will get a NullReferenceException error. The error is in the Player.cs class at the AddItemToInventory() method line 263:

            InventoryItem item = Inventory.SingleOrDefault(ii => ii.Details.ID == itemToAdd.ID);

            If I click on view error details I get: {“Object reference not set to an instance of an object.”} But my items are created in the World.cs class. I used the items that you made. Didn’t create my own yet.

            I hope this information will help you to locate my problem. If not, just tell me what details you need and I will see what I can do.

            Sorry about that.
            And thanks again.

          2. I think I found the problem. I’ll give you a clue, so you can get some practice debugging. If you need a little more help, let me know.

            In the “constructor” for the World class, the first line is PopulateChests(). The next line is PopulateItems(). Inside the PopulateChests() function, it tries to add items to the ChestLootTable. What values are in the Items list, at that point in time?

  53. hahaha, something so simple can give you such a headache. XD

    It didn’t even cross my mind. No wonder it didn’t make sense.

    Thank you so much! 🙂

    Now I will pay more attention to the order of how I call my methods. The order plays a big part in your applications.

    If I would to make Spells or skills in my game, I’m thinking of making them similarly to how a weapon is made, instead with different parameters . And then instead of “Use Weapon” I will make 2 buttons, one “Attack” for normal attacks, and then “Use Skill/Spell” with a ComboBox for skill selection. I also want to make weaknesses and resistances like fire, ice and lightning. I will make them a percentage value that will ether decrease or increase the type of incoming damage by a percentage value.

    Shouldn’t be too hard, I must just play around with different formulas. But I will test it out.

    But anyway, thanks again for your advice. I really appreciate it. 😀

      1. Thanks.
        By the way, I seem to have some troubles with the xml save and load. They don’t seem to save any of my player properties even the new properties I added to the save and load method. And also my player stats labels that where databinded to the player properties aren’t doing what the should do. When I create character the labels show all the default stats. But when I change those stats in-game the labels don’t update. However, when I try to print the changed stats (like Gold) in a message Box, it appears the players Gold is being increased. It’s just not showing on labels.(After I load the game the players Gold is back to default value.) Although it does save my players inventory for some reason. I made a button to MoveWest for testing, it didn’t update the label straight away, after I exited and loaded game from save then only the currentLocation label showed my new location.
        It feels like the game has 2 players, and the labels show one player and when I change stats in-game I am changing the other players stats. And the databinders are attached to the first players stat properties. But I can’t find anywhere where it might be that I create a new object of player. Or maybe it’s totally something different.

        Here is updated dropbox if you want to take a look.

        LINK REMOVED – FOR PRIVACY

        Oh, I don’t use the SQL database save because it takes like 15 seconds for game to start and exit. So I am just using xml for now.

        1. I’ll look at the code, but I probably won’t be able to until this weekend. Meanwhile, if you go your code to the lesson that uses NotifyPropertyChanged, make sure you use that for your new properties, to notify the UI there is a new value.

          1. No problem.

            I went through the code again, and I got the labels to update every time I change stats. But the load from xml data is still giving me troubles. I went back to the lesson where you made the xml save. Everything seems the same still. I read some of the comments and one comment was to put a break point in the start of CreatePlayerFromXmlString(), so I did and checked how the game reads in the data.

            Here is the 2 classes:
            LINK REMOVED FOR PRIVACY

            I put the BreakPoint on line 125 and it ran perfectly through up until line 138
            and then the next line says “Player player = new Player();”, from there onwards up until line 173 where it says “return player;” the debugger show player as null. And then the CreatePlayerFromXmlString() method returns a null player witch then saves it into the “_player” object in the MainForm.cs class. And then my game loads up with all the default stats and an empty name. I then tried to messageBox the players name to see if there weren’t perhaps 2 player objects like last time. And the name returned null. So I fixed the first problem I had but now I’m stuck with the game loading up a whole new player.
            I opened the xml document to have a look inside if it maybe didn’t save correctly, but it does indeed save all my player data as it should. So it’s not the save method that’s the problem. I’m guessing somewhere in the CreatePlayerFromXmlString(). Then again it could be my MainForm.cs. I don’t know haha. Not so clued up on xml.

          2. Before the “player” object is created on line 140, the function reads some values from the XML (name, currentHitPoints, etc.). Where are those values assigned to the “player” object’s properties?

            I believe the “player” variable is not null after line 140. If it was null, the program would throw a null exception on the lines where it tries too assign values to the player’s current weapon, inventory, and quests – and never get to line 173.

  54. Ok, I added the player parameters to my parameterless player constructor. And added the rest of the player stats to the CreatePlayerFromXmlString() and ToXmlString(). However, the game still loads up a default character. I placed a breakpoint on line 37 in MainForm.cs to see what the CreatePlayerFromXmlString() loads up. And all the player parameters are default. I’m guessing the game doesn’t save? I do have a FormClosing event and that event is attached to the MainForm when closing. And this is what is inside that event:

    File.WriteAllText(PLAYER_DATA_FILE_NAME, _player.ToXmlString(_player));

    Application.Exit();

    Although I did check the xml data and it did save the player stats. I don’t know what else could be the problem. After I added the rest of the player properties to the CreatPlayerFromXmlString(), I again put a breakpoint at line 117 in Player.cs and watched the debug run, it ran fine up until line 131(MaxHitPoints) and the the debugger skipped the rest of the code and went to the end of the CreatPlayerFromXmlString(). Don’t know why it skipped the rest of the lines…

    Here is updated Player.cs and MainForm.cs and I included a copy of the XmlDocument.

    LINK REMOVED FOR PRIVACY

    Actually now that I think about it, when the debugger skipped the rest of the lines it went to the “catch” part of the “Try-catch” block. and in there is:

    return CreateDefaultPlayer();

    So there must be something wrong with the xml data or something. It found an error and then returns a default player instead. I checked from where the debugger skipped those lines and it appears that I have 2 maxHitpoints entries. I removed the extra one and ran the debugger again and it ran everything nicely. The debugger got to MainForm.cs line 37 and the debugger showed the “_player” created from the CreatePlayerFromXmlString() with all the default stats. So after I fixed the xml error the game still loads up a default character. I’m out of ideas, I will check it again, but in the meantime I posted this comment.

    1. I sent you an e-mail. In case you didn’t get it, I moved my projects to my new computer and I don’t have your previous solution. Can you re-upload it to Dropbox, so I can run the latest version and test that?

      1. Ok, sure.

        LINK REMOVED FOR PRIVACY

        Are you still using this website though?
        The save works on your SuperAdventure game. Well atleast the SuperAdventure game that I have from your tutorials. Unless there’s something missing that will make it work with other projects?

        1. Yes, I’m still using this website. I just built a new computer at home, for all my programming work (my other computer will be for games, music, etc.) When I copied over my projects, yours was in a different set of directories, and I didn’t have it any more.

          For the problem in your game, look at the Player constructor, on line 106. CreatePlayerFromXmlString gets all the values from the XML file, and passes them to the constructor. However, the only properties that are set in the constructor are the Inventory, Quests, ExperiencePoints, and Specialization. The constructor calls SetSpecialization(), which sets more property values (based on the player’s specialization). But the Name, Gold, ExperiencePoints, etc. properties do not get set with the parameter values.

          1. Cool, it’s working now! Thanks.
            I will use this save method for my other project too. I used to use another save method for that game but it was a very simple one. It just serializes a class and then saves all the variables.
            I finished that game and gave it to my friends to test to give me feedback on bugs and glitches and stuff. Most of them came back and said they wanted a feature added where you can capture a planet(it’s a text based space game btw) and then get bonuses off of the planet and be able to upgrade the planets base attribute. So now Im going through all the code doing cleanups and refactoring adding and removing features. But I’m having difficulties with the planet capture. It’s basically going to be like “equipment” and then upgrading that equipment. Want to use equipments for my rpg aswel. I can get the planet in my “inventory” but how to add the planets bonuses to the player I do not know. Do you have any ideas for “equipment” for games?

          2. If you pass the equipment values to the Player constructor (similar to the inventory list), could you go through the items in that list and apply pass it to a new function that works similarly to SetSpecialization (expect, to handle the equipment)?

  55. Hi, I was planning to make a simple mini map for the game using picture boxes that would change colour dependant on where you are on the map, but I can’t seem to figure out a good way to do so. Do you know any possible way to make this?

    1. This is how I would do it:

      1. Create the images for the locations, using whatever graphics program you like.
      2. Embed those image files into the project, this way: https://msdn.microsoft.com/en-us/library/aa984367%28v=vs.71%29.aspx
      3. Add a new string property to the Location class. I’ll use “ImageFileName” for this example. Add this as a parameters to Location’s constructor.
      4. In the World class, when you populate the Locations, pass the value for the ImageFileName parameter.
      5. Create a new “Map” Windows Form, in the SuperAdventure project. This would have five picture box controls: center (for current location) and one for each direction.
      6. Create a new “Show Map” button on the SuperAdventure screen.
      7. Create the function to handle clicking on the “Show Map” button. This will create an instance of the Map form and passes the _player object to that form.
      8. In the Map form, get the ImageFileName for the player’s current location, and the locations in each direction (if they aren’t null).
      9. Populate the picture boxes with the location’s image.

      If you made the SuperAdventure form larger, you could eliminate the new Map form, put the picture boxes directly on the SuperAdventure form, and populate them in the MoveTo function.

      You could build a larger map, that showed more than the neighboring locations. But that is a little more difficult. Onec you get the small map working, you can experiment with making a larger one – if you want.

  56. I would first like to say thank you for the wonderful tutorial.  I am in the process of learning C#, and I’m past all the ‘basic’ stuff and needed something with a little more substance.  This tutorial was what I needed/wanted.

    After going through the tutorial and playing the game a few times I decided to make a quick little mapping system in the MOVETO function that changes the Text on the “Map buttons” to let you know where you head to if you click the button.

    btnNorth.Visible = (newLocation.LocationToNorth != null);
    if (btnNorth.Visible == true)
    btnNorth.Text = newLocation.LocationToNorth.Name;

    btnEast.Visible = (newLocation.LocationToEast != null);
    if (btnEast.Visible == true)
    btnEast.Text = newLocation.LocationToEast.Name;

    btnSouth.Visible = (newLocation.LocationToSouth != null);
    if (btnSouth.Visible == true)
    btnSouth.Text = newLocation.LocationToSouth.Name;

    btnWest.Visible = (newLocation.LocationToWest != null);
    if (btnWest.Visible == true)
    btnWest.Text = newLocation.LocationToWest.Name;

     

    I would like to learn how to do a Map system, sorta like Kuro was trying to do.  However I need to learn a little bit more before I tackle that project.

     

    Good Job on the Tutorial and Thanks for publishing it for us newbies  😉

    1. You’re welcome.

      That’s a great idea – changing the button text to display the location name. Several people have been interested in a map for the game. I might add that in the future, but it will be a while (my “to do” list only gets longer, never shorter 🙁 ).

  57. Hi! So i’m currently taking a c# course in school and we we’re tasked to make a simple game. And I stumbled upon your tutorial and thought I could use this as a backbone for my project. Problem is, we need to implement direct x features to the game. Do you think it will be possible to implement direct x to your project? thank you

    1. If you want to add DirectX graphics to this game, I’d suggest getting all the way to the final lessons (or, at least through all the 20.X lessons), without adding any graphics. Then, when the game is working, add the graphics. Otherwise, as you constantly change the program in the lessons, you would also need to keep changing the graphics. Keeping the game code changes synchronized with the graphics changes might be difficult.

  58. I just started using the tutorial with Visual Studio 2013, and I’ve already hit a snag – on the step where I’m supposed to create a reference to “Engine” in “SuperAdventure,” it tells me “Unable to add a reference to project ‘Engine’.”  Any idea why this might be happening and what to do about it?  Thanks!

    1. Can you take a screenshot of your Solution Explorer (the upper-right section of Visual Studio, with the files in the project), upload it someplace, and send me the link to it?

  59. Good Morning from Germany,

    i receive the error “The type or Namespace Name ‘MessageEventArgs’ could not be found(are you missing a using directive or an assembly reference?)

    The error occurs twice in the Program.cs, twice in the Player.cs, and once in the SuperAdventure.cs.

    Additionally i receive the error “No overload for ‘Player_OnMessage’ matches delegate ‘EventHandler<MessageEventArgs>’

    I hope you can help me with this, im Close to finish this lessons and i already learned soooo much!

    Thanks and best regards,
    Gerrit

  60. Nevermind, im sorry,
    just overread an class and didnt add it at the time.. just found it now..

    Now i got no Errors and im finished, but if i try to debug nothing happens, no window or something else..

    Regards,

    Gerrit

      1. Here it is:

        LINK REMOVED, FOR PRIVACY

        But i got another Problem now.. i can debug it, but it wont work because of some exceptions =/

        1. I noticed a problem in the Program.cs class (in the UI project). It looks like it has some code pasted into it from SuperAdventure.cs. Try replacing all the code in that class with this:

          using System;
          using System.Windows.Forms;

          namespace SuperAdventure
          {
          static class Program
          {
          ///

          /// The main entry point for the application.
          ///

          [STAThread]
          static void Main()
          {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new SuperAdventure());
          }
          }
          }

          Also, because you are using a different type of database, you will need to change the connection string in the PlayerDataMapper class to this:

          private static readonly string _connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\SuperAdventure.mdf;Integrated Security=True;Connect Timeout=30";

          Let me know if that does not fix the program for you.

  61. Hi, I’ve just started using this tutorial, and I have reached the point in Lesson 5 where I must enter

    using Engine;

    Below the rest of the using lines. But it is telling me that the “using directive is unnecessary”.

    And that ‘The type or namespace ‘Engine’ could not be found (are you missing a using directive or an assembly reference?)”

    but I have created an Engine reference in the Super Adventure project and can see it in the references section.

    This is stopping the datatype Player removing the red squiggly line.

    Any help would be greatly appreciated!

    1. Can you check if the Player class has these lines near the top of the class:

      namespace Engine

      and

      public class Player (especially the “public”)

      If it has those lines, did you create the Engine project with a different name, then rename it later? If so, check the solution here: Lesson 02.2B – Fixing the namespace

      If that doesn’t help you solve the error, can you upload your solution (all the files) to Dropbox or GitHub, so I can examine it?

  62. Hi, I’ve been following your tutorial in my free time to refresh my memory of C# before I go back to university and I’d just like to say thank you!

    Ever since I completed the tutorial it’s been so much fun & headache learning to change/add all the new things I’ve been adding to the game. (some days I’d spend hours trying to figure out a problem that I’d end up solving in minutes the next day)  Right now, I’m working on a special attack button for special weapons and then I’d like to have the default selected weapon in the combo box be your most powerful weapon.

    Once again, thanks!

    1. You’re welcome! I’m glad you enjoyed the tutorial.

      It’s amazing how much a night of sleep will help with finding a solution to a programming problem. I hope you have a good year in university.

Leave a Reply

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