snake game in csharp

Snake game is a classic game that can be implemented using C#. Here is a basic implementation of the game using Windows Forms:

  1. First, create a Windows Forms Application project in Visual Studio.
  2. Add a PictureBox control to the form and dock it to fill the form.
  3. Set the BackColor property of the form and the PictureBox to black (or any other color you like).
  4. Define a Snake class that will represent the snake in the game. The class should have properties for the position, length, and direction of the snake. It should also have methods for moving the snake, checking collisions with walls and itself, and growing the snake when it eats food.
main.cs
class Snake
{
    public List<Point> Body { get; set; }
    public Point Head { get { return Body.Last(); } }
    public int Length { get { return Body.Count; } }
    public Direction Direction { get; set; }

    public Snake(Point head, int length, Direction direction)
    {
        Body = new List<Point>();
        for (int i = 0; i < length; i++)
        {
            Body.Add(new Point(head.X - i, head.Y));
        }
        Direction = direction;
    }

    public void Move()
    {
        // Remove the tail and add a new head based on the current direction
        Point newHead = new Point(Head.X + Direction.X, Head.Y + Direction.Y);
        Body.Remove(Body.First());
        Body.Add(newHead);
    }

    public bool CheckCollision(Point p)
    {
        // Check if the given point collides with the snake
        return Body.Any(b => b.Equals(p));
    }

    public bool CheckSelfCollision()
    {
        // Check if the snake collides with itself
        return Body.Count(b => b.Equals(Head)) > 1;
    }

    public bool CheckWallCollision(Size s)
    {
        // Check if the snake collides with the walls
        return Head.X < 0 || Head.X >= s.Width || Head.Y < 0 || Head.Y >= s.Height;
    }

    public void Grow()
    {
        // Add a new body segment to the snake
        Body.Insert(0, new Point(Head.X + Direction.X, Head.Y + Direction.Y));
    }
}

enum Direction { Up = -1, Down = 1, Left = -2, Right = 2 };
1444 chars
52 lines
  1. Define a Food class that will represent the food in the game. The class should have a property for the position of the food and a method for drawing the food on the form.
main.cs
class Food
{
    public Point Position { get; set; }

    public Food(Point position)
    {
        Position = position;
    }

    public void Draw(Graphics g)
    {
        g.FillRectangle(Brushes.Red, new Rectangle(Position.X * GameSettings.TileSize, Position.Y * GameSettings.TileSize, GameSettings.TileSize, GameSettings.TileSize));
    }
}
346 chars
15 lines
  1. Define a GameSettings class that will contain settings for the game, such as the size of the tiles and the speed of the snake.
main.cs
static class GameSettings
{
    public const int TileSize = 20;
    public const int Speed = 100;
}
100 chars
6 lines
  1. In the form code, create instances of the Snake and Food classes and handle the KeyDown event to change the direction of the snake. In the Timer.Tick event, move the snake and check for collisions with the walls, the snake itself, and the food. If the snake collides with the food, grow the snake and create a new instance of the Food class at a random position.
main.cs
public partial class Form1 : Form
{
    private Timer gameTimer;
    private Snake snake;
    private Food food;

    public Form1()
    {
        InitializeComponent();
        snake = new Snake(new Point(10, 10), 3, Direction.Right);
        food = new Food(new Point(5, 5));
        gameTimer = new Timer();
        gameTimer.Interval = GameSettings.Speed;
        gameTimer.Tick += GameTimer_Tick;
        gameTimer.Start();
    }

    private void GameTimer_Tick(object sender, EventArgs e)
    {
        snake.Move();

        if (snake.CheckWallCollision(ClientSize) || snake.CheckSelfCollision())
        {
            gameTimer.Stop();
            MessageBox.Show("Game over!");
            Close();
        }

        if (snake.CheckCollision(food.Position))
        {
            snake.Grow();
            food = new Food(new Point(Random.Next(ClientSize.Width / GameSettings.TileSize), Random.Next(ClientSize.Height / GameSettings.TileSize)));
        }

        Draw();
    }

    private void Draw()
    {
        using (Graphics g = CreateGraphics())
        {
            g.Clear(BackColor);
            snake.Body.ForEach(b => g.FillRectangle(Brushes.Green, new Rectangle(b.X * GameSettings.TileSize, b.Y * GameSettings.TileSize, GameSettings.TileSize, GameSettings.TileSize)));
            food.Draw(g);
        }
    }

    private static Random Random = new Random();

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Up:
                if (snake.Direction != Direction.Down)
                    snake.Direction = Direction.Up;
                break;
            case Keys.Down:
                if (snake.Direction != Direction.Up)
                    snake.Direction = Direction.Down;
                break;
            case Keys.Left:
                if (snake.Direction != Direction.Right)
                    snake.Direction = Direction.Left;
                break;
            case Keys.Right:
                if (snake.Direction != Direction.Left)
                    snake.Direction = Direction.Right;
                break;
        }
    }
}
2149 chars
73 lines

This is a basic implementation of the snake game in C#. You can add more features, such as scorekeeping and sound effects, to make the game more interesting.

gistlibby LogSnag