C-Sharp Programming Beginner Tutorial: No-Frills Dungeon Crawler (Part 3)

CSharp-ForBeginners_FristImage.JPG

Hey everyone!! This Tutorial will be my last. NOT!!!

This Tutorial is actually the one that will tie together my C# Tutorial and my SQL Tutorials (check out both tags: csharp-forbeginners & sql-forbeginners), so this will be a very important Lesson. I will be focusing with this one on the C# side of things, but how I connect the data to the game.

For this Tutorial Lesson, I am focusing on 2 important tables: the monster_table table and the score_table table. The monster_table table contains monster information while the score_table table contains scoring information for a High Score list.


monster.png

A Monster of a Good Time!

So, this Post has no additions to the actual interface (the game-screen form), so we won't be going into any of that. We do, however, have a very important technique to learn.

In the image Below, you will see the SQL Server Management Studio interface showing the 2 tables on the left-hand side with the individual columns expanded for each. In the top-right panel you will see the 2 queries that are used within the code to pull this data.

SELECT * FROM dungeon_crawler.dbo.monster_table
SELECT * FROM dungeon_crawler.dbo.score_table

These 2 queries use the asterisk (*) as a wildcard to pull in all columns of data from the table; and the lack of a WHERE clause removes the possibility of filters, so both queries will pull back all rows and all columns. You should be able to learn some of this using the sql-forbeginners tag and searching for my Previous Tutorials.



True or False

Scoring With New Logic

So, in order to use the monster table and the score table, we need to add additional logic into the code. We need code that will store the query -- like a question that you ask a database (like a spreadsheet in Excel that holds rows and columns of data) -- to use in pulling data.

Before we do so, though, we need to add some components to the using section of the code. As you might recall, the using section is the section of code that allows the program to "use" different references. What I mean is that by adding certain using statements it adds more functionality to the application/game that we're programming.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;

If you compare the above segment to the same segment in Previous Posts, you should see that I added using System.Data; as well as using System.Data.SQLClient; to the ones that were already there. These new additions will allow the program to connect to Data and read & manipulate Data. Without these statements the code would error out if they were missing.

A Variable P.O.V.


POV

I will not be showing all of the code in an effort to not clutter up the screen overly much. With that in mind, I am now going to jump directly to the section of code where I create the variables. Again, I'm only going to show those that pertain to the new code additions. Look over the code snippet below for a few moments and see if you can figure out what the variables might represent. Hint: think about data.

    public partial class MapForm : Form
    {
        string connection = @"server=**********\SQLEXPRESS;Trusted_Connection=Yes;database=dungeon_crawler;";
        string monster_query = @"SELECT * FROM dungeon_crawler.dbo.monster_table ";
        string score_query = @"SELECT * FROM dungeon_crawler.dbo.score_table ";

        DataTable monster_table = new DataTable();
        DataTable score_table = new DataTable();

Yeah, I know, it's not really that hard to figure out that the connection variable is the connection to the Database while the monster_query and score_query variables represent the actual queries that will be used to pull the data from the database. If you write code as most "Best Practices" suggest, the code that you write should be easily readable by other programmers.

Additionally you will see a pair of DataTable variables. A DataTable is a data type that represents, TA-DA!!! a table. Yes, that simple. It is literally a table. So you can name columns and store data in the tables; and these 2 tables will, surprisingly, hold monster information and score information (as can be inferred from the names of the tables: monster_table & score_table).

So there you have it, those are the new variables that will tie together the game and the data (or at least those 2 elements of the data... we may add more later on). Should we take a quick break to look at some cats "hanging in there"? Okay, here you go!



Hang in there Kitty!


-And Now, Introducing Your Storyline!_

So, getting back to the Lesson, I did add on 2 components (the form in the above image, which is a Splash Screen; and the Character Sheet Class that I generated early on in these Tutorial Lessons). Thus, below you will see that code which only goes to load the form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SimpleDungeonCrawlerGame
{
    public partial class Intro : Form
    {
        public Intro()
        {
            InitializeComponent();

            this.DialogResult = DialogResult.Abort;
        }

        private void Intro_Load(object sender, EventArgs e)
        {
        }

        private void Done_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}

So there you have it, the entire class is very small indeed. The only functionality that you will actually see in the code is the Done_Click Function that closes the Splash Screen. As you can see, this is the Intro class and has been added outside of the main game code, which is a very common way to separate items that are only loosely-related.


-Show Up and Accept Your Fate!-

As could be seen above, the new Intro class provides a way to show the Splash Screen to tell the backstory of the game. Below shows some of the code that shows the Intro form and then waits until the Accept Your Knightly Duty! button has been clicked. In the below code, this is shown by instantiating an Intro form with the "Intro into = new Intro();" and then showing the form with the "...intro.ShowDialog()..." code segment.

        public MapForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Intro intro = new Intro();
            if (intro.ShowDialog() == DialogResult.OK)
            {
                NameForm name_form = new NameForm();
                if (name_form.ShowDialog() == DialogResult.OK)
                {
                    this.character_name = name_form.name;
                }
            }
            else
            {
                this.Close();
            }

            MessageBox.Show(string.Format(@"Welcome to the Dungeon, {0}!", character_name));

            if (character.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show(string.Format(@"Now you are all set! Go forth, {0} and save the Princess!", character_name));
            }

`Intro intro = new Intro();` tells us to create an object of type _Intro_ and name it "intro". It's common to use Uppercase for the name of the _class_ and Lowercase for the name of the object derived from that _class_. We could, in theory, make as many of these forms as we wanted and then show them by just using the ".ShowDialog()" function for each one; however, I only want to show a single Splash Screen.
if (intro.ShowDialog() == DialogResult.OK) is a bit confusing to many people because it doesn't seem to tell the story of what it wants to do. What it actually says is this:

  1. Pop up the Splash Screen using the intro.ShowDialog() portion of the code.
  2. Wait until the application returns a value of DialogResult.OK before doing anything. The DialogResult value of a form is basically a way to identify if the form is in an Abort, Cancel, OK, etc. state. As an example, OK buttons are usually coded to change the form's DialogResult value to OK.
  3. IF the form's value is the same as DialogResult.OK (in this case hitting the huge button), perform the tasks within the curly braces.
  4. If not, close the application.

Who Are You, Knight?

            if (intro.ShowDialog() == DialogResult.OK)
            {
                NameForm name_form = new NameForm();
                if (name_form.ShowDialog() == DialogResult.OK)
                {
                    this.character_name = name_form.name;
                }

Within those curly braces you will see the calling of the NameForm form and calling it name_form in the same way as the Intro was done. The NameForm can be seen in the image below and allows for you to set up your character name. I made it default to "Sir John E. Smythe" for the name.


And Finally We Haz Data!

Yowzer, that was far more information than I had intended. I apologize, but we're now at the most important part of our journey. We have finally reached the logic that will create the actual DataTables and connections and commands and populate them with Database information.

            using (SqlConnection monster_connection = new SqlConnection(connection))
            {
                monster_table.Columns.Add("id");
                monster_table.Columns.Add("monster_name");
                monster_table.Columns.Add("monster_image_filename");
                monster_table.Columns.Add("min_health");
                monster_table.Columns.Add("max_health");
                monster_table.Columns.Add("min_attack");
                monster_table.Columns.Add("max_attack");
                monster_table.Columns.Add("min_defense");
                monster_table.Columns.Add("max_defense");
                monster_table.Columns.Add("min_score_reward");
                monster_table.Columns.Add("max_score_reward");
                monster_table.Columns.Add("min_treasure_reward");
                monster_table.Columns.Add("max_treasure_reward");

                SqlCommand monster_command = new SqlCommand(monster_query, monster_connection);
                monster_connection.Open();

                SqlDataReader monster_reader = monster_command.ExecuteReader();
                monster_table.Load(monster_reader);
            }

            using (SqlConnection score_connection = new SqlConnection(connection))
            {
                score_table.Columns.Add("score");
                score_table.Columns.Add("name");
                score_table.Columns.Add("date");

                SqlCommand score_command = new SqlCommand(score_query, score_connection);
                score_connection.Open();

                SqlDataReader score_reader = score_command.ExecuteReader();
                score_table.Load(score_reader);
            }
        }

There are 2 segments that start with the using statement and go from left curly brace all the way to the right curly brace. The logic itself is the same between both, but the score_table variable has far fewer columns, so I'll describe the logic through the second segment of code.

            using (SqlConnection score_connection = new SqlConnection(connection))
            {
                score_table.Columns.Add("score");
                score_table.Columns.Add("name");
                score_table.Columns.Add("date");

                SqlCommand score_command = new SqlCommand(score_query, score_connection);
                score_connection.Open();

                SqlDataReader score_reader = score_command.ExecuteReader();
                score_table.Load(score_reader);
            }
        }

So here you have just the lower segment. What this does is:

  1. Create a SQLConnection object named score_connection and instantiate it as a new object utilizing the connection variable. The connection variable, remember, stores the connection string to my Database.
  2. It then adds new columns to the DataTable object ("score", "name", & "date"). These will be the individual fields of the table.
  3. Create a SQLCommand object named "score_command" as a new instance. The function to set it up uses the score_query string of text as well as the score_connection object. Basically, it says that the program is loading up the query and linking to the database connection.
  4. We then Open() the connection.
  5. We create SQLDataReader object named "score_reader" and set it up to be populated by running the ExecuteReader() function against the score_command object. This will literally query the database and bring back all of the data.
  6. We then Load all of that data from the score_reader object into the score_table object. This will hold all of the Score Information that we'll use later on to show High Scores.

A Last Word


Last Word

I'd like to apologize for the extensive wordiness, but there's really a lot to be said and to learn. Don't worry if much of it goes over your head... this is where the Stack Overflow web site and Google will be quite helpful in coding things in place.

Thanks!


Lessons Learned

Here are the links to your lessons learned (or not learned, if you need to go back and learn them):

C# Programming Beginner Tutorial: Basic Concepts and Ideas

C# Programming Beginner Tutorial: A First look at actual code using D&D as the Project

C# Programming Beginner Tutorial: Variables & Data Types to Fuel the Gaming Engine!

C# Programming Beginner Tutorial: Designing the Game with Programming Logic in Mind (Part 1)

C# Programming Beginner Tutorial: Designing the Game with Programming Logic in Mind (Part 2)

C# Programming Beginner Tutorial: Designing the Game with Programming Logic in Mind (Part 3)

C-Sharp Programming Beginner Tutorial: Designing the Game with Programming Logic in Mind (Part 4)

C-Sharp Programming Beginner Tutorial: Rock! Paper! Scissors!

C-Sharp Programming Beginner Tutorial: No-Frills Dungeon Crawler (Part 1)

C-Sharp Programming Beginner Tutorial: No-Frills Dungeon Crawler (Part 2)


Sort:  

I am learning Php and JS right now. I will learn C# very soon.
Thanks for sharing programming tutorial for C#.

You can probably already see some commonalities even between the script-based languages and C#. Once you learn one, I believe it really helps in learning the next one.

wow thank you :) I'm quite busy in my studies developing a remote desktop application and I want to finish it right away to try this and make my own game using C#

You are creating an application to tunnel between computer systems? Class assignment or proprietary Software Tool?

Just Class Assignment to monitor student activities

Oh that sounds interesting.

yes it is fun, especially we are three persons developing it

Hoo~ly! tnx dude! I'm bookmarking this fdor the near future as I'm finishing a C# tutorial but i just can't ever be happy by learning from one side :)

I'm glad you enjoy the Lesson and I hope it gives you a more reader-friendly Tutorial. Thanks so much!

I never knew both c and sql can be combined together really it's just because of you @dbzfan4awhile I learned that the thing which my clg sir and teacher should teach is taught by my virtual sir ie you sir...... Thanks for sharing this article keep steeming!!

Definitely. Using C-Sharp as the interface, it actually weaves together very well to join data to logic. The nice thing with C-Sharp is that, being based on the dotNet platform gives newer programmers an easy way to find specific functions. Hitting dot after an object and using IntelliSense offers great ease-of-use.

It definitely sounds as if these Tutorials might be helping you in your coursework, so that makes me feel very good.

Thanks!

good tutorial friend, you helped me a lot and well explained! @dbzfan4awhile

I'm happy to hear that this helped you out. Thanks for being such a devoted reader!

Useful information for programmer just like me. Thanks for Sharing :)

Thank you for finding the information useful! What kind of programming work do you normally do? I normally work in the Shipping/Logistics field... everything that I display in these Tutorials comes from my own personal experiences.

Remember, there's no reason not to lean on external resources if you need a quick refresher or some extra information/techniques... I still search for information routinely.

wow, that's great. I normally work in WP theme development. But I am also learning C sharp, I really enjoyed your tutorials. :) thanks again.

You're quite welcome and I hope they help you out. The nice thing is that once you know some of these techniques it will make learning other things far easier.

Thanks for the tutoring. Nice one keep it up

I hope it helps you create better programs! Thanks for reading!

Upvoted on behalf of the dropahead Curation Team!

Thanks for following the rules.

DISCLAIMER: dropahead Curation Team does not necessarily share opinions expressed in this article, but find author's effort and/or contribution deserves better reward and visibility.

Help us giving you bigger upvotes by:

Upvote this comment!
Upvote & Resteem the latest dropahead Curation Reports!
Join the dropahead Curation Trail
to maximize your curation rewards!
Vote dropahead Witness with SteemConnect
Proxy vote dropahead Witness
with SteemConnect
Donate STEEM POWER to @dropahead
12.5SP, 25SP, 50SP, 100SP, 250SP, 500SP, 1000SP
Do the above and we'll have more STEEM POWER to give YOU bigger rewards next time!

News from dropahead: How to give back to the dropahead Project in 15 seconds or less

Quality review by the dropahead Curation Team

According to our quality standards(1), your publication has reached an score of 90%.

Well said Gabriel García Marquez: "You learn to write by writing" Keep trying, you will soon achieve excellence!


(1) dropahead Witness' quality standards:

- Graphic relation to the text (Choice of images according to the text)
- Order and coherence
- Style and uniqueness (Personal touch, logic, complexity, what makes it interesting and easy to understand for the reader)
- Images source and their usage license

Thanks for sharing information Keep it up
I follow you And wish you good luck

I appreciate that! Thanks so much!

well thanks for sharing it with us

You're quite welcome. What would you say is the most important thing that you've learned from these Lessons?

Coin Marketplace

STEEM 0.18
TRX 0.14
JST 0.029
BTC 58132.39
ETH 3138.08
USDT 1.00
SBD 2.44