Gigi Labs

Please follow Gigi Labs for the latest articles.

Thursday, May 9, 2013

C#: ASCII Art Game (Part 2)

Hello, and welcome to this second article about creating an ASCII-art game. This article continues where yesterday's article, C#: ASCII Art Game (Part 1), left off. So if you missed it, read it first! :) We're going to continue from the code at the end of that article.

In today's article we'll implement some basic gameplay in our console-window-based game, Chase the Star. We're going to learn about switch statements, randomness, and add a touch of colour to the game. Yippee! ;)

Let's start with that switch statement. In yesterday's code, we had a bunch of if statements that check whether the arrow keys or the ESC key was pressed. When you have a bunch of if statements checking the value of the same thing (in this case keyInfo.Key), it is more convenient to use a switch statement instead, as follows:

                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
             
                switch(keyInfo.Key)
                {
                    case ConsoleKey.Escape:
                        quit = true;
                        break;
                    case ConsoleKey.UpArrow:
                        y--;
                        break;
                    case ConsoleKey.DownArrow:
                        y++;
                        break;
                    case ConsoleKey.LeftArrow:
                        x--;
                        break;
                    case ConsoleKey.RightArrow:
                        x++;
                        break;
                    default:
                        // nothing here... run along, kids
                        break;
                }

In the brackets next to switch, we put the variable whose value we are interested in. Then, we put a case statement for each value that interests us. Optionally, we can also include a default statement. This works pretty much like an else: it is used when none of the case values apply. A break statement must be placed at the end of all case and default sections.

Towards the end of yesterday's article, you might remember that we had a problem when the user runs off the screen. The console is usually 80 characters wide and 25 characters high, so we can check the player's position to ensure she never goes out of bounds:

                switch(keyInfo.Key)
                {
                    case ConsoleKey.Escape:
                        quit = true;
                        break;
                    case ConsoleKey.UpArrow:
                        if (y > 0)
                            y--;
                        break;
                    case ConsoleKey.DownArrow:
                        if (y < 24)
                            y++;
                        break;
                    case ConsoleKey.LeftArrow:
                        if (x > 0)
                            x--;
                        break;
                    case ConsoleKey.RightArrow:
                        if (x < 79)
                            x++;
                        break;
                }

Now, you'll find you can't run off the edge of the screen! If you're scratching your head a little, just remember that (0, 0) is the top-left corner. x increases as you go right, and y increases as you go down. Since both start at zero, then the highest x value we can accept is 79, not 80. Similarly, the highest y is 24.

Right now, all you can do is run around. Let's make it a little more interesting. We're going to place a star somewhere in the window, and once the user runs into it, it will appear somewhere else, Hence the name, Chase the Star. The first thing we need is a pair of new variables to store the x and y position of the star. Put these towards the beginning, before or after your x and y variables:

            int starX = 64;
            int starY = 5;

After the part where we write our "X" to the console window, let's add code to show our star:

                Console.SetCursorPosition(starX, starY);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("*");
                Console.ResetColor();

Here, we set the cursor position to the location where the star is. We write an asterisk to represent the star, and we write it in yellow to add a touch of colour. After that, we reset the console colour to the default light grey. If we don't, everything will be written in yellow! Here's what we've got so far:



After the switch statement, add this:

                if (x == starX && y == starY)
                {
                    Random random = new Random();
                    starX = random.Next(080);
                    starY = random.Next(025);
                }

This small piece of logic takes care of what happens when you run into the star. When that happens, we move the star somewhere else by setting starX and starY to some random values. In order to obtain a random number, we use Random.Next(). We can specify a range (as above) in which the random number should be generated. For starX, for example, we are requesting a random number between 0 and 79 (since the upper bound is not inclusive, the 80 doesn't count).

Awesome! You have just made your first game, and it's even a little bit of fun to play. :D

You should now be extremely proud of yourself, and with some more practice, you might even become a national hero at some point.

Here's the complete code:

            int x = 40;
            int y = 12;
            int starX = 64;
            int starY = 5;
            bool quit = false;
            Console.Title = "Chase the Star";
         
            while (quit == false)
            {
                Console.Clear();
                Console.SetCursorPosition(x, y);
                Console.Write("X");
             
                Console.SetCursorPosition(starX, starY);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.Write("*");
                Console.ResetColor();
             
                ConsoleKeyInfo keyInfo = Console.ReadKey(true);
             
                switch(keyInfo.Key)
                {
                    case ConsoleKey.Escape:
                        quit = true;
                        break;
                    case ConsoleKey.UpArrow:
                        if (y > 0)
                            y--;
                        break;
                    case ConsoleKey.DownArrow:
                        if (y < 24)
                            y++;
                        break;
                    case ConsoleKey.LeftArrow:
                        if (x > 0)
                            x--;
                        break;
                    case ConsoleKey.RightArrow:
                        if (x < 79)
                            x++;
                        break;
                }

                if (x == starX && y == starY)
                {
                    Random random = new Random();
                    starX = random.Next(080);
                    starY = random.Next(025);
                }
            }

If you want to get your hands a bit dirtier, here's a little exercise. Keep track of the player's score, by adding 10 to it each time she hits the star. Display the score in the bottom left part of the console window. Don't allow the player to walk onto the last line (where y is 24).

There will be plenty more interesting articles in the coming days, so keep coming back for more! :)

2 comments:

  1. To add score:

    - add an integer (e.g. score), set its default value to 0 at the beginning of the program
    - modify random max value & screen value to 23 instead of 23 (random starts from 0, hence 24 instead of 25)
    - add 10 when entering condition if (x == starX && y == starY) - code: score += 10;
    - finally display score: Console.SetCursorPosition(0, 24);
    Console.Write("Score: {0}", score);

    Full code:

    int x = 40;
    int y = 12;
    int starX = 64;
    int starY = 5;
    int score = 0;
    bool quit = false;
    Console.Title = "Chase the Star";

    while (!quit)
    {
    Console.Clear();
    Console.SetCursorPosition(x, y);
    Console.Write("X");

    Console.SetCursorPosition(0, 24);
    Console.Write("Score: {0}", score);

    Console.SetCursorPosition(starX, starY);
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.Write("*");
    Console.ResetColor();

    ConsoleKeyInfo keyInfo = Console.ReadKey(true);

    switch (keyInfo.Key)
    {
    case ConsoleKey.Escape:
    quit = true;
    break;
    case ConsoleKey.UpArrow:
    if (y > 0)
    y--;
    break;
    case ConsoleKey.DownArrow:
    if (y < 23)
    y++;
    break;
    case ConsoleKey.LeftArrow:
    if (x > 0)
    x--;
    break;
    case ConsoleKey.RightArrow:
    if (x < 79)
    x++;
    break;
    }

    if (x == starX && y == starY)
    {
    score += 10;
    Random random = new Random();
    starX = random.Next(0, 80);
    starY = random.Next(0, 24);
    }
    }

    ReplyDelete

Note: Only a member of this blog may post a comment.