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; // 恢复原来的速度
            }
        }
    }
}
相关推荐
言乐612 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
yuhulkjv33517 小时前
Claude表格复制到word不再崩溃,AI导出鸭批量导出+格式无损一键搞定
人工智能·ai·c#·word·ai导出鸭
WWJA王文举19 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
zhanghaha131420 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
qq_4480111621 小时前
C语言中的动态内存分配
c语言·开发语言·php
汉字萌萌哒1 天前
2024CSP-J入门级C++真题详解
开发语言·c++
arbboter1 天前
【网络工具】NetProxy网络代理用户手册
开发语言·网络·c#·网络代理·网络异常·代理工具
微小冷1 天前
海康威视相机C#二次开发环境配置
数码相机·c#·.net·海康威视·相机开发
汉字萌萌哒1 天前
2019CCF-CSP入门级C++试题解析
java·开发语言·c++
叠层归一研究院1 天前
AGI 系统(十一):二阶网络 — 二阶递归 × 多主体 (元符号网络)
开发语言·人工智能·算法·php·agi