Console Games - Catch - Part 2 (Introducing a game timer)

February 06, 2015

Based on the previous post on this, our next task is to introduce our falling objects.

This is my second go at this post, because I originally wrote it on the basis that we would introduce an actual timer into the game. On reflection, I decided against this for two reasons: 1. Timers are a difficult concept (this is aimed at teaching children to program). 2. We’re already using a rapidly iterating infinite loop, so why not use that.

Since we’re not using a timer, we’ll need to replicate a small amount of the timer functionality; Main currently looks like this:



        static void Main(string[] args)
        {
            Console.CursorVisible = false;
            DrawScreen();
            while (true)
            {
                if (AcceptInput())
                {
                    DrawScreen();
                }
            }
        }

Let’s add a timer variable into the mix:



        static void Main(string[] args)
        {
            Console.CursorVisible = false;
            DrawScreen();
            while (true)
            {
                bool autoUpdate = DateTime.Now >= nextUpdate;
                if (AcceptInput() || autoUpdate)
                {
                    DrawScreen();

                    if (autoUpdate)
                    {
                        AddStar();

                        nextUpdate = DateTime.Now.AddMilliseconds(500);
                    }                    
                }
            }
        }

That is, effectively, our timer. The AddStar method can simply add a new point at random:



        private static void AddStar()
        {
            Random rnd = new Random();
            \_points.Add(new Position() { left = rnd.Next(Console.WindowWidth), top = 0 });
        }

Admittedly there’s not too much “falling” at the minute, but that can be easily addressed.

Falling Stars

So, to make the stars fall, we just need a MoveStars method; like this:



        private static void MoveStars()
        {
            for (int i = 0; i <= \_points.Count() - 1; i++)
            {
                \_points[i] = new Position() { left = \_points[i].left, top = \_points[i].top + 1 };
            }
        }

And call it from main just below AddStar():



. . .
if (autoUpdate)
{
    AddStar();
    MoveStars();

    nextUpdate = DateTime.Now.AddMilliseconds(500);
}                    
. . .

And then…

That’s it; Not exactly a ‘game’ yet - but still it looks the part. In the next and final post in this series I’ll add collision detection and keep score. I’ve uploaded this to GitHub in the same way as I did with the Snake game. Find it here.

consolecatch



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024