Gigi Labs

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

Wednesday, May 8, 2013

C#: ASCII Art Game (Part 1)

Hello peoples! :)

In this article and the next, we're going to do something fun - a game. :D

However, I want to set expectations here. It's NOT going to look anything like this:


At best, it might look something like... uhhh.... this:


Wow, that screenshot is almost 10 years old... one of my very first projects, in C++. Games are a great way of learning just about anything programming-related.

Since the first article here, we've been writing Windows console applications. Today we're going to learn to mess around with the console to change things as we like. Let's start by creating a new console application in SharpDevelop or Visual Studio. Just before the first line of code in Main(), add the following:

            Console.Title = "Chase the Star";

This sets the title of the console window:


In case you're wondering, the title is inspired by two great songs, Chase The Sun (Planet Funk) and Into the Sun (Weekend Players). This game is going to be about chasing stars. Isn't that what everybody should do in life? =)

We can clear any text in the console window like this:

             Console.Clear();

...and we can set the cursor position like this (the numbers are x and y position):

             Console.SetCursorPosition(4010);

...so when we write something:

             Console.WriteLine("Hello world!");

...it appears at that specific position:


With this knowledge, we can start working on our game! Start a new console application, or clear the code you currently have in the Main() method. This is the code we're going to start off with:

            bool quit = false;
            Console.Title = "Chase the Star";
         
            while (quit == false)
            {
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.Escape)
                {
                    quit = true;
                }
            }

Quite a few new things here. First of all, we have a variable called quit, which is of type bool. A bool variable can be set to either true or false - it's actually called a boolean. We also have a new kind of loop (we briefly touched upon loops in yesterday's article, C#: Creating a grep-like tool using Files, Strings and Loops). The code within the body of this while loop runs for as long as the condition, in this case quit == false, is true. An important thing to note here is the difference between = and ==. = assigns a value to a variable. == checks whether two expressions are equal.

The next thing we're doing is finding out which key is being pressed, using Console.ReadKey(). We've used this method before, to wait for a keypress before terminating the program, but this time we're passing true instead of false as a parameter. Setting it to true means the value of the key gets intercepted and doesn't get written to the console.

Finally, we check what key was pressed. If it was the ESC key, then we set the quit variable to true, allowing the while loop to end. Without that, the loop would run forever (or at least until you kill the program).

So now, all we need is a couple of variables to keep track of the player's position in the console window. Put these at the beginning, before the declaration of quit:

            int x = 40;
            int y = 12;

The console is usually 80 characters wide and 25 characters high, so that puts you roughly at the centre. At the beginning of the while loop, we add some code to show your current position in the console window:

                Console.Clear();
                Console.SetCursorPosition(x, y);
                Console.Write("X");

Now, all we need to do is handle the arrow keys. This code goes after the if statement, after the curly brackets:

                else if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    y--;
                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    y++;
                }
                else if (keyInfo.Key == ConsoleKey.LeftArrow)
                {
                    x--;
                }
                else if (keyInfo.Key == ConsoleKey.RightArrow)
                {
                    x++;
                }

x++ is actually shorthand for x = x + 1, or x += 1. Same for y--: it means y = y - 1.

That's all! Press F5 and have fun running around the console window... until you move out of the window:


BOOM! We'll handle that and other things in tomorrow's article. For now, the full code is:

            int x = 40;
            int y = 12;
            bool quit = false;
            Console.Title = "Chase the Star";
         
            while (quit == false)
            {
                Console.Clear();
                Console.SetCursorPosition(x, y);
                Console.Write("X");
             
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.Escape)
                {
                    quit = true;
                }
                else if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    y--;
                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    y++;
                }
                else if (keyInfo.Key == ConsoleKey.LeftArrow)
                {
                    x--;
                }
                else if (keyInfo.Key == ConsoleKey.RightArrow)
                {
                    x++;
                }
            }

In Part 2 (tomorrow's article), we're going to continue working on this game. We'll learn about switch statements and random numbers among other things. Stay tuned! :)

Friday, May 3, 2013

C# Basics: Fun with Integers

Hi people! :)

Today we're going to learn how to make our program accept numbers as input. In doing so, we'll learn a little about variables, data types, data type conversions, and arithmetic operations (plus, minus, etc).

Start off by creating a new SharpDevelop project as in yesterday's article, C# Basics: Input and Output. Instead of asking a user for his name, let's write a small program that asks for his age. Use this code:

            Console.WriteLine("Enter your age:");
            String age = Console.ReadLine();
            Console.WriteLine("Only {0}?", age);
        
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);

Nothing new there. This time we are obtaining the user's age and storing it in the age variable, which we then display to the user. It looks like this when you run it (F5):


The String that appears in the second line means that the age variable contains text. Console.ReadLine() gives us the user's input, so we're saying: hey, we want the user's input to go into this thing called age, which contains text (String). These things like name or age, where we store user input (and possibly other stuff) are called variables. String is the data type of the variable: it describes what kind of data (text, numbers, decimal numbers, etc) the variable holds.

In this particular example, we're interested in getting the user's age, which is usually a number. In such a case, it makes more sense to store it as a number. For this, we use the int (integer) data type. However, Console.ReadLine() can only return a String, so we need a means to change that String into an integer. Fortunately, we can do that using Convert.ToInt32():

            Console.WriteLine("Enter your age:");
            String age = Console.ReadLine();
            int usersAge = Convert.ToInt32(age);
            Console.WriteLine("Only {0}?", age);

This does not change the output of the program. However, storing the age in an int allows us to do certain arithmetic operations. For example:

            Console.WriteLine("Enter your age:");
            String age = Console.ReadLine();
            int usersAge = Convert.ToInt32(age);
            int pensionAge = 65;
            int yearsLeftTillPension = pensionAge - usersAge;
            Console.WriteLine("{0} years left till pension!", yearsLeftTillPension);

In this case we're using another int variable to store the retirement age, 65. Since usersAge and pensionAge are both integers, we can subtract them and store the result in yearsLeftTillPension. Running the program (F5) brings a grim reminder that pension isn't coming anytime soon:


There's one thing we still have to take care of, though. What happens if a user writes normal text instead of a number? Basically, Convert.ToInt32() explodes and crashes the program (to get out of that, either close the console window, or press Shift+F5 in SharpDevelop):


That's not a nice thing for a program to do, and Father Christmas will certainly take note when preparing his gifts for the next Christmas season. There are many ways in which we can handle this unexpected behaviour, but we aren't ready for this yet. So keep watch for another article here, when all shall be revealed. Until then... happy coding! :)