Monday 9 July 2012

Programming in C# with XNA – Programming Basics


It’s been far too long since my last post on this set, but hope this will help make up for it. In this post we are going to cover some programming basics as I see them in this context. I am going break the concepts or areas up into three sections, “What is it?” or “What are they?”, “What does it/they look like?”, and “How do I use it/them?”. In the first section I will describe what the concept is, so no code, just a description of it. I will probably use quite visual terms so you can “see” what it is, rather than just giving you just the concept. Next, we will have a look at the concept, a look at the source code, I will then describe it’s components. and finally I will show how the concept is used and describe the kind of areas you would use it.

Compiler Basics


What is a computer program?


Well, simply it is a list of instructions that the computer will obey. I think an important thing to remember is that the computer will carry out these instructions to the letter, it will make no assumptions of what you intend your instructions to do, it will do EXACTLY what you tell it to do.

So we now know that a program is a list of instructions for your computer to carry out, but how do we give the computer these instructions? Well that’s where a programming language comes in like C#. Now, as I am sure you are aware, your computer does not understand English, or what ever your native tongue is, and in fact it doesn’t even understand the programming language. This is what the compiler is for, it takes the instructions you have written in C# and ‘compiles’ it into a language the machine understands directly and is able to act on. This compiled code (in the case of a windows application) is a .exe file. Now the compiler we will be using is Visual Studio and once we have written our instructions we can get it to compile our code and we can then play our game.

Now with this in mind, the project we have just created already has instructions as we can see in the project we have a Program.cs and Game1.cs file, so without even entering a new line of code we can compile and execute this code. At the top of your IDE in the menu you have an option called ‘Build’, move your mouse over it and a number of options will appear.




Click the ‘Build Solution’ option, as you can see you can also just press F6. Now if you are quick you should see the compiler telling you it has started the build process in the bottom left corner.


And once done, it will tell you it has completed. Now there is a much better way of seeing what goes on during the build process,this is important to know as you are going to write some code that just wont build for a number of reasons, most common of which you will make typo’s that will stop the build process. To get more information return to the menu at the top, click ‘View’ and then click ‘Output’, again, there is a short cut, you can open this view by pressing Ctrl+W then O







You should now have the output window open, and you should be able to see messages from the build process which should now look like this




Now that we have compiled our project, lets run it! So, back to the menu, click ‘Debug’ then click ‘Start Debugging’, and again there is a short cut, F5. And HEY PRESTO! We have a game running!! OK, it’s not Gears Of War or Halo 3, but it’s a start… Also, if you look back at the output window you will see a new set of messages :)

You now know how to build and execute the project, so I think it’s more than about time we start learning how to code.

Variables


What are they?


I think the best way to think of these are as box’s that we can put things in, for example, if you have a shoe box, you would use that to put shoes in, in the real world you can put what ever fits into a shoe box, but for the purposes of this tutorial, only what the box was made for can be stored. So, in our game, we will want to store the players score, so we will need to use a variable to do this or the players name, lives, health etc..

What do they look like?


Now in C# we have a lot of variable types, in other words lots of kinds of box’s to put things in. Here are a few of them:

char c;
int i;
byte b;
string s;
object o;
Vector2 v2;
Matrix m;

There are many, many more and you can create your own. The type of variable you choose to use is important, in the list above there is a ‘char’, this is used to store a single character, an ‘int’, this will store an integer (a whole number, a number without a decimal point), a ‘byte’, this will store a number in the range of 0 to 255, a ‘string’, this is used for storing words and sentences; in fact this post it just a load of strings, an ‘object’, now this one is a bit special and can store anything but you should avoid using them :), a ‘Vector2’ this stores coordinates, like on a map, and finally a ‘Matrix’, we probably wont cover these here, but I put them in so you know of them. As you can see the variables here are made up from two parts, the type and the name of the variable. You have probably noticed that some types are in blue and others in, well a lighter blue, that is because the later two are structures, we wont cover this now, just remember they are a type.

How do I use them?


As I have already mentioned we use variables to store information (data), so lets look at the two examples I gave above, the players score and the players name, so I would put the players score in an ‘int’ and his name in a ‘string’. It’s important to choose the right variable types to store the data we want, for example, I could have used the ‘byte’ type to store the plyers score, but our score could then only go up to 255, and I am sure we will want more range than that..

string playerName;
int playerScore;

The naming of our variable names is important too, we should give them sensible and logical names that describe there use, so in the case of our player score and player name I have called them just that, ‘playerName’ and ‘playerScore’, you can also see I have not made the first letter a capital (upper case) this is because I use a variable naming convention called CamelCase, now we wont use this in all naming instances, but for local variables (we will discuss local variables next) we will.

This is called ‘declaring’ variables, and when I declare my variables I like to set their values so I know there content from the start (might be the old C programmer in me) and we do it like this:

string playerName = string.Empty;
int playerScore = 0;

So, in those two lines of code we have created two variables (box’s), logically named them and given them values (put data in the box’s)

Scope


What is it?


Scope is the ‘visibility’ of our variables, what parts of our program can see and use them. The scope of a variable is within the ‘{ }’ braces that is is declared within. We can also add ‘Access Modifiers’ to a variable to extend it’s scope.

What does it look like? & How do I use it?


Here I have put in our two new variables at the top of our Game1 class, I have also created a new variable in the constructor (I’ll get onto constructors later) called ‘enemyName’

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
string playerName = string.Empty;
int playerScore = 0;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
string enemyName = string.Empty;
playerName = "Player 1";
playerScore = 0;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
enemyName = "Bad Dude 1";
base.Initialize();
}

So, our first two variables have a scope that is visible throughout the whole of the class and so can be accessed and used in the constructor for Game1, where we set the players name to be “Player 1” and ensure he has a score of 0. We also created a new variable for the name of our enemy, the scope of this variable is ONLY visible in the constructor and so where I have tried to use it in the Initialize method will cause a compile error (Hit F5 and see)

I will go onto access modifiers when we look at creating our own types later.

Decision Making & Flow Control


What is it?


This concept is where the actual game mechanics reside, it’s how we will know when to increment the score, reduce the players lives or end the game. In C# we have a few devices at our disposal, the ‘if’ statement, ‘switch’ and a variety of mechanisms to loop the flow and with in them methods to control the loops.

What do they look like? & How do I use them?


With the ‘if’ statement we can decide if we want to execute a block of code or not.

if (playerLives == 0)
{
// Code to end the game here ...
}

So, with this ‘if’ statement I am saying, if the variable playerLives is 0 then I want to run the code that will do my end game stuff. Notice I am using ‘==’ to check if the variable is ‘equal to’ 0 (checking the contents of the box) and not setting the variable to the value of 0 (putting 0 in the box).

With the ‘if’ statement also comes the ‘else’, this can be used to execute code should the ‘if’ condition fail.

if (playerHealth <= 0)
playerLives--;
else
{
if (playerHealth != 100)
playerHealth += .5f;
}

Here we have a slightly more complicated ‘if’ statement, if the players health is less than or equal to 0 then the player loses a life, ‘else’ we are the checking if the players health is not (!) equal to 100 then we add .5 to it. We have seen a few conditional statements now what other statements are there? Well here is a list of all the logical operators.

== variable equal to
> variable greater then
>= variable greater than or equal to
< variable less than
<= variable less than or equal to
! variable not
!= variable not equal to

We can also check more than one condition in an if statement by using the ‘&&’ (and) and ‘||’ (or) operators like this

if (playerScore >= 1000 && playerScore <= 1500 && !hadExtraLife)
{
hadExtraLife = true;
playerLives++;
}

What we are doing here is saying if the players score is greater than or equal to 1000 and the players score is less than or equal to 1500 (players score between 1000 and 1500) and we have not already given an extra life, then we set the hadExtraLife variable to true and add one to the players life counter.

The ‘switch’ statement is not so flexible but you can literally use it to switch between conditions

switch (playerScore)
{
case 500:
playerLives++;
break;
case 1000:
playerLives++;
break;
case 1500:
playerLives++;
break;
case 2000:
playerLives++;
break;
}


What this block of code will do is add one to the players lives if there score is equal to 500,1000, 1500 or 2000. You will also see in here a command called ‘break’ this will be covered more in the loops.

So a loop is a way of executing a block of code multiple times, there are again a number of methods at our disposal to do this, the ‘while’, ‘do while’ and ‘for’ loops, so lets have a look at them (there is also a ‘foreach’ but again we will cover that later)

while (playerLives > 0)
{
// Do some stuff over and over..
}
do
{
// Do some stuff over and over..
} while (playerLives > 0);
for (int i = 0; playerLives > 0; i++)
{
// Do some stuff over and over..
}

The ‘while’ loop execute until the condition is no longer met, the players lives are less than or equal to 0, so if the players lives are 0 before we get to star the loop the loop may never execute. The ‘do while’ loop will execute at least once as the condition is not checked until the end of the loop, and again the loop will run until the condition is no longer met. The ‘for’ loop is about the most complex loop we have as we can setup a variable, in this case the ‘int’ i who’s scope will be the ‘for’ loop, a test condition, and then also increment the new variable (and and other for that matter).

So what happens if something happens in the loop that makes me want to either leave it or return to the top again? Well that’s where ‘break’ and ‘continue’ come in. see the loop below

while (playerLives > 0)
{
// Do some stuff over and over..
if (playerScore >= 50)
continue;
if (playerHealth == 1)
break;
}

I guess not the most logical example, but I am using it to show you the mechanism, so in this example, we will continue to execute our loop while the players lives are greater than 0, if the players score is greater or equal to 50 then we will go no further in the loop and return back to the top and start gain, if the players health is equal to 1 then we will exit the loop.

So, we have dipped out toe into programming, if you are following this set of posts, then please make sure you understand the concepts I am trying to explain here before moving onto the nest post. If you have ANY questions on ANYTHING covered here then please don’t hesitate to ask, either comment here on this post, or PM me and I will do my best to help you out. By all means, google and research any of the topics here for more information on them, there are plenty of resources out there.

Previous | Next

No comments:

Post a Comment