程序代码:
#include <iostream>
using namespace std;
class SmallPlant//小型植物
{
public:
//攻击力
virtual int AttackPower()
{
return 10;//攻击力为10
}
};
class Zombie//僵尸
{
public:
//攻击力
int DestoryPower()
{
return 15;//攻击力为15
}
};
//植物大战僵尸
void Attack(SmallPlant *p, Zombie *z)
{
if(p->AttackPower() > z->DestoryPower())
{
cout<<"植物战胜了僵尸!"<<endl;
}
else
{
cout<<"僵尸战胜了植物!"<<endl;
}
}
//小型植物派生出大型植物
class BigPlant : public SmallPlant
{
public:
//攻击力
int AttackPower()
{
return 20;//攻击力为15
}
};
void main()
{
SmallPlant p;//小型植物
Zombie z;//僵尸
BigPlant p1;//大型植物
//植物大战僵尸
Attack (&p, &z);
Attack(&p1, &z);
system("pause");
}
执行结果:
本文通过C++代码实现了一个简单的“植物大战僵尸”游戏逻辑。定义了小型植物和僵尸两个类,分别拥有攻击力属性,并通过派生类实现了大型植物。通过比较攻击力大小判断胜负。

被折叠的 条评论
为什么被折叠?



