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();
}
}
}
设计说明
这个贪吃蛇游戏包含以下功能:
游戏核心机制:
- 蛇的移动和控制(使用方向键)
- 食物生成(随机位置,避免出现在蛇身上)
- 碰撞检测(墙壁和自身)
- 得分系统(每吃一个食物得10分)
游戏特性:
- 难度递增(每50分增加蛇的移动速度)
- 蛇身渐变颜色(从头部到尾部颜色渐变)
- 蛇头有眼睛,方向指示清晰
- 音效反馈(吃到食物和游戏结束)
用户界面:
- 游戏区域网格
- 分数显示
- 开始/退出按钮
- 游戏结束提示
技术实现:
- 使用Windows Forms进行渲染
- 双缓冲技术减少闪烁
- 定时器控制游戏循环
- 键盘事件处理
如何运行
在Visual Studio中创建新的Windows Forms项目
将上面的代码复制到项目中
在窗体设计器中添加以下控件:
- 一个Panel(命名为gamePanel)
- 两个Button(命名为btnStart和btnExit)
- 一个Label(命名为lblScore)
- 一个Timer(命名为gameTimer)
运行程序,点击"开始游戏"按钮即可
游戏操作指南
- 使用方向键(上、下、左、右)控制蛇的移动方向
- 吃到红色食物可以增加蛇的长度和得分
- 避免撞到墙壁或自己的身体
- 每得50分,蛇的移动速度会增加
参考源码 C# 贪吃蛇 youwenfan.com/contentcsc/92585.html
这个实现包含了贪吃蛇游戏的所有经典元素,并添加了一些视觉和听觉反馈增强游戏体验。