淘先锋技术网

首页 1 2 3 4 5 6 7

植物大战僵尸是一款经典的塔防游戏,游戏中玩家需要通过种植植物来阻挡即将进攻的僵尸。


// 植物类
class Plant {
  constructor(name, cost, hp, attack) {
    this.name = name;
    this.cost = cost;
    this.hp = hp;
    this.attack = attack;
  }
}

// 僵尸类
class Zombie {
  constructor(name, hp, attack) {
    this.name = name;
    this.hp = hp;
    this.attack = attack;
  }
}

// 战场类
class Battlefield {
  constructor(plants, zombies) {
    this.plants = plants;
    this.zombies = zombies;
  }

  // 植物攻击
  plantAttack(plant, zombie) {
    zombie.hp -= plant.attack;
    if (zombie.hp <= 0) {
      console.log(`${zombie.name}已死亡!`);
    }
  }

  // 僵尸攻击
  zombieAttack(zombie, plant) {
    plant.hp -= zombie.attack;
    if (plant.hp <= 0) {
      console.log(`${plant.name}已被摧毁!`);
    }
  }
}

let sunflower = new Plant('向日葵', 50, 100, 5);
let peaShooter = new Plant('豌豆射手', 100, 100, 10);
let zombie = new Zombie('普通僵尸', 100, 10);

let plants = [sunflower, peaShooter];
let zombies = [zombie];

let battlefield = new Battlefield(plants, zombies);
battlefield.plantAttack(peaShooter, zombie); // 植物攻击僵尸
battlefield.zombieAttack(zombie, sunflower); // 僵尸攻击植物

植物大战僵尸html格式代码

以上是植物大战僵尸的部分逻辑代码,通过构建植物和僵尸类来实现游戏的动态效果,可见该游戏的开发并不简单。