写个Csharp贪吃蛇小游戏
时间: 2023-03-04 10:33:50 浏览: 45
以下是一个简单的 C# 贪吃蛇小游戏的示例代码,使用 WinForms 库来绘制游戏界面。请注意,这个示例代码并不完美,你可以自己进行更多的优化和改进。
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SnakeGame
{
public partial class MainForm : Form
{
private const int WIDTH = 20;
private const int HEIGHT = 20;
private const int GRID_SIZE = 20;
private const int SNAKE_START_LENGTH = 3;
private const int TIMER_INTERVAL = 100;
private Point _foodPosition;
private Point[] _snake;
private Direction _direction = Direction.Right;
private Timer _timer;
public MainForm()
{
InitializeComponent();
_snake = new Point[SNAKE_START_LENGTH];
_snake[0] = new Point(10, 10);
for (int i = 1; i < SNAKE_START_LENGTH; i++)
{
_snake[i] = new Point(_snake[i - 1].X - 1, _snake[i - 1].Y);
}
NewFoodPosition();
_timer = new Timer();
_timer.Interval = TIMER_INTERVAL;
_timer.Tick += OnTimerTick;
_timer.Start();
}
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && _direction != Direction.Down)
{
_direction = Direction.Up;
}
else if (e.KeyCode == Keys.Down && _direction != Direction.Up)
{
_direction = Direction.Down;
}
else if (e.KeyCode == Keys.Left && _direction != Direction.Right)
{
_direction = Direction.Left;
}
else if (e.KeyCode == Keys.Right && _direction != Direction.Left)
{
_direction = Direction.Right;
}
}
private void OnTimerTick(object sender, EventArgs e)
{
MoveSnake();
CheckCollision();
Refresh();
}
private void MoveSnake()
{
for (int i = _snake.Length - 1; i > 0; i--)
{
_snake[i] = _snake[i - 1];
}
switch (_direction)
{
case Direction.Up:
_snake[0] = new Point(_snake[0].X, _snake[0].Y - 1);
break;
case Direction.Down:
_snake[0] = new Point(_snake[0].X, _snake[0].Y + 1);
break;
case Direction.Left:
_snake[0] = new Point(_snake[0].X - 1, _snake[0].Y);
break;
case Direction.Right:
_snake[0] = new Point(_snake[0].X + 1, _snake[0].Y);
break;
}
}
private void CheckCollision()
{
if (_snake[0].X < 0 || _snake[0].X >= WIDTH ||
_snake[0].Y < 0 || _snake[0].Y >= HEIGHT)
{
GameOver();
return;
}
for (int i = 1; i < _snake.Length; i++)
{
if (_snake[i] == _snake[0])
{
GameOver();
return;
}
}
if (_snake[0] == _foodPosition)
{
Array.Resize