html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="playMonster.js"></script>
<script>
</script>
</body>
</html>
CSS
function Charactor(name, attack, defence, hp, CritRate) {
this.name = name;
this.attack = attack;
this.defence = defence;
this.hp = hp;
this.CritRate = CritRate;
this.print = function () {
console.log(`${this.name}\t攻击力:${this.attack}\t防御力:${this.defence}\t生命值:${this.hp}\t暴击率:${this.CritRate}`)
}
this.hit = function (ctor) {
var damage = this.attack - ctor.defence;
var rate = this.CritRate / 100;
var rad = Math.random();
var isCrit = false;
if (rad <= rate) {
isCrit = true;
damage *= 2;
}
if (damage < 1) {
damage = 1;
}
ctor.hp -= damage;
if (ctor.hp < 0) {
ctor.hp = 0;
}
console.log(`${isCrit?"暴击!":""}【${this.name}】攻击【${ctor.name}】,造成【${damage}】点伤害,对方当前血量为【${ctor.hp}】`)
return ctor.hp === 0;
}
}
var hero = new Charactor("英雄", 100, 20, 500, 30);
hero.print();
console.log("vs");
var monster = new Charactor("怪兽", 120, 30, 400, 5);
monster.print();
while (true) {
if (hero.hit(monster)) {
break;
}
if (monster.hit(hero)) {
break;
}
}
console.log("=======================");
hero.print();
monster.print();
console.log("游戏结束");