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 分钟前
@SneakyThrows注解
开发语言
我的xiaodoujiao6 分钟前
快速学习Python基础知识详细图文教程14--模块
开发语言·python·学习·测试工具
NoteStream18 分钟前
【c语言基础】C语言常见概念
c语言·开发语言·编辑器
吃好睡好便好20 分钟前
MATLAB中图像的线性变换
开发语言·图像处理·学习·计算机视觉·matlab
charlie11451419127 分钟前
Cinux —— 给物理内存建账本:bitmap 物理内存管理器
开发语言·c++·操作系统·开源项目
YUS云生30 分钟前
大模型学习·第41天:LangChain进阶——提示词模板与Chain链式调用
学习·langchain·c#
ShiXZ2131 小时前
Java 8 Stream API 实用技巧详解:从入门到精通
java·开发语言
冻柠檬飞冰走茶1 小时前
PTA基础编程题目集 7-27 冒泡法排序(C语言实现)
c语言·开发语言·数据结构·算法
听雨入夜1 小时前
“同声传译”还是“全文翻译”?为何HotSpot虚拟机仍要保留解释器?
开发语言·python
随风M记忆s1 小时前
GEE&Python-demo:利用Sentinel-监测北京奥林匹克森林公园年NDVI变化(附Python版)
开发语言·python·sentinel