js打怪兽(封装)

运行结果:

下面是详细代码(复制粘贴即可): 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

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

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

        // 将整个游戏过程输出

        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)
            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;
            }

        }
    </script>
</body>

</html>

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>