C#小游戏代码至少100行
时间: 2023-07-12 09:32:23 浏览: 44
以下是一个基于Windows Forms的C#小游戏——“贪吃蛇”的代码示例,共计超过100行:
```csharp
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace SnakeGame
{
public partial class SnakeForm : Form
{
private const int GridSize = 20;
private const int MaxX = 40;
private const int MaxY = 25;
private readonly Timer _gameTimer = new Timer();
private readonly Random _random = new Random();
private readonly List<Point> _snake = new List<Point>();
private Point _food;
private Direction _direction;
private bool _gameOver;
public SnakeForm()
{
InitializeComponent();
InitializeGame();
}
private void InitializeGame()
{
_direction = Direction.Right;
_gameOver = false;
_snake.Clear();
_snake.Add(new Point(10, 10));
_snake.Add(new Point(9, 10));
_snake.Add(new Point(8, 10));
PlaceFood();
_gameTimer.Interval = 100;
_gameTimer.Tick += GameTimer_Tick;
_gameTimer.Start();
}
private void PlaceFood()
{
_food = new Point(_random.Next(MaxX), _random.Next(MaxY));
while (_snake.Any(p => p == _food))
{
_food = new Point(_random.Next(MaxX), _random.Next(MaxY));
}
}
private void GameTimer_Tick(object sender, EventArgs e)
{
if (_gameOver)
{
_gameTimer.Stop();
MessageBox.Show("游戏结束!");
return;
}
MoveSnake();
if (_snake[0] == _food)
{
_snake.Add(_snake[_snake.Count - 1]);
PlaceFood();
}
canvas.Invalidate();
}
private void MoveSnake()
{
var head = _snake[0];
switch (_direction)
{
case Direction.Up:
head.Y--;
break;
case Direction.Down:
head.Y++;
break;
case Direction.Left:
head.X--;
break;
case Direction.Right:
head.X++;
break;
}
if (head.X < 0 || head.X >= MaxX || head.Y < 0 || head.Y >= MaxY)
{
_gameOver = true;
}
for (var i = 1; i < _snake.Count; i++)
{
if (_snake[i] == head)
{
_gameOver = true;
break;
}
}
_snake.Insert(0, head);
_snake.RemoveAt(_snake.Count - 1);
}
private void SnakeForm_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
if (_direction != Direction.Down)
{
_direction = Direction.Up;
}
break;
case Keys.Down:
if (_direction != Direction.Up)
{
_direction = Direction.Down;
}
break;
case Keys.Left:
if (_direction != Direction.Right)
{
_direction = Direction.Left;
}
break;
case Keys.Right:
if (_direction != Direction.Left)
{
_direction = Direction.Right;
}
break;
}
}
private void canvas_Paint(object sender, PaintEventArgs e)
{
for (var x = 0; x < MaxX; x++)
{
for (var y = 0; y < MaxY; y++)
{
var rect = new Rectangle(x * GridSize, y * GridSize, GridSize, GridSize);
if (_snake.Any(p => p.X == x && p.Y == y))
{
e.Graphics.FillRectangle(Brushes.Green, rect);
}
else if (_food.X == x && _food.Y == y)
{
e.Graphics.FillRectangle(Brushes.Red, rect);
}
else
{
e.Graphics.FillRectangle(Brushes.Black, rect);
}
}
}
}
}
enum Direction
{
Up,
Down,
Left,
Right
}
}
```
这个程序实现了一个简单的“贪吃蛇”游戏。玩家通过控制蛇的运动方向来使其吃到食物并不断增长,直到碰到边界或自己的身体为止。游戏使用了Windows Forms作为界面,使用了定时器来控制游戏循环,使用了随机数生成食物的位置,使用了键盘事件来控制蛇的运动方向,使用了画布来绘制游戏画面。