Create Snake Game in C# WinForms

Faraz

By Faraz - August 09, 2024

Learn how to create a Snake Game using C# WinForms. Follow this simple guide with source code and easy steps. Perfect for beginners in C# programming.


create-snake-game-using-csharp-winforms.webp

Creating a Snake Game in C# WinForms is a fun way to learn programming. This classic game, loved by many, can be built with simple code in C#. Whether you're new to C# or looking to practice your skills, this guide will walk you through creating the game step by step.

In this tutorial, you will learn how to set up your C# WinForms project, design the game interface, and write the code to control the snake and food. By the end, you'll have a fully working Snake Game that you can play and share with friends. Let’s dive in!

Step 1: Set Up the Project

  1. Open Visual Studio: Start by opening Visual Studio on your computer.
  2. Create a New Project: Select "Windows Forms App (.NET Framework)" and name your project "SnakeGame."
  3. Choose the Framework: Make sure you select .NET Framework 4.7.2 or any other compatible version.
  4. Create the Project: Once you've named your project and selected the framework, click "Create."

Your project is now ready to start building the Snake Game.

Step 2: Design the Game Interface

  1. Add a Timer: Drag a Timer control from the toolbox onto the form. This Timer will control the movement of the snake.
  2. Set Timer Interval: Set the Interval property of the Timer to 100. This controls how fast the snake moves.

Step 3: Initialize Game Variables

In this step, you will set up the variables that will control the game.

1. Declare Variables: In the code, declare variables to manage the snake's position, direction, and speed. You’ll also need variables for the food and score.

private List<Rectangle> snake;
        private Rectangle food;
        private int direction;
        private int score;
        private Random random;

2. Initialize Variables: Initialize these variables in a method called InitializeGame():

private void InitializeGame()
{
    snake = new List<Rectangle>();
    snake.Add(new Rectangle(50, 50, 10, 10)); 
    direction = 0;
    score = 0;
    random = new Random();
    GenerateFood();
    timer1.Start();

Step 4: Handle Keyboard Input

To move the snake, you'll need to capture the arrow key presses.

1. Override the KeyDown Event: Capture the key presses to change the snake's direction.

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    switch (e.KeyCode)
    {
        case Keys.Right:
            if (direction != 2) direction = 0;
            break;
        case Keys.Down:
            if (direction != 3) direction = 1;
            break;
        case Keys.Left:
            if (direction != 0) direction = 2;
            break;
        case Keys.Up:
            if (direction != 1) direction = 3;
            break;
    }
}

2. Update Movement Direction: Based on the key pressed, the direction of the snake will be updated.

Step 5: Move the Snake

Now, you’ll make the snake move on the screen.

1. Timer Tick Event: Handle the Timer's Tick event to move the snake.

private void timer1_Tick(object sender, EventArgs e)
{
    MoveSnake();
    CheckCollision();
    Invalidate(); // Redraw the PictureBox
}

2. MoveSnake Function: Write the MoveSnake function to update the position of the snake.

private void MoveSnake()
{
    Rectangle head = snake[0];
    switch (direction)
    {
        case 0: head.X += 10; break;
        case 1: head.Y += 10; break;
        case 2: head.X -= 10; break;
        case 3: head.Y -= 10; break;
    }

    snake.Insert(0, head);
    if (head.IntersectsWith(food))
    {
        score += 10;
        GenerateFood();
    }
    else
    {
        snake.RemoveAt(snake.Count - 1);
    }
}

Step 6: Generate and Draw Food

The snake needs to eat food to grow. Here’s how you add the food to the game.

1. GenerateFood Function: Create a function to place food randomly on the screen.

private void GenerateFood()
{
    int x = random.Next(0, this.ClientSize.Width / 10) * 10;
    int y = random.Next(0, this.ClientSize.Height / 10) * 10;
    food = new Rectangle(x, y, 10, 10);
}

2. Draw the Snake and Food: Override the OnPaint method to draw the snake and the food on the PictureBox.

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    Graphics g = e.Graphics;
    foreach (Rectangle segment in snake)
    {
        g.FillRectangle(Brushes.Green, segment);
    }
    g.FillRectangle(Brushes.Red, food);
    g.DrawString($"Score: {score}", this.Font, Brushes.Black, new PointF(10, 10));
}

Step 7: Handle Collisions

Finally, handle what happens when the snake hits the wall or itself.

1. CheckCollision Function: Write a function to check if the snake has collided with the walls or itself.

private void CheckCollision()
{
    Rectangle head = snake[0];

    if (head.X < 0 || head.X >= this.ClientSize.Width || head.Y < 0 || head.Y >= this.ClientSize.Height)
    {
        GameOver();
    }

    for (int i = 1; i < snake.Count; i++)
    {
        if (head.IntersectsWith(snake[i]))
        {
            GameOver();
        }
    }
}

2. GameOver Function: Implement a GameOver function to stop the game and show a message.

private void GameOver()
{
    timer1.Stop();
    MessageBox.Show($"Game Over! Your score: {score}", "Game Over");
    InitializeGame();
}

Run the Game

Press F5 or click "Start" to run your game.

Conclusion

Congratulations! You've built a Snake Game using C# WinForms. This project is a great way to practice coding and learn about game development. The steps above guide you through setting up the project, coding the game logic, and handling collisions.

Feel free to add more features, such as increasing the speed of the snake as the score gets higher or adding a high score system.

Download Code

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post