C++ 5.11 人操控枪战小游戏代码示例
#include
using namespace std;
// 定义玩家类 class Player { public: int health;
Player() {
health = 100;
}
void shoot() {
cout << "玩家开枪,造成10点伤害!" << endl;
}
void takeDamage(int damage) {
health -= damage;
cout << "玩家受到" << damage << "点伤害,剩余生命值:" << health << endl;
}
};
// 定义敌人类 class Enemy { public: int health;
Enemy() {
health = 50;
}
void shoot() {
cout << "敌人开枪,造成5点伤害!" << endl;
}
void takeDamage(int damage) {
health -= damage;
cout << "敌人受到" << damage << "点伤害,剩余生命值:" << health << endl;
}
};
int main() { Player player; Enemy enemy;
while (player.health > 0 && enemy.health > 0) {
// 玩家开枪
player.shoot();
enemy.takeDamage(10);
// 敌人开枪
enemy.shoot();
player.takeDamage(5);
}
// 判断胜负
if (player.health <= 0 && enemy.health <= 0) {
cout << "平局!" << endl;
}
else if (player.health <= 0) {
cout << "敌人获胜!" << endl;
}
else {
cout << "玩家获胜!" << endl;
}
return 0;
}
// 本示例中,我们定义了一个Player玩家类和一个Enemy敌人类,它们都具有生命值和开枪的方法。在main函数中,我们创建了一个玩家对象和一个敌人对象,并使用循环进行战斗。每个循环中,玩家和敌人都会开枪,并相互造成伤害。当其中一方生命值降为0时,战斗结束,根据生命值判断胜负。
// 请注意,这只是一个简单的示例,没有添加更多的游戏逻辑和交互性。你可以根据自己的需求进行扩展和修改。
原文地址: https://www.cveoy.top/t/topic/pCDx 著作权归作者所有。请勿转载和采集!