wpf implements snake game

Everyone has played the Snake game, and its gameplay is also very simple: use the game buttons to control the direction of the snake up, down, left, and right, and look for something to eat. You will get certain points for each bite you take, and the snake’s body will grow longer as it eats. , the longer the body, the more difficult it is to play. You can’t touch the wall, bite your own body, and you can’t bite your own tail. When you reach a certain score, you can pass the level and then continue to play the next level.

Below is a simple example of using WPF to implement a snake game. First, create a WPF application named `SnakeGame` and place the following code in the `MainWindow.xaml` file:

```xaml
<Window x:Class="SnakeGame.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Snake Game" Height="400" Width="400"
        KeyDown="Window_KeyDown">
    <Grid>
        <Canvas x:Name="GameCanvas" Background="Black" Focusable="True">




        </Canvas>
    </Grid>
</Window>
```

Next, place the following code in the `MainWindow.xaml.cs` file:

```csharp
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Windows.Threading;




namespace SnakeGame
{
    public partial class MainWindow : Window
    {
        private const int CellSize = 20;
        private const int GameWidth = 400;
        private const int GameHeight = 400;
        private const int TimerInterval = 200;




        private Snake snake;
        private DispatcherTimer gameTimer;
        private Direction currentDirection;




        public MainWindow()
        {
            InitializeComponent();




            snake = new Snake();
            currentDirection = Direction.Right;




            gameTimer = new DispatcherTimer();
            gameTimer.Tick + = GameTimer_Tick;
            gameTimer.Interval = new System.TimeSpan(0, 0, 0, 0, TimerInterval);
            gameTimer.Start();




            DrawSnake();
            DrawFood();
        }




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




            if (snake.HasCollision() || snake.HasSelfCollision())
            {
                gameTimer.Stop();
                MessageBox.Show("Game Over");
                return;
            }




            if (snake.EatFood())
            {
                DrawFood();
            }
            else
            {
                EraseTail();
            }




            DrawSnake();
        }




        private void DrawSnake()
        {
            GameCanvas.Children.Clear();




            foreach (SnakePart part in snake.parts)
            {
                Rectangle rect = new Rectangle
                {
                    Width = CellSize,
                    Height = CellSize,
                    Fill = Brushes.Green
                };




                Canvas.SetLeft(rect, part.x);
                Canvas.SetTop(rect, part.y);
                GameCanvas.Children.Add(rect);
            }
        }




        private void DrawFood()
        {
            Food food = new Food(GameWidth, GameHeight, CellSize);




            Rectangle rect = new Rectangle
            {
                Width = CellSize,
                Height = CellSize,
                Fill = Brushes.Red
            };




            Canvas.SetLeft(rect, food.x);
            Canvas.SetTop(rect, food.y);
            GameCanvas.Children.Add(rect);
        }




        private void EraseTail()
        {
            if (GameCanvas.Children.Count > snake.parts.Count)
            {
                GameCanvas.Children.RemoveAt(0);
            }
        }




        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            switch(e.Key)
            {
                case Key.Up:
                    currentDirection = Direction.Up;
                    break;
                case Key.Down:
                    currentDirection = Direction.Down;
                    break;
                case Key.Left:
                    currentDirection = Direction.Left;
                    break;
                case Key.Right:
                    currentDirection = Direction.Right;
                    break;
            }
        }
    }




    public enum Direction
    {
        Up,
        Down,
        Left,
        Right
    }




    public class Snake
    {
        public List<SnakePart> parts;
        private int cellSize;




        public Snake()
        {
            parts = new List<SnakePart>();
            parts.Add(new SnakePart(0, 0));
            cellSize = MainWindow.CellSize;
        }




        public void Move(Direction direction)
        {
            int headX = parts[0].x;
            int headY = parts[0].y;




            switch (direction)
            {
                case Direction.Up:
                    headY -= cellSize;
                    break;
                case Direction.Down:
                    headY + = cellSize;
                    break;
                case Direction.Left:
                    headX -= cellSize;
                    break;
                case Direction.Right:
                    headX + = cellSize;
                    break;
            }




            SnakePart newHead = new SnakePart(headX, headY);
            parts.Insert(0, newHead);
        }




        public bool HasCollision()
        {
            SnakePart head = parts[0];




            return head.x < 0 ||
                head.x >= MainWindow.GameWidth ||
                head.y < 0 ||
                head.y >= MainWindow.GameHeight;
        }




        public bool HasSelfCollision()
        {
            SnakePart head = parts[0];




            for (int i = 1; i < parts.Count; i + + )
            {
                if (parts[i].x == head.x & parts[i].y == head.y)
                {
                    return true;
                }
            }




            return false;
        }




        public bool EatFood()
        {
            SnakePart head = parts[0];




            // Check if the head of the snake overlaps with the food
            if (head.x == Food.x & amp; & amp; head.y == Food.y)
            {
                return true;
            }




            return false;
        }
    }




    public class SnakePart
    {
        public int x;
        public int y;




        public SnakePart(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }




    public class Food
    {
        private int maxWidth;
        private int maxHeight;
        private int cellSize;
        private System.Random random;




        public int x { get; private set; }
        public int y { get; private set; }




        public Food(int maxWidth, int maxHeight, int cellSize)
        {
            this.maxWidth = maxWidth;
            this.maxHeight = maxHeight;
            this.cellSize = cellSize;
            random = new System.Random();




            GeneratePosition();
        }




        private void GeneratePosition()
        {
            x = random.Next(0, maxWidth / cellSize) * cellSize;
            y = random.Next(0, maxHeight / cellSize) * cellSize;
        }
    }
}
```

This example uses a `Canvas` as the game’s drawing area. The `Snake` class represents a greedy snake, the `SnakePart` class represents a part of a greedy snake, and the `Food` class represents food. Use the arrow keys on the keyboard to control the movement of the snake.

The above is an example of a simple snake game implementation, which you can extend and improve according to your own needs. Hope this helps!

Join the group to learn and communicate plus: mm1552923

If you like my article, then

“Watching” and forwarding are the greatest support for me!