当前位置: 首页 > news >正文

C# 贪吃蛇游戏

C# 贪吃蛇游戏

C#贪吃蛇游戏实现,使用Windows Forms作为GUI框架。这个实现包含了经典贪吃蛇的所有功能:移动、吃食物、成长、碰撞检测和计分系统。

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Media;namespace SnakeGame
{public partial class MainForm : Form{// 游戏常量private const int GridSize = 20;private const int GameWidth = 30;private const int GameHeight = 20;private const int InitialSpeed = 150;// 游戏状态private List<Point> snake = new List<Point>();private Point food;private Direction currentDirection = Direction.Right;private Direction nextDirection = Direction.Right;private int score = 0;private bool gameRunning = false;private int gameSpeed;private Random random = new Random();private SoundPlayer eatSound;private SoundPlayer gameOverSound;// 方向枚举private enum Direction{Up, Down, Left, Right}public MainForm(){InitializeComponent();InitializeGame();InitializeSounds();this.DoubleBuffered = true; // 减少闪烁this.KeyPreview = true; // 捕获键盘事件}private void InitializeGame(){// 设置游戏区域大小gamePanel.Width = GameWidth * GridSize;gamePanel.Height = GameHeight * GridSize;// 初始化蛇身snake.Clear();snake.Add(new Point(5, 10)); // 蛇头snake.Add(new Point(4, 10));snake.Add(new Point(3, 10));// 生成食物GenerateFood();// 重置分数score = 0;lblScore.Text = $"分数: {score}";// 设置游戏速度gameSpeed = InitialSpeed;gameTimer.Interval = gameSpeed;}private void InitializeSounds(){// 使用系统内置声音eatSound = new SoundPlayer(System.Media.SystemSounds.Asterisk.ToString());gameOverSound = new SoundPlayer(System.Media.SystemSounds.Hand.ToString());}private void GenerateFood(){// 随机生成食物位置do{food = new Point(random.Next(0, GameWidth),random.Next(0, GameHeight));} while (snake.Contains(food)); // 确保食物不在蛇身上}private void StartGame(){InitializeGame();gameRunning = true;currentDirection = Direction.Right;nextDirection = Direction.Right;gameTimer.Start();btnStart.Enabled = false;}private void GameOver(){gameRunning = false;gameTimer.Stop();gameOverSound.Play();MessageBox.Show($"游戏结束!\n最终分数: {score}", "贪吃蛇游戏", MessageBoxButtons.OK, MessageBoxIcon.Information);btnStart.Enabled = true;}private void MoveSnake(){if (!gameRunning) return;// 更新方向currentDirection = nextDirection;// 计算新的头部位置Point newHead = snake[0];switch (currentDirection){case Direction.Up:newHead.Y--;break;case Direction.Down:newHead.Y++;break;case Direction.Left:newHead.X--;break;case Direction.Right:newHead.X++;break;}// 检查碰撞if (CheckCollision(newHead)){GameOver();return;}// 添加新头部snake.Insert(0, newHead);// 检查是否吃到食物if (newHead == food){score += 10;lblScore.Text = $"分数: {score}";eatSound.Play();// 每50分增加速度if (score % 50 == 0 && gameSpeed > 50){gameSpeed -= 20;gameTimer.Interval = gameSpeed;}GenerateFood();}else{// 移除尾部snake.RemoveAt(snake.Count - 1);}// 重绘游戏区域gamePanel.Invalidate();}private bool CheckCollision(Point head){// 检查是否撞墙if (head.X < 0 || head.X >= GameWidth || head.Y < 0 || head.Y >= GameHeight)return true;// 检查是否撞到自己(跳过头部)for (int i = 1; i < snake.Count; i++){if (head == snake[i])return true;}return false;}private void gamePanel_Paint(object sender, PaintEventArgs e){Graphics g = e.Graphics;g.Clear(Color.Black);// 绘制网格using (Pen gridPen = new Pen(Color.FromArgb(30, 30, 30))){for (int x = 0; x <= GameWidth; x++){g.DrawLine(gridPen, x * GridSize, 0, x * GridSize, GameHeight * GridSize);}for (int y = 0; y <= GameHeight; y++){g.DrawLine(gridPen, 0, y * GridSize, GameWidth * GridSize, y * GridSize);}}// 绘制食物g.FillEllipse(Brushes.Red, food.X * GridSize + 1, food.Y * GridSize + 1, GridSize - 2, GridSize - 2);// 绘制蛇for (int i = 0; i < snake.Count; i++){Color segmentColor;if (i == 0) // 蛇头{segmentColor = Color.FromArgb(0, 192, 0); // 亮绿色}else{// 蛇身渐变double ratio = (double)i / snake.Count;int green = (int)(192 * (1 - ratio * 0.5));segmentColor = Color.FromArgb(0, green, 0);}using (Brush segmentBrush = new SolidBrush(segmentColor)){g.FillRectangle(segmentBrush, snake[i].X * GridSize + 1, snake[i].Y * GridSize + 1, GridSize - 2, GridSize - 2);}// 绘制蛇头眼睛if (i == 0){int eyeSize = GridSize / 5;int offset = GridSize / 3;int eyeX = snake[0].X * GridSize + offset;int eyeY = snake[0].Y * GridSize + offset;// 根据方向调整眼睛位置switch (currentDirection){case Direction.Right:eyeX = snake[0].X * GridSize + GridSize - offset - eyeSize;eyeY = snake[0].Y * GridSize + offset;break;case Direction.Left:eyeX = snake[0].X * GridSize + offset;eyeY = snake[0].Y * GridSize + offset;break;case Direction.Up:eyeX = snake[0].X * GridSize + offset;eyeY = snake[0].Y * GridSize + offset;break;case Direction.Down:eyeX = snake[0].X * GridSize + offset;eyeY = snake[0].Y * GridSize + GridSize - offset - eyeSize;break;}g.FillEllipse(Brushes.White, eyeX, eyeY, eyeSize, eyeSize);}}}private void MainForm_KeyDown(object sender, KeyEventArgs e){if (!gameRunning) return;// 处理方向键输入switch (e.KeyCode){case Keys.Up:if (currentDirection != Direction.Down)nextDirection = Direction.Up;break;case Keys.Down:if (currentDirection != Direction.Up)nextDirection = Direction.Down;break;case Keys.Left:if (currentDirection != Direction.Right)nextDirection = Direction.Left;break;case Keys.Right:if (currentDirection != Direction.Left)nextDirection = Direction.Right;break;}}private void btnStart_Click(object sender, EventArgs e){StartGame();}private void gameTimer_Tick(object sender, EventArgs e){MoveSnake();}private void btnExit_Click(object sender, EventArgs e){this.Close();}}
}

设计说明

这个贪吃蛇游戏包含以下功能:

  1. 游戏核心机制

    • 蛇的移动和控制(使用方向键)
    • 食物生成(随机位置,避免出现在蛇身上)
    • 碰撞检测(墙壁和自身)
    • 得分系统(每吃一个食物得10分)
  2. 游戏特性

    • 难度递增(每50分增加蛇的移动速度)
    • 蛇身渐变颜色(从头部到尾部颜色渐变)
    • 蛇头有眼睛,方向指示清晰
    • 音效反馈(吃到食物和游戏结束)
  3. 用户界面

    • 游戏区域网格
    • 分数显示
    • 开始/退出按钮
    • 游戏结束提示
  4. 技术实现

    • 使用Windows Forms进行渲染
    • 双缓冲技术减少闪烁
    • 定时器控制游戏循环
    • 键盘事件处理

如何运行

  1. 在Visual Studio中创建新的Windows Forms项目

  2. 将上面的代码复制到项目中

  3. 在窗体设计器中添加以下控件:

    • 一个Panel(命名为gamePanel)
    • 两个Button(命名为btnStart和btnExit)
    • 一个Label(命名为lblScore)
    • 一个Timer(命名为gameTimer)
  4. 运行程序,点击"开始游戏"按钮即可

游戏操作指南

  • 使用方向键(上、下、左、右)控制蛇的移动方向
  • 吃到红色食物可以增加蛇的长度和得分
  • 避免撞到墙壁或自己的身体
  • 每得50分,蛇的移动速度会增加

参考源码 C# 贪吃蛇 youwenfan.com/contentcsc/92585.html

这个实现包含了贪吃蛇游戏的所有经典元素,并添加了一些视觉和听觉反馈增强游戏体验。

http://www.dtcms.com/a/331530.html

相关文章:

  • js加密逆向
  • Chrome插件开发实战:从零开发高效Chrome插件,提升浏览器生产力
  • 通过 USB 配置闭环驱动器——易格斯igus
  • glTF-教程/glb-教程
  • tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
  • AI硬件小众赛道崛起:垂直场景的价值重构与增长密码。
  • Java高级流
  • 公链开发竞争白热化:如何设计下一代高性能、可扩展的区块链基础设施?
  • 云手机的存储功能怎么样?
  • 一次 Unity ↔ Android 基于 RSA‑OAEP 的互通踩坑记
  • Android ADB 常用指令全解析
  • ADB服务端调试
  • markdown格式中table表格不生效,没有编译的原因
  • Mybatis Plus 分页插件报错`GOLDILOCKS`
  • 视频号主页的企业信息如何设置?
  • 深入了解linux系统—— 线程概念
  • Fiddler抓包
  • nginx --ssl证书生成mkcert
  • PCB爆板产生的原因有哪些?如何预防?
  • 第三十一天(系统io)
  • Qwen2-VL-2B 轻量化部署实战:数据集构建、LoRA微调、GPTQ量化与vLLM加速
  • 归并排序专栏
  • 机器学习基础讲解
  • Java -- HashSet的全面说明-Map接口的常用方法-遍历方法
  • feed-forward系列工作集合与跟进(vggt以后)
  • 第二十三天:求逆序对
  • Day54 Java面向对象08 继承
  • 附:日期类Date的实现
  • Pytorch在FSDP模型中使用EMA
  • Leetcode_1780.判断一个数字是否可以表示成三的幂的和