Console Games - Snake - Part 1

November 23, 2014

Based on this earlier post, we had a working console game. Admittedly it doesn’t do much, apart from allow you to move a star around the screen. In order to turn this into a snake game, the first thing to do is to no longer clear the screen:



        private static void DrawScreen()
        {
            //Console.Clear();
            Console.SetCursorPosition(\_left, \_top);
            Console.Write('\*');            
        }


That gives us a snake - but you might notice that when you move left, it doesn’t ‘trail’. There is a possible workaround (albeit, not massively efficient - although remember that this is a game with the purpose of teaching programming).

First, create a struct to hold the position:



        private struct Position
        {
            public int left;
            public int top;
        }

This obviously could be a class. Next, create a list of these:



        private static List<Position> points = new List<Position>();

Here’s what the `AcceptInput` function looks like with the changes:



        private static bool AcceptInput()
        {
            if (!Console.KeyAvailable)
                return false;

            ConsoleKeyInfo key = Console.ReadKey();

            Position currentPos;
            if (points.Count != 0)
                currentPos = points.Last();
            else
                currentPos = GetStartPosition();

            switch (key.Key)
            {
                case ConsoleKey.LeftArrow:
                    currentPos.left--;
                    break;
                case ConsoleKey.RightArrow:
                    currentPos.left++;
                    break;
                case ConsoleKey.UpArrow:
                    currentPos.top--;
                    break;
                case ConsoleKey.DownArrow:
                    currentPos.top++;
                    break;

            }

            points.Add(currentPos);

            return true;
        }

        private static Position GetStartPosition()
        {
            return new Position()
            {
                left = 0,
                top = 0
            };
        }

But what about the tail

In traditional snake, the last element is removed each iteration, unless you `eat` something. Doing it the above way lends itself to this more easily. I’ll tackle that for the next post.



Profile picture

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

© Paul Michaels 2024