写一下贪吃蛇应用Cshap代码
时间: 2023-03-05 09:24:47 浏览: 176
用C#编程语言编写的简单贪吃蛇程序
好的,以下是一个简单的贪吃蛇应用的C#代码,仅供参考:
```csharp
using System;
using System.Collections.Generic;
namespace SnakeGame
{
class Program
{
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.SetWindowSize(40, 20);
Console.SetBufferSize(40, 20);
// 初始化贪吃蛇和食物
Snake snake = new Snake();
Food food = new Food(snake);
while (true)
{
// 显示贪吃蛇和食物
snake.Draw();
food.Draw();
// 检测用户输入,控制贪吃蛇移动
if (Console.KeyAvailable)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.LeftArrow)
snake.Move(Direction.Left);
else if (keyInfo.Key == ConsoleKey.RightArrow)
snake.Move(Direction.Right);
else if (keyInfo.Key == ConsoleKey.UpArrow)
snake.Move(Direction.Up);
else if (keyInfo.Key == ConsoleKey.DownArrow)
snake.Move(Direction.Down);
}
// 更新贪吃蛇和食物状态
snake.Update();
food.Update();
// 判断游戏结束条件
if (snake.IsDead())
{
Console.SetCursorPosition(15, 10);
Console.Write("Game Over!");
Console.ReadKey();
break;
}
// 清除屏幕,准备下一帧
Console.Clear();
}
}
}
// 贪吃蛇类
class Snake
{
private List<Point> body; // 贪吃蛇身体
private Point head; // 贪吃蛇头部
private Direction direction; // 贪吃蛇移动方向
public Snake()
{
// 初始化贪吃蛇
body = new List<Point>();
body.Add(new Point(20, 10));
body.Add(new Point(21, 10));
body.Add(new Point(22, 10));
head = body[body.Count - 1];
direction = Direction.Right;
}
// 绘制贪吃蛇
public void Draw()
{
foreach (Point p in body)
{
Console.SetCursorPosition(p.x, p.y);
Console.Write("*");
}
}
// 更新贪吃蛇状态
public void Update()
{
// 移动身体
for (int i = 0; i < body.Count - 1; i++)
{
body[i].x = body[i + 1].x;
body[i].y = body[i + 1].y;
}
// 移动头部
switch (direction)
{
case Direction.Left:
head.x--;
break;
case Direction.Right:
head.x++;
break;
case Direction.Up:
head.y--;
break;
case Direction.Down:
head.y++;
break;
}
// 检测碰撞
if (IsCollidingWithSelf())
Kill();
// 检测边界
if (head.x < 0 || head.x >= 40 || head.y < 0
阅读全文