✦ 仙 途 ✦

C++ 修仙模拟器 · 继承与多态 · 网页交互版

┃ 类继承结构 — 基类与派生类

Cultivator(修仙者·基类) virtual
道号 · 境界 · 气血 · 灵力 · 灵石 · 寿元
SwordCultivator(剑修) extends Cultivator
+攻击力 +剑气值
PillCultivator(丹修) extends Cultivator
+炼丹率 +丹药库存
FormationCultivator(阵修) extends Cultivator
+阵法强度 +灵力储备

┃ 交互操作 — 点击按钮触发多态行为

系统 修仙世界已开启,点击按钮体验继承多态

┃ 多态行为对照 — 同一方法 · 不同表现

cultivate() 修炼
⚔ 剑修:攻击力+20,剑气+15
⚗ 丹修:概率炼丹,提升炼丹经验
▤ 阵修:提升阵法强度,储备灵力
breakthrough() 突破
⚔ 剑修:概率45%,成功后攻击翻倍
⚗ 丹修:概率65%,丹药额外加成
▤ 阵修:概率55%,阵法护持
duel() 对决
⚔ 剑修:纯攻击,剑气爆发
⚗ 丹修:丹药回血,持久消耗
▤ 阵修:布阵减伤,反伤制敌

┃ 类定义源码 — 展示继承与多态实现

class Cultivator { // ===== 封装:受保护属性 ===== constructor(name, root) { this.name = name; // 道号 this.root = root; // 灵根 this.realm = '凡人'; // 境界 this.health = 100; // 气血 this.spiritPower = 50; // 灵力 this.spiritStone = 10; // 灵石 this.lifespan = 100; // 寿元 } // ===== 多态:虚方法 ===== cultivate() { /* 基类默认 */ } breakthrough() { /* 基类默认:40% */ } duel(opponent) { /* 基类默认:基础攻击 */ } }
class SwordCultivator extends Cultivator { // 【继承】通过 extends 继承基类 constructor(name, root) { super(name, root); // 调用基类构造 this.attackPower = 30; // 攻击力(新增) this.swordQi = 20; // 剑气值(新增) } // 【多态】重写 cultivate() cultivate() { this.attackPower += 20; this.swordQi += 15; return `剑气纵横!攻击力+20,剑气+15`; } // 【多态】重写 breakthrough() —— 45% 概率,成功攻击翻倍 breakthrough() { const rate = 0.45; if (Math.random() < rate) { this.attackPower *= 2; return true; } return false; } // 【多态】重写 duel() —— 高爆发 duel(opponent) { const dmg = 25 + Math.floor(this.swordQi/2); opponent.health -= dmg; return `万剑归宗!造成 ${dmg} 点伤害`; } }
class PillCultivator extends Cultivator { constructor(name, root) { super(name, root); this.pillStock = 3; // 丹药库存 this.pillSuccessRate = 0.5; // 炼丹成功率 this.pillExp = 0; } // 【多态】修炼时概率炼丹 cultivate() { this.spiritPower += 8; if (Math.random() < this.pillSuccessRate) { this.pillStock++; this.pillExp += 5; return `成功炼出一枚丹药!`; } return `炼丹失败...`; } // 【多态】突破概率 65%,丹药加成 breakthrough() { let rate = 0.65; if (this.pillStock > 0) { rate += 0.15; this.pillStock--; } return Math.random() < rate; } // 【多态】丹药回血,持久战 duel(opponent) { /* 造成少量伤害,低血量时回血 */ } }
class FormationCultivator extends Cultivator { constructor(name, root) { super(name, root); this.formationStrength = 15; // 阵法强度 this.spiritReserve = 30; // 灵力储备 } // 【多态】布阵修炼 cultivate() { this.formationStrength += 12; this.spiritReserve += 20; return `阵法强度+12,灵力储备+20`; } // 【多态】突破概率 55%,阵法护持 breakthrough() { let rate = 0.55; if (this.formationStrength > 50) rate += 0.1; return Math.random() < rate; } // 【多态】防御型,减伤+反伤 duel(opponent) { /* 困龙阵:减伤+反伤 */ } }
// ===== 多态:同一接口,不同行为 ===== const cultivators = [ new SwordCultivator('青云剑仙','天灵根'), new PillCultivator('丹心长老','木灵根'), new FormationCultivator('天阵子','水灵根'), ]; // 遍历调用 → 多态! for (const c of cultivators) { // c 是基类类型,但调用的是派生类重写的方法 addLog(`${c.name} → ${c.cultivate()}`); } // 青云剑仙 → 剑气纵横!攻击力+20,剑气+15 ← 剑修版 // 丹心长老 → 成功炼出一枚丹药! ← 丹修版 // 天阵子 → 阵法强度+12,灵力储备+20 ← 阵修版
《仙途 · C++ 修仙模拟器》 — 继承 · 封装 · 多态 — 网页交互演示版

⚔ 对决竞技场

选择两位修仙者,点击"开始对决"观战!
VS