当前位置: 首页 > news >正文

C#编程:贪吃蛇游戏

贪吃蛇

  • game.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SnakeGame
{public class Game{private const int Width = 40;private const int Height = 20;private const char SnakeChar = '■';private const char FoodChar = '★';private const char WallChar = '█';private List<Position> snake;private Position food;private Direction direction;private bool gameOver;private int score;private Random random;public Game(){snake = new List<Position>();random = new Random();InitializeGame();}private void InitializeGame(){// 初始化蛇的位置(从中心开始)snake.Clear();snake.Add(new Position(Width / 2, Height / 2));snake.Add(new Position(Width / 2 - 1, Height / 2));snake.Add(new Position(Width / 2 - 2, Height / 2));direction = Direction.Right;gameOver = false;score = 0;GenerateFood();}public void Start(){Console.CursorVisible = false;Console.Clear();while (!gameOver){if (Console.KeyAvailable){HandleInput();}MoveSnake();CheckCollision();Draw();Thread.Sleep(150); // 控制游戏速度}GameOver();}private void HandleInput(){var key = Console.ReadKey(true).Key;switch (key){case ConsoleKey.UpArrow:if (direction != Direction.Down)direction = Direction.Up;break;case ConsoleKey.DownArrow:if (direction != Direction.Up)direction = Direction.Down;break;case ConsoleKey.LeftArrow:if (direction != Direction.Right)direction = Direction.Left;break;case ConsoleKey.RightArrow:if (direction != Direction.Left)direction = Direction.Right;break;case ConsoleKey.Escape:gameOver = true;break;}}private void MoveSnake(){Position head = snake.First();Position newHead = new Position(head.X, head.Y);switch (direction){case Direction.Up:newHead.Y--;break;case Direction.Down:newHead.Y++;break;case Direction.Left:newHead.X--;break;case Direction.Right:newHead.X++;break;}snake.Insert(0, newHead);// 检查是否吃到食物if (newHead.X == food.X && newHead.Y == food.Y){score += 10;GenerateFood();}else{snake.RemoveAt(snake.Count - 1);}}private void CheckCollision(){Position head = snake.First();// 检查是否撞墙if (head.X < 0 || head.X >= Width || head.Y < 0 || head.Y >= Height){gameOver = true;return;}// 检查是否撞到自己for (int i = 1; i < snake.Count; i++){if (head.X == snake[i].X && head.Y == snake[i].Y){gameOver = true;return;}}}private void GenerateFood(){do{food = new Position(random.Next(0, Width), random.Next(0, Height));} while (snake.Any(p => p.X == food.X && p.Y == food.Y));}private void Draw(){Console.SetCursorPosition(0, 0);// 绘制上边界Console.WriteLine(new string(WallChar, Width + 2));// 绘制游戏区域for (int y = 0; y < Height; y++){Console.Write(WallChar);for (int x = 0; x < Width; x++){if (snake.Any(p => p.X == x && p.Y == y)){Console.Write(SnakeChar);}else if (food.X == x && food.Y == y){Console.Write(FoodChar);}else{Console.Write(' ');}}Console.WriteLine(WallChar);}// 绘制下边界Console.WriteLine(new string(WallChar, Width + 2));// 显示分数Console.WriteLine($"分数: {score}");Console.WriteLine($"蛇的长度: {snake.Count}");Console.WriteLine("按ESC键退出游戏");}private void GameOver(){Console.Clear();Console.WriteLine("游戏结束!");Console.WriteLine($"最终分数: {score}");Console.WriteLine($"蛇的最终长度: {snake.Count}");Console.WriteLine("按任意键退出...");Console.ReadKey();}}
}
  • PosiAndDire.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SnakeGame
{public class Position{public int X { get; set; }public int Y { get; set; }public Position(int x, int y){X = x;Y = y;}}public enum Direction{Up,Down,Left,Right}}
  • Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;namespace SnakeGame
{class Program{static void Main(string[] args){Console.WriteLine("欢迎来到贪吃蛇游戏!");Console.WriteLine("使用方向键控制蛇的移动");Console.WriteLine("按任意键开始游戏...");Console.ReadKey();Game game = new Game();game.Start();}}
}
  • Project
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><Platforms>AnyCPU;x86</Platforms></PropertyGroup></Project>
  • readme
# 贪吃蛇游戏 (Snake Game)一个用C#编写的控制台版贪吃蛇游戏。## 功能特点- 完整的贪吃蛇游戏逻辑
- 使用方向键控制蛇的移动
- 实时分数显示
- 碰撞检测(墙壁和自身)
- 食物随机生成
- 游戏结束统计## 游戏控制- **方向键**: 控制蛇的移动方向
- **ESC键**: 退出游戏## 如何运行### 方法1: 使用 .NET CLI1. 确保您已安装 .NET 6.0 或更高版本
2. 在项目目录中打开命令行
3. 运行以下命令:```bash
# 编译项目
dotnet build# 运行游戏
dotnet run
### 方法2: 使用 Visual Studio1. 打开 `SnakeGame.csproj` 文件
2. 按 F5 运行游戏## 游戏规则1. 使用方向键控制蛇的移动
2. 吃到食物(★)可以增加分数和蛇的长度
3. 避免撞到墙壁或蛇的身体
4. 游戏会一直进行直到撞墙或撞到自己## 系统要求- .NET 6.0 或更高版本
- Windows/Linux/macOS 操作系统
- 支持控制台应用程序的终端## 游戏截图游戏界面包含:
- 边界墙(█)
- 蛇身(■)
- 食物(★)
- 实时分数显示
- 蛇的长度显示享受游戏吧!
http://www.dtcms.com/a/352222.html

相关文章:

  • 使用linux+javascript+html+mysql+nodejs+npm+express等构建信息资料采集系统
  • FreeRTOS 同步互斥与任务协作 学习笔记
  • 【Protues仿真】定时器
  • 对讲联动电梯门禁系统通过深度集成对讲、梯控、身份认证三大模块,在提升便捷性的同时,以“权限后置发放+电梯状态闭环检测“为核心,实现安全性与可靠性的双重突破。
  • 解决VSCode无法下载服务器端 Server问的题
  • 当 C++ 用于嵌入式开发:优点和缺点
  • .gitignore 文件相关使用配置
  • 【Redis】安装和基础命令
  • 十、Java面向对象编程入门指南:继承与多态
  • 利用 OpenTelemetry 建设尾部采样
  • 大模型全栈学习路线:4 - 6 个月从入门到实战,打通技术与业务闭环
  • [灵动微电子 霍尔FOC MM32BIN560C]从引脚到应用
  • 《黑客帝国》解构:白帽黑客的极客思维宇宙
  • vue3写一个简单的时间轴组件
  • 【python】python利用QQ邮箱SMTP发送邮件
  • k8s pod resources: {} 设置的含义
  • 支持向量机(第二十九节课内容总结)
  • TensorFlow 面试题及详细答案 120道(61-70)-- 高级特性与工具
  • 如何在项目中集成XXL-JOB
  • uniapp 引入使用u-view 完整步骤,u-view 样式不生效
  • 重复文件删除查找工具 Duplicate Files Search Link v10.7.0
  • 【深度学习】Transformer 注意力机制与 LoRA target_modules 详解
  • 如何安装 VS2019 和 .NET Core SDK 2.2.301(winx64)?完整操作步骤(附安装包下载)
  • 基于YOLOv11训练无人机视角Visdrone2019数据集
  • 区块链技术探索与应用:从密码学奇迹到产业变革引擎
  • 从入门到理解:支持向量机的核心原理与实战思路
  • 计数组合学7.21(有界部分大小的平面分拆)
  • 车载铁框矫平机:一辆“会熨衣服”的工程车
  • 高性能异步任务编排框架:Gobrs-Async
  • 【项目】深房数据通——深圳房价可视化系统