用c#写一个贪吃蛇代码
时间: 2023-08-02 15:21:54 浏览: 66
好的,以下是一个简单的 C# 贪吃蛇代码示例,您可以参考一下:
```csharp
using System;
using System.Collections.Generic;
namespace SnakeGame
{
class Program
{
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.SetWindowSize(50, 25);
// 初始化贪吃蛇
Snake snake = new Snake(20, 10);
// 初始化食物
Food food = new Food();
while (true)
{
// 绘制贪吃蛇和食物
Console.Clear();
snake.Draw();
food.Draw();
// 移动贪吃蛇和判断是否吃到食物
if (snake.Move(food))
{
food = new Food();
}
// 判断是否游戏结束
if (snake.IsDead())
{
Console.Clear();
Console.WriteLine("Game over!");
break;
}
// 控制游戏速度
System.Threading.Thread.Sleep(100);
}
}
}
// 贪吃蛇类
class Snake
{
private List<Point> body;
private Direction direction;
public Snake(int x, int y)
{
body = new List<Point>();
body.Add(new Point(x, y));
direction = Direction.Right;
}
public void Draw()
{
Console.ForegroundColor = ConsoleColor.Green;
foreach (Point point in body)
{
Console.SetCursorPosition(point.X, point.Y);
Console.Write("*");
}
}
public bool Move(Food food)
{
// 判断贪吃蛇是否吃到食物
if (body[0].X == food.X && body[0].Y == food.Y)
{
body.Insert(0, new Point(food.X, food.Y));
return true;
}
// 移动贪吃蛇
for (int i = body.Count - 1; i > 0; i--)
{
body[i].X = body[i - 1].X;
body[i].Y = body[i - 1].Y;
}
switch (direction)
{
case Direction.Up:
body[0].Y--;
break;
case Direction.Down:
body[0].Y++;
break;
case Direction.Left:
body[0].X--;
break;
case Direction.Right:
body[0].X++;
break;
}
// 判断贪吃蛇是否撞墙或撞到自己
for (int i = 1; i < body.Count; i++)
{
if (body[0].X == body[i].X && body[0].Y == body[i].Y)
{
return false;
}
}
if (body[0].X < 0 || body[0].X >= Console.WindowWidth ||
body[0].Y < 0 || body[0].Y >= Console.WindowHeight)
{
return false;
}
return true;
}
public bool IsDead()
{
return !Move(new Food());
}
public void SetDirection(Direction dir)
{
if ((int)dir % 2 != (int)direction % 2)
{
direction = dir;
}
}
}
// 食物类
class Food
{
public int X { get; private set; }
public int Y { get; private set; }
public Food()
{
Random random = new Random();
X = random.Next(Console.WindowWidth);
Y = random.Next(Console.WindowHeight);
}
public void Draw()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.SetCursorPosition(X, Y);
Console.Write("@");
}
}
// 坐标点类
class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
}
// 方向枚举类
enum Direction
{
Up,
Down,
Left,
Right
}
}
```
希望这个示例能够帮到您!
阅读全文