C# 开发贪吃蛇游戏

贪吃蛇大家都玩过,所以就不过多解释 这是一个Winfrom项目即贴既玩

cs 复制代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace SnakeGame
{
    public partial class Form1 : Form
    {
        private const int GridSize = 10; // 每个格子的尺寸
        private const int WidthInGrid = 100;    // 游戏区域的宽度(格子数)
        private const int HeightInGrid = 70;   // 游戏区域的高度(格子数)

        private List<Rectangle> snake = new List<Rectangle>
            {
                new Rectangle(100, 100, GridSize, GridSize)  // 初始化蛇的起始位置
            };  // 蛇的身体部分(每个部分都是一个矩形)
        private Rectangle food;         // 食物的矩形区域
        private Random random;          // 用于生成随机数
        private int dx, dy;             // 蛇的移动方向
        private Timer timer;            // 游戏定时器
        private bool isGameOver;        // 游戏是否结束
        private int fastSpeed = 20;    // 按住方向键时的加速速度(定时器间隔)
        private int defaultSpeed = 100; // 默认的蛇的速度(定时器间隔)
        // 新增:记录蛇的当前大小
        private int snakeSegmentWidth = GridSize;
        private int snakeSegmentHeight = GridSize;

        public Form1()
        {
            InitializeComponent();
            Start();
        }

        public void Start()
        {
            label2.Visible = false;
            label1.Visible = false;
            button1.Visible = false;
            this.DoubleBuffered = true; // 开启双缓冲,减少闪烁

            // 根据格子数调整窗体尺寸
            this.Width = WidthInGrid * GridSize + 16;  // Form的宽度
            this.Height = HeightInGrid * GridSize + 39; // Form的高度

            random = new Random();

            timer = new Timer { Interval = defaultSpeed }; // 设置定时器初始速度
            timer.Tick += Timer_Tick;

            ResetGame();
        }

        private void ResetGame()
        {
            food = GenerateFood();
            dx = GridSize; // 初始时蛇向右移动
            dy = 0;
            isGameOver = false;

            timer.Start(); // 启动游戏定时器
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            if (isGameOver)
            {
                timer.Stop();
                label1.Visible = true;
                label1.Text = "Game Over";
                button1.Visible = true;
                button1.Enabled = true;
                label2.Visible = true;
                return;
            }

            // 计算蛇头的新位置
            var head = snake.First();
            var newHead = new Rectangle(head.X + dx, head.Y + dy, snakeSegmentWidth, snakeSegmentHeight);

            // 如果蛇头碰到墙壁或自己,游戏结束
            if (newHead.X < 0 || newHead.Y < 0 || newHead.X >= WidthInGrid * GridSize || newHead.Y >= HeightInGrid * GridSize || snake.Contains(newHead))
            {
                isGameOver = true;
                return;
            }
            if (snake.Count % 5 == 0)
            {
                snakeSegmentWidth = (int)(GridSize + snake.Count);
                snakeSegmentHeight = (int)(GridSize + snake.Count);
            }
            // 将蛇头添加到蛇身前
            snake.Insert(0, newHead);

            // 如果蛇吃到食物,生成新食物并让蛇变长
            if (newHead.IntersectsWith(food))
            {
                food = GenerateFood();
            }
            else
            {
                // 否则去掉蛇尾
                snake.RemoveAt(snake.Count - 1);
            }

            // 重新绘制游戏画面
            Invalidate();
        }

        private Rectangle GenerateFood()
        {
            // 随机生成食物的位置,确保食物生成在窗体内
            int x = random.Next(0, WidthInGrid) * GridSize;
            int y = random.Next(0, HeightInGrid) * GridSize;
            return new Rectangle(x, y, GridSize, GridSize);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Visible = false;
            button1.Visible = false;
            button1.Enabled = false;
            isGameOver = false;
            label2.Visible = false;
            snakeSegmentWidth = GridSize;
            snakeSegmentHeight = GridSize;
            snake = new List<Rectangle>
            {
                new Rectangle(100, 100, GridSize, GridSize)  // 初始化蛇的起始位置
            };
            dx = GridSize; // 初始时蛇向右移动
            dy = 0;
            timer.Interval = defaultSpeed;
            timer.Start();
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            // 控制蛇的移动方向
            if (e.KeyCode == Keys.Up&& dy==0)
            {
                dx = 0;
                dy = -GridSize;
                timer.Interval = fastSpeed; // 按住时加速
            }
            else if (e.KeyCode == Keys.Down && dy == 0)
            {
                dx = 0;
                dy = GridSize;
                timer.Interval = fastSpeed; // 按住时加速
            }
            else if (e.KeyCode == Keys.Left && dx == 0)
            {
                dx = -GridSize;
                dy = 0;
                timer.Interval = fastSpeed; // 按住时加速
            }
            else if (e.KeyCode == Keys.Right && dx == 0)
            {
                dx = GridSize;
                dy = 0;
                timer.Interval = fastSpeed; // 按住时加速
            }
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            var g = e.Graphics;

            // 绘制蛇身
            for (int i = 0; i < snake.Count; i++)
            {
                var segment = snake[i];

                // 蛇头(第一个部分)为黄色,其余为绿色
                if (i == 0)
                {
                    g.FillRectangle(Brushes.Yellow, segment); // 蛇头为黄色
                }
                else
                {
                    g.FillRectangle(Brushes.Lime, segment); // 蛇身为绿色
                }
            }

            // 绘制食物
            g.FillRectangle(Brushes.Red, food);
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            // 松开方向键时恢复到默认速度
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
            {
                timer.Interval = defaultSpeed; // 恢复原来的速度
            }
        }
    }
}
相关推荐
漫路在线23 分钟前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
小辉懂编程1 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
醍醐三叶2 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
Magnum Lehar3 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld8573 小时前
java集合
java·开发语言·windows
成功人chen某3 小时前
配置VScodePython环境Python was not found;
开发语言·python
动感光博4 小时前
Unity序列化字段、单例模式(Singleton Pattern)
unity·单例模式·c#
海绵宝宝贾克斯儿4 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01124 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
isyangli_blog4 小时前
(1-4)Java Object类、Final、注解、设计模式、抽象类、接口、内部类
java·开发语言