Video Game Development: Lesson 2

Overview
Before delving into the depths of game development, it is important that we learn a good language to do it in. We will be learning XNA which is built upon C#. So, we will begin with learning the basics of C#. In this lesson we will look at all the basics of the language including variables, input and output, arrays, conditional statements, and loops.

Where to program
Initially we will be using an online IDE(interactive development environment) It is ideone.com. I recommend that you create an account here, so that you can save your code but it is not important for now. When you open this page, go to the bottom left corner where you can select a language and choose C# every time.

What am I looking at?
When you first open this ide you will see this: using System; public class Test { 	public static void Main { 		// your code goes here } } I will explain this all to you in time, but for now just assume that all that is necessary.

Very Basic Syntax
As with most programming languages, (almost) every line must end with a ;

Spaces don't matter i.e. a=b is the same as a = b and a= b and a =           b

Comments which are snippets of text that you can leave in your code that are not evaluated can be written two ways: //Check out this awesome code! or for multi-line comments: /* Check out this awesome code! */ Also, Everything in C# is case-sensitive!

All the code you will be writing for now will be between {   } after public static void Main where the comment says "your code goes here"!

Variables
Variables in C# are essential to know very well. I will start off by showing you a few pretty standard initializations and declarations: int i; int j=1; int J=j; double dou=0.3245; int a=5,b=6; You can see quite a few similarities among all of these. Lets start with what first appears: int/double.

Data Types
A great(or terrible) thing about C# is that it has different types of variables. These can range from integers and real numbers to characters and words. C# has different identifiers for each of the types: For now, these are all we will be looking at.
 * int -> integers in the range –2,147,483,648 to 2,147,483,647
 * float -> real numbers out to seven decimal places
 * double -> real numbers out to 15 decimal places
 * char -> all standard characters in the ASCII text system they are hereif you want to see them.
 * bool -> true or false

An important thing to note is that all these identifiers are case sensitive so Int i; will give you an error!

Naming Variables
The next thing you see in any of these initialization of variables is a name. The names can be one a single letter to a several words as long as they follow these rules: Remember that variable names are case sensitive! As we can see in example 2 and 3, j and J are not the same.
 * Names may only include letters(upper and lower), numbers, and _ (underscore characters)
 * The first character in any variable name must be a letter
 * Variable names may not be the same as words used in the language. These include but are not limited to: int, double, float, for, while, if, else, end, new, switch, return, break, and exit.
 * No two variable may have the same name (kind of, ==_==  I will explain this later.)

Assignments
As we can see in some of the examples, variables can be given values. To do this, we use "=" (called the assignment operator, for those of you who wish to be technical). (BTW, This symbol will cause you more problems than anything else, if you do not know how to use it well...) The "=" works by assigning the value to the right of it to the thing to the left of it, so in this case: int i=0; The "=" is copying the value 0 and giving it to i. The same idea works in examples 2 and 3 where 0 is assigned to j and the value assigned to j is then assigned to J. This in no way changes j, it only copies the value.

Assignments can be done outside of an initialization too: 1. int i; 2. i=2; 3. i=3; 4. n=500; //ERROOOOOORRRRRR In this case we see that values can be given to i at any time, but if you look at line 4, something is wrong. n cannot be given a value because we did not already declare its existence like we did for i. In this case we would get an error at line 4.

So, always remember to declare your variables before using them!

N.B. There is a thing called truncation. So for integers especially, if you give them a value they don't understand expect weird results. I.e. int i=1.657; i would be 1 because it always rounds down.

Constants
Constants are like variables except not... In a way, they are variables that cannot vary. They are defined this way: const double PI=3.14; The cardinal rule of constants is that you cannot change them once they have been initialized. So, you must give them a value at the get-go.

It also important to note that basically everyone names constants in just upper-case letters like I did for PI.

Arithmetic Operators
As I stated in the last lesson, there are four main arithmetic operators native to C#: addition, subtraction, multiplication, and division.

Addition/Subtraction
Addition is done by using "+". An example is: int i=5; int j=-2; i+j; j+i; The result of both of these are 3 as you would expect.

Another way to some types of additions is like this: i+=10; which is the same as: i=i+10; All it is is a shorthand notation programmers made to save time.

Subtraction functions the same way as addition except you just change the "+" to a "-" that is all.

Multiplication/Division
Multiplication is done by using  " * ". It has the same properties as addition so really nothing is new.

For division the same is true.

Parentheses and Order of Operations
Parenthesis can be used the same way that they are in mathematics. One thing to note is that in these cases you may only use ( and ) not  [, ] , { , or }.

Order of operations pretty much works the same way it does in mathematics except there are no native exponents (there is a way to do it but I will explain that later)

Increment and Decrement Operators
There are two other arithmetic operators in C#, ++ and --. The ++ is what gives C++ its name, for those who are curious. These operators work by adding one to the number and subtracting one respectively. They can be put before or after the variable and they have slightly different effects. For us, they aren't too important but feel free to look herefor more information.

Modulo
One essential operator is % which is the modulo operator. This operator gives the remainder of two integers divided. For example, 43%6=1. You will use this operator a lot.

Basic Input and Output
In C# there are a few methods of input and output, but the most widely used are cin and cout.

Input
Here is an example of input: using System; public class Test { 	public static void Main { 		int a;                a= Convert.ToInt32((Console.ReadLine)); } } Try running this and it will ask you to enter something. To do this, just type it and press enter.

As you can see in this example, there is a new type of notation which is Console.Read. There are a lot of things we will need to cover first before I can explain them to you, so for now just know that that is the way to do it. Also, because Read sends back a string, we must change it to whatever our type is so check this site for what to put after convert.

Output
Here is an example of output: using System; public class Test { 	public static void Main { 		int a=5; Console.Write(a+"\n"+ (4+3) +"Hello World!"); } } In this example, I did a bunch of interesting things. First of all, though, let's start with the syntax. I used another notation Console.Write which I will explain in more depth later. On the inside of Write, there are a lot of cool things happening. First thing that you will see is that I outputted a which is a variable. Then I used "+" which in this case acts almost like a concatenator(means to put stuff at the end). You will use it whenever you are outputting more than one thing. Next I outputted \n which is a new-line character which moves the writer down a line. Then I outputed some arithmetic which if you want to do it you must put it in parenthesis. If I had not, then it would have done the 4 and 3 individually. Then I outputted a full string of characters which is denoted by  " "

Please explore these a bunch! There is a lot more that gained by just messing around a bit than me explaining them all to you.

Arrays
Arrays are very much like variables, but just a whole bunch of them.

Initialization
They have this syntax: int[] a= new int[5]; int[] b= {1,2,3,4,5}; The initialization of an array requires a type, name and size. In the case of the first example, I did just that. In the case of the second, I did the same the same thing but just in a different way. I let the compiler determine the size of the array just by putting it in there. The third example is a special case where it will fill every element in the array with the number between the curly-braces.

Again, for the first example the "new" which you see I will explain next lesson. For now, just know that you need it.

An important thing to note is that you can only redefine a whole array by doing this: int[] a= {1,2,3,4,5}; a= {1,2,3,4,5,6,7,8,9,10} //NNNNNNNNOOOOOOOOOONNNNNNNN YOU CANNOT DO THIS a=new int[10];//THIS IS OK One nice thing about arrays in C# is that they can be assigned completely: int[] a= {1,2,3,4,5}; int[] b = a;

Manipulation
The other side to arrays is their manipulation. Luckily arrays have the ability to be changed element by element. Here is an example of this: using System; public class Test { 	public static void Main { 		int[] a=new int[5]; a[0]=1; a[1]=3; a[2]=5; a[3]=7; a[4]=9; Console.Write(a[0]+a[1]+a[2]+a[3]+a[4]); } } As you can see, I am manipulating each individual element of the array. A very important thing to note is that array elements are referenced from 0 to size-1. In this case, a[5] would give you an error because it does not exist. a[4] is the fifth element.

In the case of outputting arrays, you cannot just do Console.Write(a). That will give you some odd results. You can try it, I will be getting to why you get the results that you do in the next lesson.

There are many more elegant ways of doing what I just did and I will be explain them later in the lesson.

Strings and character arrays
There are other types of arrays than those of numbers. There are character arrays too. They work in the same way as numerical arrays. They do give us a new thing though. They are strings. I referenced them earlier. They are defined this way: string s= "Hello World!"; This string can be thought of as this too: char[] s= {'H','e','l','l','o',' ','W','o','r','l','d','!', NULL}; It is an array of characters with a NULL character at the end which is the same thing as a 0. The reason that it is there is so that the compiler knows where it ends. Also, doesn't the first just look more pleasant than the second :)

Conditionals
An essential part of programming is comparing things. Are A and B equal? Is A greater than B? etc. These type of questions are always either true or false.

Comparison Operators
There are five comparison operators: <, >, ==, <=, >= From left to right: Less than, Greater than, Equal to, Less than or Equal To, Greater Than or Equal To. These operators provide with the ability to compare any two numbers. All comparison operators send either true or false.

Here is a good example of this: using System; public class Test { 	public static void Main { 		int a,b; Console.Read(a); Console.Read(b); Console.Write(a==b); } } In this example it asks the user for two numbers and then outputs 1 if they are equal and 0 if not. This is because true becomes 1 when outputted and false becomes 0.

Logical Operators
There are 4 main logical operators: ! , &&, ||, ^ From left to right: NOT, AND, OR, XOR (exclusive or). These work as follows, for a boolean(or comparison), !(NOT) produces the opposite as you might expect. For two booleans, a and b, a && b produces a true only if both are true and a false otherwise. a || b produces a true if either or both of them are true and a false otherwise. a^b produces true if only one is true and the other is false. If they are both true or both false it produces a false. You can see herefor tables of how this works.

If-Else
Now, we are into some fun stuff. If-Else statements are how you utilize everything we have just learned. This is their syntax: if(condition) {  Execute code }    if(condition) {       Execute code }    else if(condition 2) {       Execute code }    else {       Execute code } }

The conditions in these cases are true booleans i.e. comparisons, logicals, non-zero variables. You can have If statements on their own; If and else; if and else if; or if, else if, and else. Any of those work. N.B. You can have as many else if statements as you want but only one else.

One other nice things about these are that if the execution for any these is a single line only, then you don't have to use the curly braces.

Loops
Loops in my opinion are why computers so useful. They are capable of looping through a task as many times as you want them to.

While Loops
While loops are written as follows: while(condition) {   Execute code } They are effectively looping if statements. They continue to execute as long as the condition is true.

For Loops
For loops are a lot more complex than while loops, but are much easier to use in some cases over others. Here is a very common use for For Loops: using System; public class Test { 	public static void Main { 		int[] a= new int[5]; for(int i=0; i<5; i++) {       		      a[i]=i; }   		for(int i=0; i<5; i++) {       		      Console.Write(a[i] + " "); } 	} } In this example, I wrote the values 0 to 4 to the array and then I printed the values in the array.

These two are the most common uses for For Loops that you will have.

As you can see, the general format of For Loops is as follows: for( initial condition; conditional; change) {   Execute code } The three parts of the For Loop must be separated by semicolons. Think of them as three lines of code so you can make those three segments as complex as you want them to be.

Scope and Nested Loops
A very important thing to note, which I will get into in the next section is a topic called scope. In the example I just gave for the For Loop, you can think of the variable i as exclusive to for loop. If I were to try to do this for example I would get an error: using System; public class Test { 	public static void Main { 		int[] a= new int[5]; for(int i=0; i<5; i++) {       		      a[i]=i; }   		for(int i=0; i<5; i++) {       		      Console.Write(a[i] + " "); }   		Console.Write(i); //ERRRROOOOORORRRRR!!!!!!!!!!!!! } } That is because the variable is restricted to the For loop and what is inside of it.

This important property of scope can be thought of as: anything inside a body (within two curly braces) can only be used within that body and the bodies inside of it. I will show you an example of this with nested loops. using System; public class Test { 	public static void Main { 		int[] a={1,3,5,7,9}; int[] b={2,4,6,8,10}; for(int i=0; i<5; i++) {        	        for(int j=4; j>=0; j--) {           		       Console.Write((a[i]+b[j])+ " "); }    		} 	} } This is a pretty simple example of nested loops. For these nested for loops you can see that I had to change the variable of the inner For loop to j because the variable i is still accessible to it. Inside the inner For loop, I can use both the i and the j (and even the array). This just goes to illustrate just how scope works. Here is one last example for scope and loops: using System; public class Test { 	public static void Main { 		int[] a= new int[5]; for(int i=0; i<5; i++) {       		      a[i]=i; }   		for(int i=0; i<5; i++) {       		      Console.Write(a[i] + " "); } 	} } In this example you can see that I have broken one of my cardinal rules from the beginning of this lesson. I have two variables with the same name!?!?!?!?! As I wrote up there, I will explain the "kind of". I will now give you a better definition of variable definition:No variable can be given the same name as another variable accessible in its scope. The second For loop does not know about the first one so you can use the variable name again.

Practice
1. Write a program that takes an amount(in cents or in dollars if you want a bit more of a challenge) and gives you the least number of coins you will need to give someone that amount

2. Find the number of five digit numbers (abcde) such that 0d>e>0, c<10(obviously, it is a digit). An example of this is 12532. Write a program to do this. (Hint: use nested For loops)

3. Write a program to approximate the following: suppose we have an infinitely long full binary tree (which is just a tree that looks likethis )  suppose we have a person that begins at the top of the tree and randomly chooses one direction to walk in(it must be one of the the connected nodes). He does this at every node he arrives at. He only stops if he goes back to his initial position at the top of the tree. Find the probability that he does not come back to the starting position after and infinite amount of time. (Hint: use a Monte Carlo simulation and simulate it for a finite amount of time)(Hint: you don't  know how to make trees yet, so think of trees as levels)

4. Write a program that can take an input and then count the number words in that input. You can make it as complex as you want.

5. Write a function that takes 6 integers and outputs all of the two member combinations of those those numbers