C# Tutorial – How to make a Classic Snakes Game with Windows form and Visual Studio [Updated]

Hi Welcome to this tutorial. This tutorial is an updated version of the C# Snakes game tutorial we have done before on the website.  This video tutorial will explain all of the core components needed to make this classic game in windows form in visual studio with C# programming language. We wont be using any oher game frameworks to make this work however we will be using some OOP programming practices in this tutorial. Everything you need to know and how to use them inside of the game effectively is explained in the tutorial.

Lesson objectives –

  1. Make a full snakes game in visual studio
  2. Using custom classes to load and reload default settings
  3. Using custom classes to draw the snake and food to the game
  4. Working with Keyboard controls
  5. Keeping score and high score in the current game session
  6. Able to take snap of the game when it ends
  7. Starting and Restarting the game to replay

Full Video Tutorial on How to make the classic snake game in Visual Studio with C#

 
Download Snake Game Project Tutorial on MOOICT GitHub
 

Source Code –

Circle Class –

This class will help us draw circles to the form, we will use this one to determine the X and Y position of the circles in the screen. This will be used for both the SNAKE and the Food objects inside of the game.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Classic_Snakes_Game_Tutorial___MOO_ICT
{
    class Circle
    {
        public int X { get; set; }
        public int Y { get; set; }

        public Circle()
        {
            X = 0;
            Y = 0;
        }
    }
}

 

Settings Class

This is the settings class for the game. This class will be used to load up the default settings for the game objects only. It will load the size in height and width of the circles that will be drawn to the project also the direction the snake should be moving when the game initially loads.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Classic_Snakes_Game_Tutorial___MOO_ICT
{
    class Settings
    {

        public static int Width { get; set; }
        public static int Height { get; set; }

        public static string directions;

        public Settings()
        {
            Width = 16;
            Height = 16;
            directions = "left";
        }
    }
}

 

Main Form C# Scripts

This is the main form1.cs code. In this script we have given all of the instructions necessary for the game and how it will behave when the game loads up. We have several events in the code below for example the Key Down, Key Up, Timer,  2 Click Events and a Paint Event. Also we have 3 custom functions such as Restart Game, Game Over and Eat Food function for the snake.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Drawing.Imaging; // add this for the JPG compressor

namespace Classic_Snakes_Game_Tutorial___MOO_ICT
{
    public partial class Form1 : Form
    {

        private List<Circle> Snake = new List<Circle>();
        private Circle food = new Circle();

        int maxWidth;
        int maxHeight;

        int score;
        int highScore;

        Random rand = new Random();

        bool goLeft, goRight, goDown, goUp;


        public Form1()
        {
            InitializeComponent();

            new Settings();
        }

        private void KeyIsDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Left && Settings.directions != "right")
            {
                goLeft = true;
            }
            if (e.KeyCode == Keys.Right && Settings.directions != "left")
            {
                goRight = true;
            }
            if (e.KeyCode == Keys.Up && Settings.directions != "down")
            {
                goUp = true;
            }
            if (e.KeyCode == Keys.Down && Settings.directions != "up")
            {
                goDown = true;
            }



        }

        private void KeyIsUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
            {
                goLeft = false;
            }
            if (e.KeyCode == Keys.Right)
            {
                goRight = false;
            }
            if (e.KeyCode == Keys.Up)
            {
                goUp = false;
            }
            if (e.KeyCode == Keys.Down)
            {
                goDown = false;
            }
        }

        private void StartGame(object sender, EventArgs e)
        {
            RestartGame();
        }

        private void TakeSnapShot(object sender, EventArgs e)
        {
            Label caption = new Label();
            caption.Text = "I scored: " + score + " and my Highscore is " + highScore + " on the Snake Game from MOO ICT";
            caption.Font = new Font("Ariel", 12, FontStyle.Bold);
            caption.ForeColor = Color.Purple;
            caption.AutoSize = false;
            caption.Width = picCanvas.Width;
            caption.Height = 30;
            caption.TextAlign = ContentAlignment.MiddleCenter;
            picCanvas.Controls.Add(caption);

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.FileName = "Snake Game SnapShot MOO ICT";
            dialog.DefaultExt = "jpg";
            dialog.Filter = "JPG Image File | *.jpg";
            dialog.ValidateNames = true;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                int width = Convert.ToInt32(picCanvas.Width);
                int height = Convert.ToInt32(picCanvas.Height);
                Bitmap bmp = new Bitmap(width, height);
                picCanvas.DrawToBitmap(bmp, new Rectangle(0,0, width, height));
                bmp.Save(dialog.FileName, ImageFormat.Jpeg);
                picCanvas.Controls.Remove(caption);
            }





        }

        private void GameTimerEvent(object sender, EventArgs e)
        {
            // setting the directions

            if (goLeft)
            {
                Settings.directions = "left";
            }
            if (goRight)
            {
                Settings.directions = "right";
            }
            if (goDown)
            {
                Settings.directions = "down";
            }
            if (goUp)
            {
                Settings.directions = "up";
            }
            // end of directions

            for (int i = Snake.Count - 1; i >= 0; i--)
            {
                if (i == 0)
                {

                    switch (Settings.directions)
                    {
                        case "left":
                            Snake[i].X--;
                            break;
                        case "right":
                            Snake[i].X++;
                            break;
                        case "down":
                            Snake[i].Y++;
                            break;
                        case "up":
                            Snake[i].Y--;
                            break;
                    }

                    if (Snake[i].X < 0)
                    {
                        Snake[i].X = maxWidth;
                    }
                    if (Snake[i].X > maxWidth)
                    {
                        Snake[i].X = 0;
                    }
                    if (Snake[i].Y < 0)
                    {
                        Snake[i].Y = maxHeight;
                    }
                    if (Snake[i].Y > maxHeight)
                    {
                        Snake[i].Y = 0;
                    }


                    if (Snake[i].X == food.X && Snake[i].Y == food.Y)
                    {
                        EatFood();
                    }

                    for (int j = 1; j < Snake.Count; j++)
                    {

                        if (Snake[i].X == Snake[j].X && Snake[i].Y == Snake[j].Y)
                        {
                            GameOver();
                        }

                    }


                }
                else
                {
                    Snake[i].X = Snake[i - 1].X;
                    Snake[i].Y = Snake[i - 1].Y;
                }
            }
            picCanvas.Invalidate();
        }

        private void UpdatePictureBoxGraphics(object sender, PaintEventArgs e)
        {
            Graphics canvas = e.Graphics;

            Brush snakeColour;

            for (int i = 0; i < Snake.Count; i++)
            {
                if (i == 0)
                {
                    snakeColour = Brushes.Black;
                }
                else
                {
                    snakeColour = Brushes.DarkGreen;
                }

                canvas.FillEllipse(snakeColour, new Rectangle
                    (
                    Snake[i].X * Settings.Width,
                    Snake[i].Y * Settings.Height,
                    Settings.Width, Settings.Height
                    ));
            }


            canvas.FillEllipse(Brushes.DarkRed, new Rectangle
            (
            food.X * Settings.Width,
            food.Y * Settings.Height,
            Settings.Width, Settings.Height
            ));
        }

        private void RestartGame()
        {
            maxWidth = picCanvas.Width / Settings.Width - 1;
            maxHeight = picCanvas.Height / Settings.Height - 1;

            Snake.Clear();

            startButton.Enabled = false;
            snapButton.Enabled = false;
            score = 0;
            txtScore.Text = "Score: " + score;

            Circle head = new Circle { X = 10, Y = 5 };
            Snake.Add(head); // adding the head part of the snake to the list

            for (int i = 0; i < 100; i++)
            {
                Circle body = new Circle();
                Snake.Add(body);
            }

            food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight)};

            gameTimer.Start();

        }

        private void EatFood()
        {
            score += 1;

            txtScore.Text = "Score: " + score;

            Circle body = new Circle
            {
                X = Snake[Snake.Count - 1].X,
                Y = Snake[Snake.Count - 1].Y
            };

            Snake.Add(body);

            food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight) };
        }

        private void GameOver()
        {
            gameTimer.Stop();
            startButton.Enabled = true;
            snapButton.Enabled = true;

            if (score > highScore)
            {
                highScore = score;

                txtHighScore.Text = "High Score: " + Environment.NewLine + highScore;
                txtHighScore.ForeColor = Color.Maroon;
                txtHighScore.TextAlign = ContentAlignment.MiddleCenter;
            }
        }
    }
}

 

 

 




2 responses to “C# Tutorial – How to make a Classic Snakes Game with Windows form and Visual Studio [Updated]”

  1. Volkan Coskun says:

    is there any reason you have flags to indicate left,right,up & down?
    Also, is the KeyIsUp function needed ?

  2. Volkan Coskun says:

    I refactored your code to :

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    static class Constants
    {
    public const int headPos = 0;
    public const int gameTimerInterval = 500;
    }

    namespace snake
    {
    public partial class Form1 : Form
    {
    private List Snake = new List();
    private Circle food = new Circle();
    int maxWidth;
    int maxHeight;
    Random rand = new Random();

    public Form1()
    {
    InitializeComponent();
    new setting();
    }
    private void KeyIsDown(object sender, KeyEventArgs e)
    {
    if (e.KeyCode == Keys.Left && setting.direction != “RIGHT”)
    {
    setting.direction = “LEFT”;
    }
    if (e.KeyCode == Keys.Right && setting.direction != “LEFT”)
    {
    setting.direction = “RIGHT”;
    }
    if (e.KeyCode == Keys.Up && setting.direction != “DOWN”)
    {
    setting.direction = “UP”;
    }
    if (e.KeyCode == Keys.Down && setting.direction != “UP”)
    {
    setting.direction = “DOWN”;
    }
    }
    private void StartGame(object sender, EventArgs e)
    {
    RestartGame();
    }
    private void GameTimerEvent(object sender, EventArgs e)
    {
    checkFood();

    for (int bodyIndex = Snake.Count – 1; bodyIndex >= 0; bodyIndex–)
    {
    if (bodyIndex == Constants.headPos)
    {
    updateSnakePos();
    }
    else
    {
    Snake[bodyIndex].X = Snake[bodyIndex – 1].X;
    Snake[bodyIndex].Y = Snake[bodyIndex – 1].Y;
    }
    }
    checkSnakeCollision();
    picCanvas.Invalidate();
    }
    private void updateSnakePos()
    {
    switch (setting.direction)
    {
    case “LEFT”:
    Snake[Constants.headPos].X–;

    if (Snake[Constants.headPos].X maxWidth)
    {
    gameOver();
    }
    break;
    case “DOWN”:
    Snake[Constants.headPos].Y++;

    if (Snake[Constants.headPos].Y > maxHeight)
    {
    gameOver();
    }
    break;
    case “UP”:
    Snake[Constants.headPos].Y–;

    if (Snake[Constants.headPos].Y < 0)
    {
    gameOver();
    }
    break;
    default:
    break;
    }
    }
    private void drawSnake(object sender, PaintEventArgs e)
    {
    Graphics canvas = e.Graphics;

    for (int i = 0; i < Snake.Count; i++)
    {
    canvas.FillEllipse((i == Constants.headPos) ? Brushes.Black : Brushes.DarkGreen, new Rectangle(Snake[i].X * setting.Width, Snake[i].Y * setting.Height, setting.Width, setting.Height));
    }
    canvas.FillEllipse(Brushes.DarkRed, new Rectangle(food.X * setting.Width, food.Y * setting.Height, setting.Width, setting.Height));
    }

    private void RestartGame()
    {
    maxWidth = picCanvas.Width / setting.Width – 1;
    maxHeight = picCanvas.Height / setting.Height – 1;

    Snake.Clear();

    startButton.Enabled = false;

    Circle head = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight)};
    Snake.Add(head); // adding the head part of the snake to the list

    for (int i = 0; i < 3; i++)
    {
    Circle body = new Circle();
    Snake.Add(body);
    }

    food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight) };

    gameTimer.Start();
    }

    private void checkSnakeCollision()
    {
    for (int j = 1; j < Snake.Count; j++)
    {
    if (Snake[Constants.headPos].X == Snake[j].X && Snake[Constants.headPos].Y == Snake[j].Y)
    {
    gameOver();
    }
    }
    }

    private void gameOver()
    {
    gameTimer.Interval = Constants.gameTimerInterval;
    gameTimer.Stop();
    startButton.Enabled = true;
    }
    private void checkFood()
    {
    if (Snake[Constants.headPos].X == food.X && Snake[Constants.headPos].Y == food.Y)
    {
    Circle body = new Circle
    {
    X = Snake[Snake.Count – 1].X,
    Y = Snake[Snake.Count – 1].Y
    };

    if(gameTimer.Interval / 2 == 0)
    {
    gameTimer.Interval = 5;
    }
    else
    {
    gameTimer.Interval = gameTimer.Interval / 2;
    }
    Snake.Add(body);

    food = new Circle { X = rand.Next(2, maxWidth), Y = rand.Next(2, maxHeight) };
    }
    }
    }
    }