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

in #programming7 years ago (edited)

Hi everyone,

I think the first installment of my C# Tutorials was a success. I just hope that it finds its way in front of the eyes of any Steemians that are interested in learning to Program in C#. It was just a primer, so it was dense with concepts and abstraction, but I believe I kept it light enough that most would be able to follow it and have an appreciation for the difficulty in programming as well as providing them, at the same time, with encouragement to show them that they can do it too.

Tutorial: Basic Concepts and Ideas

So, the next step to this is to just speak lightly about the framework of code. This will be a fairly short post and comes with homework.



Source

The Framework

By the term "Framework", I'm really only speaking of the structure of the code itself. Here you will see an example of a few functions that could be used to create a D&D Character Attribute List. It's always more fun to learn when it's something that is unique and interesting, so this is what I'll be attempting to do.

Things to assume: using a basic form and letting Visual Studio auto-generate some of the behind-the-scenes layout code, I will be using Textboxes and Buttons to allow input and randomize mock Dice Rolls (3D6 rolls for a maximum of 18).


Source

I will call the Textboxes as follows (and each will also have a label):

Strength
Dexterity
Intelligence
Wisdom
Charisma
Constitution

I will call the Buttons as follows:

Exit
Reroll

This is our form:

So with this form, it loads with a default set of Character Attributes with a range of 3-18 (3 x 6-sided dice); and when you click on the Reroll Button, it does another set of dice-rolls. It's a nifty little program if you just wanted a quick way to create character attribute lists for your gaming needs. Behind-the-scenes, of course, this is not actual rolls of dice... instead it is C# code instructions that tell the computer what to do.

For now I will mention in passing that there is also code behind-the-scenes to control the entire layout of the Form itself; however, since I'm using Visual Studio -- the IDE (Integrated Developer Environment) of my choice -- it auto-generates the code that creates the form and the components of the visual application. It also automatically generates some of the header-based information as well, which I am going to remove that which is unnecessary... I don't want to garbage up the post more than it may already be.


The Code Itself

using System;
using System.Windows.Forms;

namespace DnD_Character_Sheet
{
public partial class CharacterSheet : Form
{
public int Str;
public int Dex;
public int Int;
public int Wis;
public int Cha;
public int Con;

public Random random_number_generator;

public CharacterSheet()
{
InitializeComponent();

this.random_number_generator = new Random();
}

private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}

private void Reroll_Click(object sender, EventArgs e)
{
this.Str = DiceRoll();
this.Dex = DiceRoll();
this.Int = DiceRoll();
this.Wis = DiceRoll();
this.Cha = DiceRoll();
this.Con = DiceRoll();

this.Strength.Text = this.Str.ToString();
this.Dexterity.Text = this.Dex.ToString();
this.Intelligence.Text = this.Int.ToString();
this.Wisdom.Text = this.Wis.ToString();
this.Charisma.Text = this.Cha.ToString();
this.Constitution.Text = this.Con.ToString();

this.Refresh();
}

private void Form1_Load(object sender, EventArgs e)
{
this.Str = DiceRoll();
this.Dex = DiceRoll();
this.Int = DiceRoll();
this.Wis = DiceRoll();
this.Cha = DiceRoll();
this.Con = DiceRoll();

this.Strength.Text = this.Str.ToString();
this.Dexterity.Text = this.Dex.ToString();
this.Intelligence.Text = this.Int.ToString();
this.Wisdom.Text = this.Wis.ToString();
this.Charisma.Text = this.Cha.ToString();
this.Constitution.Text = this.Con.ToString();

this.Refresh();
}

public int DiceRoll()
{
int die_roll = 0;

die_roll = random_number_generator.Next(1, 6) +
random_number_generator.Next(1, 6) +
random_number_generator.Next(1, 6);

return die_roll;
}
}
}


The Explanations

Take some long moments to look over the code before you continue onward. See if you can figure out what's going on. I think you will find it oddly simple to follow much of it as I try to use Best Practices to make the code as easily readable as possible. Once you're ready, return and journey onward.

I'm going to break it down by Sections below.

Section 1:

using System;
using System.Windows.Forms;

This just tells the program to use external components in order to perform certain tasks. The System component has many datatype components and logic components and basic system components. The System.Windows.Forms component tells the computer program that it can show Forms and Buttons and other such components. I would say this is about the smallest list of using statements that you're likely to encounter.

Section 2:

namespace DnD_Character_Sheet
{
public partial class CharacterSheet : Form
{
public int Str;
public int Dex;
public int Int;
public int Wis;
public int Cha;
public int Con;

public Random random_number_generator;

public CharacterSheet()
{
InitializeComponent();

this.random_number_generator = new Random();
}

I'm going to gloss over this a bit and will come back to this in a later Post to explain the nuance further. So, essentially, what you see here is the main container for the program, to put it in layman's terms. The namespace term is basically like telling the system "this is our main container to use". The "{" is the opening to the container and there always needs to be a matching number of "}"s to correspond to the opening brace (you always need to close an open brace... goes with parentheses as well).

The public partial class is auto-generated to identify the form-styled container so that the system knows that "this is where all the action is going to take place against the Form (which is called CharacterSheet). It also has an opening brace "{" to set the beginning of this container... there's a matching closing brace "}" later in the code.

The set of instructions that begins with public int Str; and ends with public int Con; are the variables that I will be using. Str, Dex, Int, Wis, Cha, Con are all arbitrary variable names. This harkens back to the first tutorial where it discussed accessibility and datatypes. These are all int (Integer) datatypes to hold the cumulative Dice Roll values for each Character Attribute. At this stage they are undefined so they have no value (not a zero value).

Next you see the public Random random_number_generator; line of code. This one creates a "randomizer" which is usually based in some fashion against the computer's internal clock. A computer cannot create random numbers truthfully, but by using the internal clock in some way to cycle numbers around (I don't get it all myself) it gives a good approximation of random numbers. The Random keyword is actually a datatype in itself... it's an object that corresponds to the functionality to create random numbers in a variety of datatypes.

After the variables have been declared so that they can be used throughout the code (with the public keyword), it's time to declare the actual CharacterSheet Form. This allows the system to "see" the Form properly and instantiate components. This is called an accessor and is something you only really need to know in a cursory fashion to start. I didn't understand them for over a year even while I used it. Within the "container" that is the accessor, you will see a call to the "InitializeComponent()" function that passes in no parameters. This is a basic function of any class and is needed in order to access the layout code. After this, I actually set up the random_number_generator datatype by setting it equal to a new object of datatype Random... using new Random() with the "()" parentheses is like calling to its accessor functionality. This allows it to be used to create those random numbers that we need.

Section 3:

private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}

private void Reroll_Click(object sender, EventArgs e)
{
this.Str = DiceRoll();
this.Dex = DiceRoll();
this.Int = DiceRoll();
this.Wis = DiceRoll();
this.Cha = DiceRoll();
this.Con = DiceRoll();

this.Strength.Text = this.Str.ToString();
this.Dexterity.Text = this.Dex.ToString();
this.Intelligence.Text = this.Int.ToString();
this.Wisdom.Text = this.Wis.ToString();
this.Charisma.Text = this.Cha.ToString();
this.Constitution.Text = this.Con.ToString();

this.Refresh();
}

private void Form1_Load(object sender, EventArgs e)
{
this.Str = DiceRoll();
this.Dex = DiceRoll();
this.Int = DiceRoll();
this.Wis = DiceRoll();
this.Cha = DiceRoll();
this.Con = DiceRoll();

this.Strength.Text = this.Str.ToString();
this.Dexterity.Text = this.Dex.ToString();
this.Intelligence.Text = this.Int.ToString();
this.Wisdom.Text = this.Wis.ToString();
this.Charisma.Text = this.Cha.ToString();
this.Constitution.Text = this.Con.ToString();

this.Refresh();
}

public int DiceRoll()
{
int die_roll = 0;

die_roll = random_number_generator.Next(1, 6) + random_number_generator.Next(1, 6) + random_number_generator.Next(1, 6);

return die_roll;
}
}
}

This section is where all the actual functions happen. The private void Form1_Load(object sender, EventArgs e) segment is the code that is hit when the application is started and the Form itself first loads up. After that, it will not be executed again. Within this container of code, I set each of those variables (eg. Str, Dex, etc.) to a returned value from the DiceRoll() function towards the end of the code. After that, I set the .Text component of each of the Textboxes (eg. Strength, Dexterity, etc.) to the value of the corresponding variable (eg. Strength correlates to Str). As you can see, it starts with the this keyword component, which basically says "use this form" to accomplish your tasks... often this can be left off, but it's not a bad idea to get in the habit of using it.

As each of those Textbox components is text-based (.Text), we cannot set it equal to an int datatype... numbers are not text; however, there is an extension that is .ToString() that is a basic component behind-the-scenes to turn the basic value of an object into a string (Text). Finally, we use the base this.Refresh(); code to "refresh and repaint" the screen... if we didn't do this, there's a chance that the numbers will not change with the click of the Reroll Button.

Speaking of which, the Reroll Button, when clicked, triggers the private void Reroll_Click(object sender, EventArgs e) event. The private keyword says "hands off unless you are part of this form specifically", so it keeps it private to the outside application, if applicable. Within this function, it is just a repetition of the same thing from the initial Load functionality. It just offers a way to "re-roll" the dice and get a new list of attribute values.

So this brings us to the DiceRoll "function/method". Since it is prefaced with public it says "you can use this anywhere in the application code", and since it then has int after it, that says "and we're going to return an integer value". To finish the line, you name the function (DiceRoll) and pass in parameters, as is applicable... since this has an empty set of parentheses "()", it means I'm sending no variables into the function. I start the inner code by setting up an Integer variable (die_roll) with a default value of 0. After that I call the .Next(1,6) function extension through the random_number_generator variable... if you recall, this was the variable that is tied to the Random object to create random numbers. Next is a function that returns an integer, and the 2 parameters within the parentheses are (min, max) that identifies the die-roll range (between 1 and 6, like a 6-sided die). I do this 3 times and add them together and set the die_roll variable equal to that logic. To finish it, I return that die_roll value.

Going backwards a bit to the private void Exit_Click(object sender, EventArgs e) container, or to be more accurate Event is triggered when the Exit Button is "clicked". When it executes, it does just 1 thing: this.Close();. I believe this is self-explanatory, but if not, it means "Ok, now I'm going to close the Form and go back to doing what I was otherwise doing". Since this application is just a single Form, then it closes down the entire thing. On a side note, when I was getting my last job, this is the code I did (just the Exit Button functionality) to show them I could code.

At the very end, you will see the 2 closing braces "}" that match up to the namespace and public partial class containers. That sums it up.


As you should be able to see, it can be confusing on the "micro" level, but at a "macro" level, all that happens is that it loads up, defaults the dice-rolls, allows you to re-roll those dice-rolls, and then close out the appication.

I hope I didn't lose too many of you as I went through this. If I remember, I will take a deeper look at functions, parameters, access levels, return datatypes, and their proper usage in the next Post.

Let me know if this all makes sense.
Thanks.

Sort:  

For some reason it is not letting me re-steem this, so I'm commenting as to find it again later.

It may be due to the fact that this one has already matured out of payment.

Upvoted on behalf of the dropahead Curation Team!

Your post will be Resteemed by @dropahead witness account of the dropahead curation team!

Also please note that by given upvote dropahead Curation Team does not necessarily share opinions expressed in this article, but find author's effort and/or contribution deserves better visibility.

Watch out for the #xx-votesplus tag!

Help us giving you bigger upvotes by

Do the above and we'll have more STEEM POWER to give YOU bigger rewards next time.

Keep up the good work!

Please, also see the recent Change!


News from @dropahead: ¡Castellano!

Interesting. Do you have youtube channel? I'd subscribe if there is any. Do post about channel link under every post so you can get the subscribers. :)

Thanks for taking the time to look! I don’t have a YouTube Channel or any other streaming service yet; however, I am planning on doing one. I can’t say for sure long it will be before I have a YouTube Channel but I can say I’m hoping to have a TwitchTV streaming channel soon.

Go to this link and sign up to watch me when I’m ready and to earn a new pre-launch ICO Token: https://steemit.com/refereum/@dbzfan4awhile/refereum-this-could-be-as-big-as-bitcoin

I’m considering streaming some various content, like gaming and juggling and solving my Rubik’s Cube and cooking sessions and programming tutorials.

Would that be good?

Yes that is a good start. Looking forward to more of your content :)

I am currently working on a java certification. Do you have any tips for landing a solid internship or a job to get my foot in the door?

If you're like me, just kinda blind luck is involved and taking a position that's not actually related to the programming itself. I was hired to a Support Engineer role as I was in CSR for a long time and knew some programming. Just make sure to cover the bases and look into DB access. That's what I would suggest.

Hi @ dbzfan4awhile! I'm a programming student and I really appreciate articles such as this. I hope you can write more about it and I'll be your number 1 fan here :). Thanks so much for sharing!

You're quite welcome!! I plan on doing an entire "course" and would love suggestions on what you want to see. I can make these geared towards certain things for certain.

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by dbzfan4awhile from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews/crimsonclad, and netuoso. The goal is to help Steemit grow by supporting Minnows and creating a social network. Please find us in the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

@eileenbeach has voted on behalf of @minnowpond.
If you would like to recieve upvotes from minnowponds team on all your posts, simply FOLLOW @minnowpond.

            To receive an BiggerUpvote send 0.5 SBD to @minnowpond with your posts url as the memo
            To receive an BiggerUpvote and a reSteem send 1.25SBD to @minnowpond with your posts url as the memo
            To receive an upvote send 0.25 SBD to @minnowpond with your posts url as the memo
            To receive an reSteem send 0.75 SBD to @minnowpond with your posts url as the memo
            To receive an upvote and a reSteem send 1.00SBD to @minnowpond with your posts url as the memo

Programming is the key success but there's a challenge, I tried learning it as I found myself into fashion... Low memory I guess.😆

Coin Marketplace

STEEM 0.19
TRX 0.15
JST 0.029
BTC 63316.74
ETH 2581.53
USDT 1.00
SBD 2.79