Gigi Labs

Please follow Gigi Labs for the latest articles.
Showing posts with label structs. Show all posts
Showing posts with label structs. Show all posts

Friday, June 21, 2013

C#: Value Types vs Reference Types

Hi all! :)

I'll be writing a few articles about Object Oriented Programming (OOP), but before I do that, there's something I need to explain. In this article, I will be discussing the difference between value types and reference types, as well as the use of the ref keyword.

Let us first create a new console application using SharpDevelop (or Visual Studio, if you prefer). In this application, we declare a struct that represents a monster in a game (if you don't remember structs, look back at "C# Basics: Snake Game in ASCII Art (Part 1)"):

    struct Monster
    {
        public string name;
        public int health;
    };

This struct goes under the namespace, at the same level as class Program. We can now make instances of Monster in the Main() method:

            Monster wolf = new Monster();
            wolf.name = "Rex";
            wolf.health = 100;
           
            Monster steve = new Monster();
            steve.name = "Steve Ballmer";
            steve.health = 10;

Next, we define a couple of methods that work on a monster and modify its attributes:

        public static void RenameMonster(Monster monster, String newName)
        {
            monster.name = newName;
        }
       
        public static void HurtMonster(Monster monster, int damage)
        {
            monster.health -= damage;
        }

In Main(), we can test this:

            Console.WriteLine("Monster's name before: {0}", wolf.name);
            RenameMonster(wolf, "Wolverine");
            Console.WriteLine("Monster's name after: {0}", wolf.name);
           
            Console.WriteLine("Monster's health before: {0}", wolf.health);
            HurtMonster(wolf, 5);
            Console.WriteLine("Monster's health after: {0}", wolf.health);
           
            Console.ReadLine();

The output, however, is not quite what we were expecting:



If we change the Monster from a struct to a class and re-run the program, on the other hand, it works correctly:


So, what exactly is happening here? A struct is an example of a value type. When you pass it as a parameter to a function, a copy of it is actually passed to the function. If you modify it within that function, you are actually modifying the copy. When the function returns, the struct still has its old values.

A class, on the other hand, is a reference type. When you pass an instance of a class (i.e. an object) as a parameter to a function, the object itself is passed. You can make changes to the class's members and they are retained even after the function returns.

Most simple data types (such as integers, floats, etc), as well as structs and enumerations, are value types. Classes and strings are reference types, although a string behaves pretty much like a value type when passed to a function (see an explanation on Stack Overflow, if you're interested).

[Sidenote for purists: in C#, functions are actually called "methods". I consider the term "method" to be more of an OOP thing, and what we're doing here isn't quite OOP.]

It is, however, possible to pass a value type by reference. Let's say you have this function:

        public static void Increment(int x)
        {
            x++;
        }

If we try to call this function on a variable as it is, we're back to square one:


However, we can use the ref keyword to mark parameters that we want to pass by reference:

        public static void Increment(ref int x)
        {
            x++;
        }

...and do the same in the calling code:

            Increment(ref x);

This gives the result we want:


Wonderful. The bottom line is that structs and classes are very similar, but there are a few subtle differences (such as value type vs reference type, stack allocation vs heap allocation, etc) that can affect the way your code works. The differences are particularly clear if you know what pointers are. We will be using classes a lot for Object Oriented Programming (OOP), so it's important to know a little bit about them.

In the next article, we will dive straight into OOP! :)

Thursday, May 16, 2013

C# Threading: Bouncing Ball

Hi all! :)

I hope you've enjoyed the articles so far, and found the little ASCII art games both entertaining and mentally stimulating. Towards the end of yesterday's article, C# Basics: Snake Game in ASCII Art (Part 2), we discussed the problems with the Snake game. One of them was that the snake wouldn't move on its own - you had to press a key in order to make the program do something.

In today's article, we're going to begin learning about threads, and use them to overcome this limitation. This time we're going to draw a ball bouncing all over the console window.

Start a new console application, and add the following struct before the class Program:

    struct Vector
    {
        public int X;
        public int Y;
       
        public Vector(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

You'll notice this is exactly the same as the Location struct in C# Basics: Snake Game in ASCII Art (Part 1). Instead of just using it just as a location, we're also going to use it as a direction. You'll see what I mean in a minute. Add the following for starters:

            Console.OutputEncoding = System.Text.Encoding.GetEncoding(1252);
            Console.Title = "Bouncing Ball";
           
            Vector ballLocation = new Vector(40, 12);
            Vector direction = new Vector(-1, -1);

So ballLocation is the location in the console window where we're going to draw our ball. The direction represents where the ball will go next, relative to ballLocation. In this case, the ball starts at (40, 12) and moves in a northwest direction, so the next position will be (39, 11), and then (38, 10), and so on.

[This paragraph is a bit more advanced... feel free to skip it.] The Vector struct is simply a code representation of a mathematical vector, where a vector such as (3, 1) means "three steps to the right, one step down" (depending on what coordinate system you're using). I'm not going to get into the mathematics, but if you're interested, check out my "A Concise Introduction to Vectors" [PDF].

We're now going to add a loop to show the ball and then move it:

            while (true)
            {
                Console.Clear();
                Console.SetCursorPosition(ballLocation.X, ballLocation.Y);
                Console.Write((char) 4);
               
                ballLocation.X += direction.X;
                ballLocation.Y += direction.Y;
                Thread.Sleep(100);
            }

At the beginning, add the following which is needed by Thread:

using System.Threading;

The code above is an infinite loop; there no condition for which the while loop will end. In this loop, we show an ASCII diamond as our ball, and then simply add the direction to the ballLocation in order to move it. The Thread.Sleep() at the end is simply a delay (in milliseconds) so that you can see the ball move; otherwise it would move quickly. Try changing the value of 100 and use something else (e.g. 1000, which means 1 second) to see what happens.

Press F5 to see the ball move:


You will get an exception once the ball moves off the edge. Add the following to fix this and make the ball change direction when it hits an edge (note || means "OR"):

                if (ballLocation.X == 0 || ballLocation.X == 79)
                    direction.X = -direction.X;
                if (ballLocation.Y == 0 || ballLocation.Y == 24)
                    direction.Y = -direction.Y;

The infinite loop allows the ball to move on its own without user intervention - just as we wanted with Snake. However, there is a problem: we cannot accept any user input like this. In fact, you can only exit by actually closing the window. If you try to add a

Console.ReadKey(true);

at the end of the while loop, we're back to square one: the user must press a key for anything to happen. Clearly, in order to accept input, we need the program to do two things at the same time: let the ball move, and handle user input. Fortunately, such godlike powers are not unique to Chuck Norris and Multiple Man.

A program (or process to be more precise) can do several things at the same time. It can be composed of multiple threads which run at the same time but do different things. This area of programming is called multithreading. Let's see how we can exploit this to allow user input while the ball is moving on its own.

First, move the while loop and the vectors to a new method outside of Main():

        public static void Move()
        {
            Vector ballLocation = new Vector(40, 12);
            Vector direction = new Vector(-1, -1);
           
            while (true)
            {
                Console.Clear();
                Console.SetCursorPosition(ballLocation.X, ballLocation.Y);
                Console.Write((char) 4);
               
                ballLocation.X += direction.X;
                ballLocation.Y += direction.Y;
                Thread.Sleep(100);

                if (ballLocation.X == 0 || ballLocation.X == 79)
                    direction.X = -direction.X;
                if (ballLocation.Y == 0 || ballLocation.Y == 24)
                    direction.Y = -direction.Y;
            }
        }

In what remains of the Main() method, add the following code:

            Thread thread = new Thread(Move);
            thread.IsBackground = true;
            thread.Start();
           
            Console.ReadKey(true);

When you press F5 and run the program, you will now end up with two threads:


The new thread is created in the first line of code above. A thread executes the code in a particular method, so we supply the name of the Move() method (without brackets) as a parameter.

In the second line, we set thread.IsBackground = true. A process (running instance of a program) runs as long as there is a foreground thread (such as the main thread) running. Since our new thread is designated as a background thread, the process will terminate once the main thread has exited.

The rest of the Main() method then starts the secondary thread and waits for a keypress. When the keypress is received, Main() ends, and with it the process. If we didn't set the secondary thread as a background thread, the process would keep on running anyway. Try that out. :)

Fantastic. :) In this article, we learned how to use a simple thread in order to allow a program to do two things at the same time. We used this to allow a game to run, while at the same time waiting for user input.

Stay tuned for more! :)

Wednesday, May 15, 2013

C# Basics: Snake Game in ASCII Art (Part 2)

Hi all! :)

In yesterday's article, C# Basics: Snake Game in ASCII Art (Part 1), we created the first part of our Snake Ranch game (a clone of Snake) and learned to use structs. Today we will learn to use lists in order to allow the snake to grow.

At the beginning of yesterday's article, we mentioned that we needed to store each part of the snake in a list, as follows:


The head of the snake would be at (1,1), for example. The remaining parts trail behind it in sequence. We can store these locations in a list, in the following fashion:


There is a List collection in .NET that allows us to do this kind of thing. As with dictionaries (see "C# Basics: Morse Code Converter Using Dictionaries", we first need to include System.Collections.Generic first:

using System.Collections.Generic;

We can now declare a new List of Location objects, and put the head as the first item:

            List<Location> snake = new List<Location>();
            snake.Add(head);

We now change the code that shows the head (from yesterday's article) to show the entire snake in the list:

                // show snake
               
                foreach (Location location in snake)
                {
                    Console.SetCursorPosition(location.X, location.Y);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write((char) 178);
                    Console.ResetColor();
                }

All we're doing here is going over each element in the list and showing a portion of the snake there. For now we only have the head though.

Before we make the snake grow, we first need to understand what happens when it moves. Consider this again:


Let's say the head of the snake is at (1,1), and it moves to the left. Then the head becomes (0,1). The tail (last part) of the snake goes away, and all the parts between the new head and the old tail remain unchanged. We need to make some changes to our code to handle this properly. First, before the while loop, we declare a new Location variable called next:

            Location next;

This will hold the position of the new head, based on the keypress received. In the example above, the head is currently at (1,1), but if the user presses the left arrow, then we want next to contain (0,1).

At the beginning of the while loop, we add the following:

                next = snake[0];
               
                Console.Clear();

The first line assigns next to the location of the current head, stored in the first element of the snake variable. Lists can be accessed using [] notation just like arrays.

Next, we change the input handling logic to modify next instead of head:

                switch(keyInfo.Key)
                {
                    case ConsoleKey.Escape:
                        return;
                    case ConsoleKey.UpArrow:
                        if (next.Y > 0)
                            next.Y--;
                        break;
                    case ConsoleKey.DownArrow:
                        if (next.Y < 24)
                            next.Y++;
                        break;
                    case ConsoleKey.LeftArrow:
                        if (next.X > 0)
                            next.X--;
                        break;
                    case ConsoleKey.RightArrow:
                        if (next.X < 79)
                            next.X++;
                        break;
                }

After that, we can do the following:

                snake.Insert(0, next);
                snake.RemoveAt(snake.Count - 1);

Here we are doing exactly what I explained earlier: adding a new head at the beginning of the snake, and removing the old tail. If you press F5 now, you should have functionality just like what we had at the end of yesterday's article (because we still have just one part of the snake):


All we have left to do now is to make the snake get longer when he eats a star. At the beginning, add a new variable to store the location of the star:

Location star = new Location(60, 20);

After showing the snake, add the following code to show the star:

                // show star
               
                Console.SetCursorPosition(star.X, star.Y);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write('*');
                Console.ResetColor();

Finally, replace the last two lines in the while loop (Insert() and RemoveAt()) with the following logic:

                snake.Insert(0, next);
                if (next.X == star.X && next.Y == star.Y)
                {
                    Random random = new Random();
                    star.X = random.Next(0, 80);
                    star.Y = random.Next(0, 25);
                }
                else
                    snake.RemoveAt(snake.Count - 1);

This code is based on the code from Chase the Star (see "C#: ASCII Art Game (Part 2)"). If the snake bumps into the star, the star moves away to some other random location. Here we are using structs instead of separate starX and starY variables.

The most important thing to understand here is that if the player bumps into the star, we don't remove the snake's tail, thus allowing it to grow. We can now test it:



Awesome! :) We have just made our own variant of Snake using ASCII art. If you test it thoroughly, you'll notice there are a few problems:

  1. The snake doesn't move on its own as time goes by. You need to press an arrow key for it to move.
  2. The snake can bump into itself or the edges and nothing bad happens.
  3. If the snake moves into the edge, it sort of compresses. When you move away, it regains its former length.
  4. The star can appear over the snake.
  5. No obstacles... boring!

As you can see, it can be quite complicated to make a complete game, as there are many things you need to take care of. Making a fully blown Snake game would take many more articles, so I'll leave it at that. In this article we use generic lists to implement the Snake concept. If you're really adventurous, you might want to try and fixing some of the issues above as an exercise. Don't worry if you don't manage - just thinking about strategies to solve them will teach you how to think like a programmer.

I hope you enjoyed this, and come back for more programming articles! :)

Here is the full code for Snake Ranch:

using System;
using System.Collections.Generic;

namespace CsSnake
{
    struct Location
    {
        public int X;
        public int Y;
       
        public Location(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    };
   
    class Program
    {
        public static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.GetEncoding(1252);
            Console.Title = "Snake Ranch";
           
            Location head = new Location(40, 12);
            List<Location> snake = new List<Location>();
            snake.Add(head);
           
            Location next;

            Location star = new Location(60, 20);
           
            while (true)
            {
                next = snake[0];
               
                Console.Clear();
               
                // show snake
               
                foreach (Location location in snake)
                {
                    Console.SetCursorPosition(location.X, location.Y);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write((char) 178);
                    Console.ResetColor();
                }
               
                // show star
               
                Console.SetCursorPosition(star.X, star.Y);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write('*');
                Console.ResetColor();
               
                // handle input
               
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
               
                switch(keyInfo.Key)
                {
                    case ConsoleKey.Escape:
                        return;
                    case ConsoleKey.UpArrow:
                        if (next.Y > 0)
                            next.Y--;
                        break;
                    case ConsoleKey.DownArrow:
                        if (next.Y < 24)
                            next.Y++;
                        break;
                    case ConsoleKey.LeftArrow:
                        if (next.X > 0)
                            next.X--;
                        break;
                    case ConsoleKey.RightArrow:
                        if (next.X < 79)
                            next.X++;
                        break;
                }
               
                snake.Insert(0, next);
                if (next.X == star.X && next.Y == star.Y)
                {
                    Random random = new Random();
                    star.X = random.Next(0, 80);
                    star.Y = random.Next(0, 25);
                }
                else
                    snake.RemoveAt(snake.Count - 1);
            }
        }
    }
}

C# Basics: Snake Game in ASCII Art (Part 1)

Hi! :)

In recent articles, we created a game called Chase the Star (see "C#: ASCII Art Game (Part 1)" and "C#: ASCII Art Game (Part 2)"), and also learned about what The ASCII Table (C#) has to offer to us.

In today's article we're going to create a little game like the classic Snake. The first Snake game I ever played was probably Nibbles, on an ancient DOS machine. Rumour has it that in the Stone Age, when cavemen used to dance around a bonfire and chant "Ugh!", this machine was used to make a series of electronic beeps in a disco fashion. Each caveman would then walk like an Egyptian.

OK, we're going to start with something quite similar to Chase the Star. The difference is that our snake will get longer when it eats the star. Instead of storing just the location of our player, as with Chase the Star, we are going to need a whole list of locations:


Start a new console application. Since we're going to have a lot of locations, it makes sense to define a structure or struct storing X and Y, rather than keeping separate variables for them. This must be declared at the same level as class Program (ideally just before it):

    struct Location
    {
        int X;
        int Y;
    };

In Main(), we can now store the location of the head of the snake as follows:

            Location head;
            head.X = 40;
            head.Y = 12;

If you try compiling now, you'll get the following error:

'CsSnake.Location.X' is inaccessible due to its protection level (CS0122)

In order to make this work, you need to set the Location's members to public:

    struct Location
    {
        public int X;
        public int Y;
    };

Even better, instead of setting X and Y separately, we can define a constructor:

    struct Location
    {
        public int X;
        public int Y;
      
        public Location(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    };

In Main(), we can now declare head in one line as follows:

Location head = new Location(40, 12);

A constructor, in this case Location(int x, int y), is a method that always has the same name as the struct or class it is in (more about classes another time). It can be used to pass parameters that will be used when the object is created. In many constructors, including this one, those parameters are used to set the member variables in the struct (in this case X and Y).

In this case, we declare a new Location called head and pass 40 and 12 as parameters. Those end up in the constructor, where they are assigned to the X and Y variables within head. The this keyword simply states that we are working with the member variables of head (which is a Location).

We can now add the following at the beginning of Main():

            Console.OutputEncoding = System.Text.Encoding.GetEncoding(1252);
            Console.Title = "Snake Ranch";

...and some logic to show the head of the snake and handle movement:

            while (true)
            {
                // show head
              
                Console.Clear();
                Console.SetCursorPosition(head.X, head.Y);
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write((char) 178);
                Console.ResetColor();
              
                // handle input
              
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
              
                switch(keyInfo.Key)
                {
                    case ConsoleKey.Escape:
                        return;
                    case ConsoleKey.UpArrow:
                        if (head.Y > 0)
                            head.Y--;
                        break;
                    case ConsoleKey.DownArrow:
                        if (head.Y < 24)
                            head.Y++;
                        break;
                    case ConsoleKey.LeftArrow:
                        if (head.X > 0)
                            head.X--;
                        break;
                    case ConsoleKey.RightArrow:
                        if (head.X < 79)
                            head.X++;
                        break;
                }
            }

We now have something similar to Chase the Star, except that we don't yet have the star functionality:


We are using character number 178 from the ASCII Table to represent the head of the snake. When the user presses an arrow key, we modify the X or Y members of head. We can access them as head.X or head.Y.

Wonderful :) In this article we implemented the first part of our Snake game, and learned to use structs. Tomorrow we will learn to use Lists, which we will need to store each part of the snake. This will allow us to complete the game. :)

Check back tomorrow for more! :)