C#控制台实现贪吃蛇完整案例代码
以下内容来自ChatGPT,稍作更改。
using System;
using System.Collections.Generic;
using System.Threading;
using static System.Net.Mime.MediaTypeNames;
namespace SnakeGame
{
internal class Program
{
private static void Main(string[] args)
{
Console.WindowHeight = 30;
Console.WindowWidth = 30;
Console.BufferHeight = 30;
Console.BufferWidth = 30;
Point p = new Point(4, 5, '*');
Snake snake = new Snake(p, 4, Direction.RIGHT);
snake.Draw();
FoodCreator foodCreator = new FoodCreator(30, 30, '$');
Point food = foodCreator.CreateFood();
food.Draw();
while (true)
{
if (snake.Eat(food))
{
food = foodCreator.CreateFood();
food.Draw();
}
else
{
snake.Move();
}
Thread.Sleep(100);
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey();
snake.HandleKey(key.Key);
}
}
}
}
internal class Point
{
public int x;
public int y;
public char sym;
public Point(int x, int y, char sym)
{
this.x = x;
this.y = y;
this.sym = sym;
}
public void Draw()
{
try
{
Console.SetCursorPosition(x, y);
}
catch (Exception)
{
Console.WriteLine("游戏结束");
throw;
}
Console.Write(sym);
}
public void Clear()
{
sym = ' ';
Draw();
}
}
internal class Snake
{
public List<Point> body;
public int length;
public Direction direction;
public Snake(Point tail, int length, Direction direction)
{
body = new List<Point>();
this.length = length;
this.direction = direction;
for (int i = 0; i < length; i++)
{
Point p = new Point(tail.x - i, tail.y, tail.sym);
body.Add(p);
}
}
public void Move()
{
Point tail = body[body.Count - 1];
body.Remove(tail);
Point head = GetNextPoint();
body.Insert(0, head);
tail.Clear();
head.Draw();
}
public Point GetNextPoint()
{
Point head = body[0];
Point nextPoint = new Point(head.x, head.y, head.sym);
switch (direction)
{
case Direction.LEFT:
nextPoint.x--;
break;
case Direction.RIGHT:
nextPoint.x++;
break;
case Direction.UP:
nextPoint.y--;
break;
case Direction.DOWN:
nextPoint.y++;
break;
}
return nextPoint;
}
public void HandleKey(ConsoleKey key)
{
switch (key)
{
case ConsoleKey.LeftArrow:
direction = Direction.LEFT;
break;
case ConsoleKey.RightArrow:
direction = Direction.RIGHT;
break;
case ConsoleKey.UpArrow:
direction = Direction.UP;
break;
case ConsoleKey.DownArrow:
direction = Direction.DOWN;
break;
}
}
public bool Eat(Point food)
{
Point head = GetNextPoint();
if (head.x == food.x && head.y == food.y)
{
food.sym = head.sym;
body.Insert(0, food);
length++;
return true;
}
else
{
return false;
}
}
public void Draw()
{
foreach (Point p in body)
{
p.Draw();
}
}
}
internal class FoodCreator
{
private int mapWidht;
private int mapHeight;
private char sym;
private Random random = new Random();
public FoodCreator(int mapWidht, int mapHeight, char sym)
{
this.mapWidht = mapWidht;
this.mapHeight = mapHeight;
this.sym = sym;
}
public Point CreateFood()
{
int x = random.Next(2, mapWidht - 2);
int y = random.Next(2, mapHeight - 2);
return new Point(x, y, sym);
}
}
internal enum Direction
{
LEFT,
RIGHT,
UP,
DOWN
}
}