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; // 恢复原来的速度
            }
        }
    }
}
相关推荐
夏幻灵3 小时前
JavaScript this 面试:五种绑定规则、优先级与常见面试陷阱
开发语言·javascript·面试
程序猿编码3 小时前
榨干 RTX5090 算力!Qwen3 专用单卡推理引擎,手写C++/CUDA 算子实现 MTP 推测解码
开发语言·c++·大模型推理·qwen3·多模态推理
曹牧4 小时前
C#:未被引用的函数
c#
bkspiderx5 小时前
Qt 插件机制:动态扩展应用功能的核心框架
开发语言·qt·元数据·qt 插件·qpluginloader
程序员老陆5 小时前
深入理解 C++ thread_local:线程私有存储的正确打开方式
开发语言·c++·程序设计
沐晓时光5 小时前
C语言入门,深入理解指针(3)
c语言·开发语言
码云数智-园园5 小时前
unique_ptr 还是 shared_ptr?C++ 智能指针选型与内存泄漏实战分析
java·开发语言
禾小西6 小时前
07丨Redis 哨兵机制:主库故障后,如何恢复服务?
java·开发语言·redis
我不是阵雨6 小时前
JDK 21虚拟线程Pinning陷阱:一文拔钉解困
java·开发语言
徐小黑ACG7 小时前
Golang 基础05 结构体struct
开发语言·算法·golang