2.C#-贪吃蛇

做出来的结果就是这样:

20240411-233807

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C#编写的简单贪吃蛇游戏代码,仅供参考: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace ConsoleApp1 { class Program { static int width = 20; static int height = 20; static int score = 0; static int[,] grid = new int[width, height]; static List<Point> snake = new List<Point>(); static Point food = new Point(); static Random rnd = new Random(); static void Main(string[] args) { InitGame(); while (true) { DrawGrid(); DrawSnake(); DrawFood(); MoveSnake(); if (CheckCollision()) { Console.Clear(); Console.WriteLine("Game over!"); Console.WriteLine("Score: " + score); Console.ReadKey(); break; } Thread.Sleep(100); } } static void InitGame() { snake.Add(new Point(width / 2, height / 2)); grid[snake[0].x, snake[0].y] = 1; food = GenerateFood(); } static void DrawGrid() { Console.Clear(); for (int i = 0; i < height + 2; i++) { for (int j = 0; j < width + 2; j++) { if (i == 0 || i == height + 1 || j == 0 || j == width + 1) Console.Write("#"); else Console.Write(" "); } Console.WriteLine(); } Console.WriteLine("Score: " + score); } static void DrawSnake() { foreach (Point p in snake) { Console.SetCursorPosition(p.x + 1, p.y + 1); Console.Write("*"); } } static void DrawFood() { Console.SetCursorPosition(food.x + 1, food.y + 1); Console.Write("@"); } static void MoveSnake() { Point head = new Point(snake[0].x, snake[0].y); switch (Console.ReadKey().Key) { case ConsoleKey.LeftArrow: head.x--; break; case ConsoleKey.RightArrow: head.x++; break; case ConsoleKey.UpArrow: head.y--; break; case ConsoleKey.DownArrow: head.y++; break; } snake.Insert(0, head); if (head.x == food.x && head.y == food.y) { score++; food = GenerateFood(); } else { snake.RemoveAt(snake.Count - 1); } } static bool CheckCollision() { if (snake[0].x == 0 || snake[0].x == width + 1 || snake[0].y == 0 || snake[0].y == height + 1) return true; for (int i = 1; i < snake.Count; i++) { if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) return true; } return false; } static Point GenerateFood() { Point p = new Point(rnd.Next(1, width + 1), rnd.Next(1, height + 1)); while (grid[p.x, p.y] == 1) { p.x = rnd.Next(1, width + 1); p.y = rnd.Next(1, height + 1); } return p; } class Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值