wpf实现贪吃蛇游戏

贪吃蛇游戏大家都玩过,它的玩法也很简单:用游戏按键上下左右控制蛇的方向,寻找吃的东西,每吃一口就能得到一定的积分,而且蛇的身子会越吃越长,身子越长玩的难度就越大,不能碰墙,不能咬到自己的身体,更不能咬自己的尾巴,等到了一定的分数,就能过关,然后继续玩下一关。

下面是一个使用WPF实现贪吃蛇游戏的简单示例。首先,创建一个名为`SnakeGame`的WPF应用程序,并在`MainWindow.xaml`文件中放置以下代码:

```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>
```

接下来,在`MainWindow.xaml.cs`文件中放置以下代码:

```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 && 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;
        }
    }
}
```

此示例使用`Canvas`作为游戏的绘图区域。`Snake`类表示贪吃蛇,`SnakePart`类表示贪吃蛇的一个部分,`Food`类表示食物。通过键盘上的箭头键控制贪吃蛇的移动。

以上是一个简单的贪吃蛇游戏的实现示例,你可以根据自己的需求对其进行扩展和改进。希望对你有所帮助!

进群学习交流加 : mm1552923

如果喜欢我的文章,那么

“在看”和转发是对我最大的支持!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值