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

从零开发游戏需要学习的c#模块,第二十章(2D 敌人与战斗触发)

本节课我们要学习的内容在地图上随机生成红色敌人玩家碰到敌人后进入战斗模式战斗胜利后敌人消失获得分数屏幕显示敌人数量using Microsoft.Xna.Framework;using Microsoft.Xna.Framework.Graphics;using Microsoft.Xna.Framework.Input;using System;using System.Collections.Generic;using System.IO;using FontStashSharp;namespace MY_FIRST_GAME{// ★ 游戏状态枚举public enum GameState{Exploring, // 探索模式Battling // 战斗模式}public class Game1 : Game{private GraphicsDeviceManager _graphics;private SpriteBatch _spriteBatch;// 玩家private Texture2D playerTexture;private Vector2 playerPosition;private float playerSpeed 200f;private int playerHp 100;private int playerMaxHp 100;private int playerAttack 15;// 金币private Texture2D coinTexture;private ListVector2 coins;private Random rng;private int score;// ★ 敌人private Texture2D enemyTexture;private ListEnemyData enemies;// 字体private SpriteFontBase font;// ★ 游戏状态private GameState state GameState.Exploring;// ★ 战斗相关private EnemyData? currentEnemy;private string battleMessage ;private float battleTimer 0f;private bool playerTurn true;public Game1(){_graphics new GraphicsDeviceManager(this);Content.RootDirectory Content;IsMouseVisible true;}protected override void Initialize(){_graphics.PreferredBackBufferWidth 800;_graphics.PreferredBackBufferHeight 600;_graphics.ApplyChanges();playerPosition new Vector2(400, 300);rng new Random();coins new ListVector2();enemies new ListEnemyData();score 0;SpawnCoins(5);SpawnEnemies(3);base.Initialize();}protected override void LoadContent(){_spriteBatch new SpriteBatch(GraphicsDevice);// 玩家图片using var stream File.OpenRead(Content/player.png);playerTexture Texture2D.FromStream(GraphicsDevice, stream);// 金币纹理coinTexture new Texture2D(GraphicsDevice, 32, 32);Color[] coinData new Color[32 * 32];for (int i 0; i coinData.Length; i)coinData[i] Color.Gold;coinTexture.SetData(coinData);// ★ 敌人纹理红色方块 48x48enemyTexture new Texture2D(GraphicsDevice, 48, 48);Color[] enemyData new Color[48 * 48];for (int i 0; i enemyData.Length; i)enemyData[i] Color.Red;enemyTexture.SetData(enemyData);// 字体var fontSystem new FontSystem();fontSystem.AddFont(File.ReadAllBytes(Content/consola.ttf));font fontSystem.GetFont(18);}// ★ 敌人数据结构private class EnemyData{public Vector2 Position;public int Hp;public int MaxHp;public int Attack;public bool IsAlive;public string Name;public EnemyData(Vector2 pos, string name, int hp, int attack){Position pos;Name name;Hp hp;MaxHp hp;Attack attack;IsAlive true;}}private void SpawnCoins(int count){for (int i 0; i count; i){float x rng.Next(50, 750);float y rng.Next(50, 550);coins.Add(new Vector2(x, y));}}private void SpawnEnemies(int count){for (int i 0; i count; i){float x rng.Next(80, 720);float y rng.Next(80, 520);enemies.Add(new EnemyData(new Vector2(x, y),史莱姆 (i 1),30 rng.Next(0, 20),8 rng.Next(0, 6)));}}protected override void Update(GameTime gameTime){KeyboardState keyboard Keyboard.GetState();float deltaTime (float)gameTime.ElapsedGameTime.TotalSeconds;// ★ 根据游戏状态分发更新if (state GameState.Exploring)UpdateExploring(keyboard, deltaTime);else if (state GameState.Battling)UpdateBattling(keyboard, deltaTime);if (keyboard.IsKeyDown(Keys.Escape))Exit();base.Update(gameTime);}// ★ 探索模式更新private void UpdateExploring(KeyboardState keyboard, float deltaTime){float speed playerSpeed * deltaTime;if (keyboard.IsKeyDown(Keys.W) || keyboard.IsKeyDown(Keys.Up))playerPosition.Y - speed;if (keyboard.IsKeyDown(Keys.S) || keyboard.IsKeyDown(Keys.Down))playerPosition.Y speed;if (keyboard.IsKeyDown(Keys.A) || keyboard.IsKeyDown(Keys.Left))playerPosition.X - speed;if (keyboard.IsKeyDown(Keys.D) || keyboard.IsKeyDown(Keys.Right))playerPosition.X speed;playerPosition.X Math.Clamp(playerPosition.X, 32, 768);playerPosition.Y Math.Clamp(playerPosition.Y, 32, 568);CheckCoinCollision();CheckEnemyCollision();if (coins.Count 0) SpawnCoins(5);if (enemies.Count 0) SpawnEnemies(3);}// ★ 战斗模式更新private void UpdateBattling(KeyboardState keyboard, float deltaTime){if (currentEnemy null || !currentEnemy.IsAlive){EndBattle(true);return;}if (playerHp 0){EndBattle(false);return;}// 按空格攻击if (playerTurn keyboard.IsKeyDown(Keys.Space)){// 玩家攻击currentEnemy.Hp - playerAttack;battleMessage $你对 {currentEnemy.Name} 造成了 {playerAttack} 点伤害;playerTurn false;}// 敌人回合简单延迟if (!playerTurn){battleTimer deltaTime;if (battleTimer 0.8f){battleTimer 0f;// 敌人攻击playerHp - currentEnemy.Attack;battleMessage ${currentEnemy.Name} 对你造成了 {currentEnemy.Attack} 点伤害;playerTurn true;}}}// ★ 结束战斗private void EndBattle(bool playerWon){if (playerWon currentEnemy ! null){score 50;currentEnemy.IsAlive false;enemies.Remove(currentEnemy);}currentEnemy null;battleMessage ;battleTimer 0f;playerTurn true;state GameState.Exploring;}// ★ 敌人碰撞检测private void CheckEnemyCollision(){Rectangle playerRect new Rectangle((int)playerPosition.X - 32,(int)playerPosition.Y - 32,64, 64);for (int i enemies.Count - 1; i 0; i--){Rectangle enemyRect new Rectangle((int)enemies[i].Position.X - 24,(int)enemies[i].Position.Y - 24,48, 48);if (playerRect.Intersects(enemyRect)){// 进入战斗currentEnemy enemies[i];state GameState.Battling;battleMessage $遭遇了 {currentEnemy.Name}按 空格 攻击;playerTurn true;battleTimer 0f;break;}}}// 金币碰撞private void CheckCoinCollision(){Rectangle playerRect new Rectangle((int)playerPosition.X - 32,(int)playerPosition.Y - 32,64, 64);for (int i coins.Count - 1; i 0; i--){Rectangle coinRect new Rectangle((int)coins[i].X, (int)coins[i].Y, 32, 32);if (playerRect.Intersects(coinRect)){coins.RemoveAt(i);score 10;}}}protected override void Draw(GameTime gameTime){GraphicsDevice.Clear(Color.CornflowerBlue);_spriteBatch.Begin();// 画金币foreach (Vector2 coinPos in coins)_spriteBatch.Draw(coinTexture, coinPos, Color.White);// ★ 画敌人foreach (EnemyData enemy in enemies){_spriteBatch.Draw(enemyTexture,enemy.Position,null,Color.White,0f,new Vector2(24, 24),1f,SpriteEffects.None,0f);}// 画玩家_spriteBatch.Draw(playerTexture,playerPosition,null,Color.White,0f,new Vector2(playerTexture.Width / 2, playerTexture.Height / 2),1f,SpriteEffects.None,0f);// UI 文字_spriteBatch.DrawString(font, $分数{score}, new Vector2(10, 10), Color.White);_spriteBatch.DrawString(font, $金币{coins.Count}, new Vector2(10, 35), Color.Gold);_spriteBatch.DrawString(font, $敌人{enemies.Count}, new Vector2(10, 60), Color.Red);_spriteBatch.DrawString(font, $HP{playerHp}/{playerMaxHp}, new Vector2(10, 85), Color.LimeGreen);// ★ 战斗界面if (state GameState.Battling currentEnemy ! null){// 半透明背景Texture2D overlay new Texture2D(GraphicsDevice, 1, 1);overlay.SetData(new[] { new Color(0, 0, 0, 180) });_spriteBatch.Draw(overlay, new Rectangle(0, 250, 800, 100), Color.White);_spriteBatch.DrawString(font, $⚔️ {currentEnemy.Name}, new Vector2(20, 260), Color.Red);_spriteBatch.DrawString(font, $敌人HP{currentEnemy.Hp}/{currentEnemy.MaxHp}, new Vector2(20, 285), Color.White);_spriteBatch.DrawString(font, $你的HP{playerHp}/{playerMaxHp}, new Vector2(20, 310), Color.LimeGreen);_spriteBatch.DrawString(font, battleMessage, new Vector2(20, 335), Color.Yellow);}_spriteBatch.DrawString(font, WASD移动 | 靠近敌人战斗 | 战斗中按空格攻击, new Vector2(10, 570), Color.LightGray);_spriteBatch.End();base.Draw(gameTime);}}} 核心新知识1. 游戏状态机public enum GameState { Exploring, Battling } if (state GameState.Exploring) UpdateExploring(...); else if (state GameState.Battling) UpdateBattling(...);这就是你在设计模式课学的状态模式的实际应用。探索和战斗是两个完全独立的逻辑分支。2. 战斗触发if (playerRect.Intersects(enemyRect)) { currentEnemy enemies[i]; state GameState.Battling; }. 战斗流程玩家回合按空格键攻击敌人回合等待 0.8 秒后自动反击战斗结束敌人死亡或玩家死亡回到探索模式

相关文章:

从零开发游戏需要学习的c#模块,第二十章(2D 敌人与战斗触发)

本节课我们要学习的内容在地图上随机生成红色敌人玩家碰到敌人后,进入战斗模式战斗胜利后敌人消失,获得分数屏幕显示敌人数量using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Syst…...

AI 时代的平台工程

两个月前,正是我 Aha moment 不断,多巴胺爆炸的时刻,每天都会记录下很多灵感和想法,准备在未来写成文章,或者开发成工具。其中有一条是这样的:AI 时代的平台工程(CLISkillMCP,可访问…...

加印了!谢谢大家,这本不讲空话的“AI落地说明书”为什么能卖爆?

想不到有一天我也会有“书竟然卖爆了”的感觉,机械工业出版社要紧急加印才能供上货的那种。特别感谢机械工业出版社的朋友们从策划到发布的全程细致高效的工作,感谢微软中国首席技术官韦青老师亲临发布会现场为我们共同的理想发声,更要感谢各…...

MongoDB 连接详解

MongoDB 连接详解 引言 MongoDB 是一款强大的 NoSQL 数据库,以其灵活的文档存储和强大的扩展性而备受青睐。在开发过程中,与 MongoDB 的连接是至关重要的第一步。本文将详细讲解 MongoDB 的连接方式、连接参数以及连接池的使用,帮助您更好地理解并使用 MongoDB。 MongoDB…...

C++学习笔记23:const 成员函数

目录 一、为什么需要 const 成员函数? 二、const 成员函数的写法 三、const 修饰的到底是什么? 四、const 成员函数不能修改成员变量 五、const 对象和普通对象的调用规则 1. const 对象只能调用 const 成员函数 2. 普通对象可以调用 const 成员函…...

Blender 3MF插件:实现CAD到3D打印的无缝转换完整指南

Blender 3MF插件:实现CAD到3D打印的无缝转换完整指南 【免费下载链接】Blender3mfFormat Blender add-on to import/export 3MF files 项目地址: https://gitcode.com/gh_mirrors/bl/Blender3mfFormat 在3D打印和数字制造领域,3D Manufacturing F…...

终结拟合式智能:记忆博弈心智架构重塑硅基生命进化逻辑

当前全球AGI研发赛道,正陷入一场难以破局的同质化内卷。无论是头部科技企业的超大参数模型,还是轻量化垂直AI产品,核心底层始终沿用Transformer概率拟合逻辑。这套技术体系虽然实现了人工智能的规模化落地,却从根源上锁死了AI的智…...

从概率拟合到内生心智:七层投影架构重构AGI数字生命新范式

自2017年Transformer架构问世以来,人工智能领域正式迈入大模型迭代时代。十余年间,千亿、万亿参数模型不断涌现,依托自注意力机制的概率拟合算法,AI在文本生成、多模态交互、逻辑问答等领域实现了规模化突破,彻底改变了…...

3步搞定显卡风扇异常:用FanControl彻底解决NVIDIA风扇噪音和转速问题

3步搞定显卡风扇异常:用FanControl彻底解决NVIDIA风扇噪音和转速问题 【免费下载链接】FanControl.Releases This is the release repository for Fan Control, a highly customizable fan controlling software for Windows. 项目地址: https://gitcode.com/GitH…...

Supervisely完整指南:5步打造AI视觉标注神器

Supervisely完整指南:5步打造AI视觉标注神器 【免费下载链接】supervisely Supervisely SDK for Python - convenient way to automate, customize and extend Supervisely Platform for your computer vision task 项目地址: https://gitcode.com/gh_mirrors/su…...

B/S架构模式在校园管理系统中的应用研究

随着校园信息化建设的不断普及,各类校园管理系统层出不穷,系统架构模式直接决定系统的使用便捷性、运维难度与适配场景。传统C/S架构即客户端/服务器架构,需要用户下载安装专属客户端,存在部署繁琐、升级困难、跨终端适配差、运维…...

MyBatis-Plus持久层框架应用技术研究

在Web应用系统开发过程中,数据持久层承担着数据库交互、数据读写、数据统计、条件查询的核心作用,持久层框架的性能与便捷性直接决定项目开发效率与系统运行稳定性。传统MyBatis框架虽能够实现数据库增删改查操作,但存在代码冗余、重复代码多…...

《技术底稿 40》别只看文件大小:一次 “反常 OOM” 背后的内存缓存重构

一、反常现象:小文件报错,大文件反倒正常业务场景需批量导入文献类 ZIP 压缩包。本次测试出现诡异问题:一个 282MB 的 ZIP 包导入时,直接抛出 java.lang.OutOfMemoryError: Java heap space 堆内存溢出。当前服务 JVM 堆内存固定配…...

基于Spring Security与JWT的权限认证技术研究

在高校信息化管理系统中,数据安全与权限隔离是系统设计的核心重点。学生奖惩信息属于高校学生核心隐私数据,包含学生奖励记录、违纪处分记录、档案信息、审批流程信息等敏感内容,若缺乏完善的权限管控机制,极易出现数据泄露、越权…...

如何让微信聊天记录成为你的数字记忆银行?WeChatMsg完全指南

如何让微信聊天记录成为你的数字记忆银行?WeChatMsg完全指南 【免费下载链接】WeChatMsg 提取微信聊天记录,将其导出成HTML、Word、CSV文档永久保存,对聊天记录进行分析生成年度聊天报告 项目地址: https://gitcode.com/GitHub_Trending/we…...

从能算到秒杀:单词拆分与「能否拼出来」的判定艺术

如果说 完全平方数​ 是在算「最少几个数」,零钱兑换​ 是在算「最少几枚硬币」,那 139. 单词拆分​ 就是在考你:一个字符串,到底能不能被“拼”出来?这也是我第一次意识到:很多 DP 题,其实是在…...

终极指南:Visual C++运行库合集AIO - 一站式解决Windows程序依赖问题

终极指南:Visual C运行库合集AIO - 一站式解决Windows程序依赖问题 【免费下载链接】vcredist AIO Repack for latest Microsoft Visual C Redistributable Runtimes 项目地址: https://gitcode.com/gh_mirrors/vc/vcredist 你是否曾经在运行某些软件或游戏时…...

为什么你的Windows快捷键突然失效?Hotkey Detective一键定位占用程序终极指南

为什么你的Windows快捷键突然失效?Hotkey Detective一键定位占用程序终极指南 【免费下载链接】hotkey-detective A small program for investigating stolen key combinations under Windows 7 and later. 项目地址: https://gitcode.com/gh_mirrors/ho/hotkey-d…...

10M参数也能跑ARC与数独,Bengio团队押注「多轨迹推理」

10M 参数跑到数独 97%,GRAM 把递归推理改成多轨迹采样。 10M 参数,在大模型时代显得有些微不足道。 但 Yoshua Bengio 团队与 KAIST、Mila、NYU 研究人员提出的 GRAM,用这个量级的模型跑出了几组值得注意的结果。 在 Sudoku-Extreme 上准确率…...

3步彻底解决Windows更新后开始菜单重置难题:ExplorerPatcher深度解析与实战

3步彻底解决Windows更新后开始菜单重置难题:ExplorerPatcher深度解析与实战 【免费下载链接】ExplorerPatcher This project aims to enhance the working environment on Windows 项目地址: https://gitcode.com/GitHub_Trending/ex/ExplorerPatcher 每次Wi…...

模拟几种数据融合协作频谱感知技术在认知无线电应用中性能研究(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…...

【顶级EI复现】考虑用户行为基于扩散模型的电动汽车充电场景生成( Python + PyTorch代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 &#x1f381…...

【顶级EI复现】基于去噪概率扩散模型(DDPM)的电动汽车充电行为场景生成研究( Python + PyTorch实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 &#x1f381…...

中性点不接地系统或中性点经消弧线圈接地系统的小电流接地故障仿真研究(Simulink仿真实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 &#x1f381…...

终极指南:如何用ESP32-A2DP库快速构建蓝牙音频设备

终极指南:如何用ESP32-A2DP库快速构建蓝牙音频设备 【免费下载链接】ESP32-A2DP A Simple ESP32 Bluetooth A2DP Library (to implement a Music Receiver or Sender) that supports Arduino, PlatformIO and Espressif IDF 项目地址: https://gitcode.com/gh_mir…...

神州细胞递表港交所 创新生物制药领军者构筑A+H双平台全球化版图

5月22日,北京神州细胞生物技术集团股份公司(证券代码:688520,证券简称:神州细胞)正式向香港联合交易所有限公司递交上市申请,迈出“AH”双资本平台布局的关键一步。公司以科创板上市为根基&…...

2026年阿里云OpenClaw/Hermes Agent配置Token Plan部署一文读懂

2026年阿里云OpenClaw/Hermes Agent配置Token Plan部署一文读懂。OpenClaw是开源的个人AI助手,Hermes Agent则是一个能自我进化的AI智能体框架。阿里云提供计算巢、轻量服务器及无影云电脑三种部署OpenClaw 与 Hermes Agent的方案、百炼Token Plan兼容主流 AI 工具&…...

2026年腾讯云OpenClaw/Hermes Agent配置Token Plan集成流程详解

2026年腾讯云OpenClaw/Hermes Agent配置Token Plan集成流程详解。OpenClaw是开源的个人AI助手,Hermes Agent则是一个能自我进化的AI智能体框架。阿里云提供计算巢、轻量服务器及无影云电脑三种部署OpenClaw 与 Hermes Agent的方案、百炼Token Plan兼容主流 AI 工具&…...

2026年京东云OpenClaw/Hermes Agent配置Token Plan保姆级搭建分享

2026年京东云OpenClaw/Hermes Agent配置Token Plan保姆级搭建分享。OpenClaw是开源的个人AI助手,Hermes Agent则是一个能自我进化的AI智能体框架。阿里云提供计算巢、轻量服务器及无影云电脑三种部署OpenClaw 与 Hermes Agent的方案、百炼Token Plan兼容主流 AI 工具…...

React Props:深入解析组件间的数据传递

React Props:深入解析组件间的数据传递 在React中,组件间的数据传递是构建复杂应用的关键。Props(属性)是React组件间数据传递的主要方式,它允许父组件向子组件传递数据。本文将深入探讨React Props的概念、使用方法以及注意事项。 一、Props的概念 Props是React组件的…...