c++代码植物大战僵尸
时间: 2023-10-19 15:07:11 浏览: 224
好的,以下是一个简单的植物大战僵尸的 C++ 代码示例:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 植物类
class Plant {
public:
Plant(string name, int cost) : name(name), cost(cost) {}
virtual void attack() = 0; // 攻击方法,纯虚函数
protected:
string name; // 名称
int cost; // 花费
};
// 向日葵类
class Sunflower : public Plant {
public:
Sunflower() : Plant("Sunflower", 50) {}
void attack() {
cout << "Sunflower produces suns." << endl;
}
};
// 豌豆射手类
class Peashooter : public Plant {
public:
Peashooter() : Plant("Peashooter", 100) {}
void attack() {
cout << "Peashooter shoots peas." << endl;
}
};
// 僵尸类
class Zombie {
public:
Zombie(int health, int attack) : health(health), attack(attack) {}
void beAttacked(int damage) {
health -= damage;
if (health <= 0) {
cout << "Zombie is dead." << endl;
}
}
protected:
int health; // 生命值
int attack; // 攻击力
};
// 普通僵尸类
class NormalZombie : public Zombie {
public:
NormalZombie() : Zombie(100, 10) {}
};
// 游戏类
class Game {
public:
Game() {
plants.push_back(new Sunflower());
plants.push_back(new Peashooter());
}
void start() {
while (true) {
// 产生阳光
cout << "Sun is produced." << endl;
// 放置植物
for (int i = 0; i < plants.size(); i++) {
Plant* plant = plants[i];
if (sun >= plant->cost) {
sun -= plant->cost;
plant->attack();
}
}
// 僵尸进攻
zombie.beAttacked(20);
if (zombie.health <= 0) {
break;
}
}
}
private:
int sun = 100; // 阳光数量
vector<Plant*> plants; // 植物列表
NormalZombie zombie; // 僵尸
};
int main() {
Game game;
game.start();
return 0;
}
```
这是一个简单的植物大战僵尸的代码示例,其中包含了植物类、僵尸类和游戏类。在游戏开始时,会产生阳光并放置植物,然后僵尸会进攻,直到僵尸死亡为止。
阅读全文