题目链接
分析:
实践了面向对象编程的思想。每个角色都有的属性是攻击力和生命值,封装成结构体。对于每个操作需要输入的数据是不同的,将操作封装成结构体,内部有具体的操作函数。然后需要注意的是输入end 后角色改变,因此操作对象中需要一个now 指明当前的操作人。只有两个人用(now+1)%2实现角色的转换。大部分的操作是vector 的增加和删除。
然后需要注意的是,攻击的时候如果死亡需要移除,但是如果在最后一轮英雄死亡,移除之后需要输出英雄的生命值,结果就是错误的,因此需要加上不等于0 的条件。
代码:
#include<stdio.h>
#include<vector>
#include<string>
#include<iostream>
using namespace std;
struct person
{
int health;
int attack;
person(int theHealth,int theAttack){
health=theHealth;
attack=theAttack;
}
bool operator < (const person p)const{
return health<p.health;
}
};
vector<vector<person> > v(2); //2行
person hero(30,0);
//vector<person> v[2];
struct Op
{
const string ops[3]={"summon","attack","end"};
int now;
int position,attack,health,attacker,defender;
Op(int thenow,string s){
now=thenow;
if(s==ops[0]){
scanf("%d %d %d",&position,&attack,&health);
summon();
}
else if(s==ops[1]){
scanf("%d %d",&attacker,&defender);
Attack();
}
else if(s==ops[2])
{
end();
}
}
void summon()
{
person pp(health,attack);
v[now].insert(v[now].begin()+position,pp);
//print();
}
void Attack()
{
v[now][attacker].health-=v[(now+1)%2][defender].attack;
v[(now+1)%2][defender].health-=v[now][attacker].attack;
if(v[now][attacker].health<=0){
v[now].erase(v[now].begin()+attacker);
}
if(defender!=0 && v[(now+1)%2][defender].health<=0){ //假设==0,去除英雄,但是最后需要输出英雄的生命值,结果错误。
v[(now+1)%2].erase(v[(now+1)%2].begin()+defender);
}
//print();
}
void end()
{
return ;
}
void print()
{
cout<<"********"<<endl;
for(int i=0;i<v[0].size();i++){
cout<<v[0][i].health<<" "<<v[0][i].attack<<" ";
}
cout<<endl;
for(int i=0;i<v[0].size();i++){
cout<<v[1][i].health<<" "<<v[1][i].attack<<" ";
}
cout<<"********"<<endl;
}
};
int main()
{
int n;
string s;
int now=0;
string e="end";
cin>>n;
v[0].push_back(hero);
v[1].push_back(hero);
while(n--){
cin>>s;
Op* op = new Op(now,s);
if(s==e){
now=(now+1)%2;
}
}
if(v[0][0].health<=0&&v[1][0].health>0){
printf("-1\n");
now=1;
}
else if(v[0][0].health>0&&v[1][0].health<=0){
printf("1\n");
now=0;
}
else if(v[0][0].health>0&&v[1][0].health>0){
printf("0\n");
}
printf("%d\n",v[0][0]);
printf("%d ",v[0].size()-1);
for(int i=1;i<v[0].size();i++){
printf("%d ",v[0][i]);
} //先手玩家
printf("\n");
printf("%d\n",v[1][0]);
printf("%d ",v[1].size()-1);
for(int i=1;i<v[1].size();i++){
printf("%d ",v[1][i]);
} //后手玩家
printf("\n");
return 0;
}