┃ 类定义源码 — 展示继承与多态实现
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 ← 阵修版