专栏文章
植物大战僵尸代码
个人记录参与者 1已保存评论 0
文章操作
快速查看文章及其快照的属性,并进行相关操作。
- 当前评论
- 0 条
- 当前快照
- 1 份
- 快照标识符
- @miq8meds
- 此快照首次捕获于
- 2025/12/04 00:44 3 个月前
- 此快照最后确认于
- 2025/12/04 00:44 3 个月前
#include
#include
#include
#include
#include <conio.h>
#include <windows.h>
using namespace std;
const int WIDTH = 20;
const int HEIGHT = 5;
class GameObject {
protected:
int x, y;
int health;
public:
GameObject(int x, int y, int health) : x(x), y(y), health(health) {}
virtual ~GameObject() {}
virtual void update() = 0;
virtual void draw() const = 0;
int getX() const { return x; }
int getY() const { return y; }
int getHealth() const { return health; }
void takeDamage(int damage) { health -= damage; }
};
class Plant : public GameObject {
public:
Plant(int x, int y, int health) : GameObject(x, y, health) {}
virtual void shoot() = 0;
};
class Zombie : public GameObject {
protected:
int speed;
public:
Zombie(int x, int y, int health, int speed) : GameObject(x, y, health), speed(speed) {}
void update() override {
x -= speed;
}
};
class Peashooter : public Plant {
public:
Peashooter(int x, int y) : Plant(x, y, 50) {}
void update() override {}
void draw() const override {
cout << "P";
}
void shoot() override {
// 射击逻辑
}
};
class NormalZombie : public Zombie {
public:
NormalZombie(int x, int y) : Zombie(x, y, 100, 1) {}
void draw() const override {
cout << "Z";
}
};
class Game {
private:
vector<Plant*> plants;
vector<Zombie*> zombies;
int sun;
bool gameOver;
CPPvoid drawBorder() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++) cout << "#";
cout << endl;
}
void spawnZombie() {
if (rand() % 100 < 5) { // 5% 概率生成僵尸
zombies.push_back(new NormalZombie(WIDTH - 1, rand() % HEIGHT));
}
}
public:
Game() : sun(50), gameOver(false) {
srand(time(0));
}
CPP~Game() {
for (auto p : plants) delete p;
for (auto z : zombies) delete z;
}
void run() {
while (!gameOver) {
drawBorder();
// 绘制游戏区域
for (int y = 0; y < HEIGHT; y++) {
cout << "#";
for (int x = 0; x < WIDTH; x++) {
bool drawn = false;
for (auto p : plants) {
if (p->getX() == x && p->getY() == y) {
p->draw();
drawn = true;
break;
}
}
for (auto z : zombies) {
if (z->getX() == x && z->getY() == y) {
z->draw();
drawn = true;
break;
}
}
if (!drawn) cout << " ";
}
cout << "#" << endl;
}
for (int i = 0; i < WIDTH + 2; i++) cout << "#";
cout << "\nSun: " << sun << endl;
// 用户输入
if (_kbhit()) {
char input = _getch();
if (input == 'p' && sun >= 50) {
plants.push_back(new Peashooter(0, rand() % HEIGHT));
sun -= 50;
}
}
// 更新游戏状态
spawnZombie();
for (auto z : zombies) z->update();
sun++;
// 检查碰撞
for (auto z : zombies) {
if (z->getX() <= 0) {
gameOver = true;
cout << "Zombies ate your brain!" << endl;
}
}
Sleep(200);
}
}
};
int main() {
Game game;
game.run();
return 0;
}
相关推荐
评论
共 0 条评论,欢迎与作者交流。
正在加载评论...