你好你作为一个专业的程序员帮我用csharp写一个贪吃蛇的小游戏
好的,以下是一个简单的贪吃蛇游戏的C#代码:
using System;
using System.Collections.Generic;
class SnakeGame
{
static void Main(string[] args)
{
// 定义游戏界面的大小
int width = 20;
int height = 10;
// 初始化贪吃蛇的位置和方向
List<int> snakeX = new List<int>() { 2, 1, 0 };
List<int> snakeY = new List<int>() { 0, 0, 0 };
int direction = 1; // 0:向上 1:向右 2:向下 3:向左
// 初始化食物的位置
int foodX = 10;
int foodY = 5;
// 游戏循环
while (true)
{
// 显示游戏界面
Console.Clear();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (x == foodX && y == foodY)
{
Console.Write("●");
}
else if (snakeX.Contains(x) && snakeY[snakeX.IndexOf(x)] == y)
{
Console.Write("■");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
// 获取用户输入
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.UpArrow && direction != 2)
{
direction = 0;
}
else if (keyInfo.Key == ConsoleKey.RightArrow && direction != 3)
{
direction = 1;
}
else if (keyInfo.Key == ConsoleKey.DownArrow && direction != 0)
{
direction = 2;
}
else if (keyInfo.Key == ConsoleKey.LeftArrow && direction != 1)
{
direction = 3;
}
// 移动贪吃蛇
int headX = snakeX[0];
int headY = snakeY[0];
switch (direction)
{
case 0: // 向上
headY--;
break;
case 1: // 向右
headX++;
break;
case 2: // 向下
headY++;
break;
case 3: // 向左
headX--;
break;
}
snakeX.Insert(0, headX);
snakeY.Insert(0, headY);
if (headX == foodX && headY == foodY) // 如果吃到了食物
{
foodX = new Random().Next(width);
foodY = new Random().Next(height);
}
else // 如果没有吃到食物,尾部要移除
{
snakeX.RemoveAt(snakeX.Count - 1);
snakeY.RemoveAt(snakeY.Count - 1);
}
// 判断是否游戏结束
if (headX < 0 || headX >= width || headY < 0 || headY >= height || snakeX.IndexOf(headX) != 0)
{
Console.WriteLine("Game Over!");
break;
}
// 暂停一下,控制游戏速度
System.Threading.Thread.Sleep(100);
}
// 按任意键退出
Console.ReadKey();
}
}
运行结果如下:
●
■■■
按上下左右键可以控制贪吃蛇的方向,吃到食物可以加分,碰到墙或者自己的身体就游戏结束。
原文地址: https://www.cveoy.top/t/topic/bKuH 著作权归作者所有。请勿转载和采集!