You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现属性与方法逻辑交互?以Unit类kick方法加闪避逻辑为例

Adding Evasion Logic and Console Feedback to the Unit Class's kick Method

Let's fix up your code to add the evasion logic and proper console feedback. First, I noticed a small typo in your original code—_currentHeaalth has an extra 'a' which would cause bugs, so we'll fix that first. Then we'll update the _kick method to handle dodges and print clear messages for each attack.

Key Changes Made:

  • Fixed the typo: _currentHeaalth → _currentHealth (critical for correct health tracking)
  • Updated the _kick method to include evasion check using Math.random()
  • Added console logs to show whether an attack hit or was dodged, including damage dealt and updated health when applicable
  • Ensured all status checks and calculations use the corrected health property name

Modified Full Code:

function Unit(maxHealth, basicDamage, evasion, type) {
  this._maxHealth = maxHealth;
  this._currentHealth = maxHealth; // Fixed typo here
  this._basicDamage = basicDamage;
  this._evasion = evasion;
  this._type = type;

  /*method for showing the status of life, true if health > 0, false otherwise */
  this._isAlive = function () {
    return this._currentHealth > 0; // Fixed typo here
  };

  /* Formats health as "current/max HP" */
  this._getFormattedHealth = function () {
    return this._currentHealth + '/' + this._maxHealth + ' HP'; // Fixed typo here
  };

  /* Returns total damage (basic + weapon if equipped) */
  this._getDamage = function () {
    return (this.weapon ? this.weapon._getDamage() : 0) + this._basicDamage;
  };

  /* Updated kick method with evasion logic and feedback */
  this._kick = function (target) {
    if (this._isAlive()) {
      const damageDealt = this._getDamage();
      // Generate random value between 0 and 1 to check evasion
      const evasionRoll = Math.random();

      if (evasionRoll > target._evasion) {
        // Attack lands: reduce target health (can't go below 0)
        target._currentHealth = Math.max(0, target._currentHealth - damageDealt);
        console.log(`${this._type} attacks ${target._type} - Hit! ${target._type} takes ${damageDealt} damage. Health: ${target._getFormattedHealth()}`);
      } else {
        // Attack is dodged
        console.log(`${this._type} attacks ${target._type} - Dodged! No damage taken.`);
      }
    } else {
      console.log(`${this._type} can't attack—they're already defeated!`);
    }
    return this;
  };

  /* Returns full unit status as a string */
  this.toString = function () {
    return `Type-${this._type}, is alive - ${this._isAlive()}, ${this._getFormattedHealth()}, hero current damage-${this._getDamage()} points, hero evasion - ${this._evasion}`;
  };
}

function Archer(maxHealth, basicDamage, evasion) {
  Unit.apply(this, arguments);
  this._type = "archer";
}

var archer = new Archer(60, 5, 0.6);

function Swordsman(maxHealth, basicDamage, evasion) {
  Unit.apply(this, arguments);
  this._type = "swordsman";
}

var swordsman = new Swordsman(100, 10, 0.3);

// Fight until one unit is defeated
while (archer._isAlive() && swordsman._isAlive()) {
  archer._kick(swordsman);
  swordsman._kick(archer);
}

console.log("\nFinal Status:");
console.log(archer.toString());
console.log(swordsman.toString());

How the Evasion Logic Works:

  • We use Math.random() to generate a value between 0 (inclusive) and 1 (exclusive) — this simulates a random chance for evasion.
  • If the random roll is greater than the target's _evasion value, the attack lands. For example, an archer with 0.6 evasion has a 60% chance to dodge (rolls ≤0.6 trigger a dodge) and 40% chance to take damage.
  • When an attack hits, we calculate total damage with _getDamage() (which includes basic damage plus any weapon damage if equipped), then clamp the target's health to 0 to avoid negative values.
  • Console messages break down each attack's outcome, making it easy to track the fight's progress.

内容的提问来源于stack exchange,提问作者Igor Shvets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:28:45