js fight monsters (encapsulation function)

operation result:

The following is the detailed code (just copy and paste): 


// 案例:英雄打怪兽
// 创建一个构造函数 (英雄和怪兽),攻击力(100)、防御力(50)、暴击率(随机一个数5的倍数 攻击力*2)
// 伤害值 = 攻击力 - 防御力
// 伤害值最小为1

// 直到一方死掉为止  hp <= 0

// 将整个游戏过程输出
/**
* 游戏角色的构造函数
* @param {*} name 角色名
* @param {*} attack 攻击力
* @param {*} defence 防御力
* @param {*} hp 生命值
* @param {*} CritRate 暴击率(0~100)
*/
function CreateHero(name, attack, defence, hp, CritRate) {
    this.name = name;
    this.attack = attack;
    this.defence = defence;
    this.hp = hp;
    this.CritRate = CritRate;


// 击打的方法 
// hero.impact(boss)
// boss.impact(hero)
/**
 * 
 * @param {*} name 攻击对象
 */
this.impact = function (name) {
    sh = this.attack - name.defence; //造成的伤害

    name.hp -= sh; //剩余的血量值

    bj = this.CritRate / 100; //指定暴击率

    // console.log(bj);
    bjl = Math.random(); //随机暴击率

    isBj = false; //初始化动态触发暴击为无暴击
    // console.log(sh);
}
console.log(`${this.name}\t攻击力:${this.attack}\t防御力:${this.defence}\t生命值:${this.hp}\t暴击率:${this.CritRate}`)

}

// 创建英雄和怪兽各自的构造函数
var hero = new CreateHero('英雄', 300, 50, 1000, 30);
console.log('VS');
var boss = new CreateHero('怪兽', 200, 0, 800, 5);

// 循环双方击打的次数
while (true) {
    hero.impact(boss);
    heroSh = sh; //定义一个变量接收英雄造成的伤害
    boss.impact(hero);

// 判断随机暴击率小于指定暴击率的时,触发英雄的暴击率
if (bjl <= bj) {
    isBj = true;
    // sh *= 2;
    heroSh *= 2; //造成的伤害加倍
}

// 造成伤害不能小于1
if (sh < 1) {
    sh = 1;
}

// 判断双方剩余的血量值
if (boss.hp > 0 && hero.hp > 0) {

    console.log(`【${hero.name}】打【${boss.name}】 造成伤害:【${heroSh}】 当前血量为:【${boss.hp}】`);

    console.log(`${isBj?'暴击!':''} 【${boss.name}】打【${hero.name}】 造成伤害:【${sh}】 当前血量为:【${hero.hp}】`);

} else if (boss.hp <= 0) { //当Boss血量值小于等于0时,hero  is  win
    console.log(`【${boss.name}】当前血量为:【${0}】is die`);
    console.log(`【${hero.name}】win`);
    break;
} else if (hero.hp <= 0) { //当hero血量值小于等于0时,boss  is  win
    console.log(`【${hero.name}】当前血量为:【${0}】is die`);
    console.log(`【${boss.name}】win`);
    break;
}

}

Guess you like

Origin blog.csdn.net/emm_10_01/article/details/122398271