我有这个程序,其中角色使用Weapon对象对其他角色造成伤害。所以我实例化了两个玩家和两个敌人。然后将它们推入玩家列表和敌人列表。所以每个列表都有两个对象。我设置了迭代器和一个for循环,它应该在每个循环中对列表进行洗牌,因此每次攻击都是随机的。这样,轮到我直到我到达两个列表的末尾。现在我想重置for循环,以便玩家继续轮流,直到两个敌人或两个玩家都死亡并且游戏结束。我尝试使用while(true)循环并将for循环嵌套,但这只会使循环结束后程序停止。我如何设置for循环重置,以便玩家和敌人继续攻击直到游戏结束?我将不胜感激。谢谢。
int main()
{
srand(time(NULL));
PlayerCharacter* p1 = new PlayerCharacter();
PlayerCharacter* p2 = new PlayerCharacter();
EnemyCharacter* e1 = new EnemyCharacter();
EnemyCharacter* e2 = new EnemyCharacter();
p1->printCharacter();
p2->printCharacter();
e1->printCharacter();
e2->printCharacter();
string enemyTarget, playerTarget;
list<Character*> players;
list<Character*> enemies;
players.push_back(p1);
players.push_back(p2);
enemies.push_back(e1);
enemies.push_back(e2);
list<Character*>::iterator PinsertIt = players.begin();
list<Character*>::iterator EinsertIt = enemies.begin();
while (!p1->dead && !p2->dead && !e1->dead && !e2->dead)
{
if (PinsertIt == players.end()) {
PinsertIt = players.begin();
}
if (EinsertIt != enemies.end()) {
EinsertIt = enemies.begin();
}
for (; PinsertIt != players.end() && EinsertIt != enemies.end(); ++PinsertIt, ++EinsertIt)
{
listShuffle(players);
listShuffle(enemies);
if (*PinsertIt == p1)
{
if (!p1->dead)
{
cout << "Player One. Choose your Target (1 or 2)" << endl;
cin >> playerTarget;
playerAttack(e1, e2, p1->currentWeapon, playerTarget);
}
else
{
cout << p1->firstName << " " << p1->lastName << " is dead. Skip turn" << endl;
}
}
else if (*PinsertIt == p2)
{
if (!p2->dead)
{
cout << "Player Two. Choose your Target (1 or 2)" << endl;
cin >> playerTarget;
playerAttack(e1, e2, p2->currentWeapon, playerTarget);
}
else
{
cout << p2->firstName << " " << p2->lastName << " is dead. Skip turn" << endl;
}
}
if (*EinsertIt == e1)
{
if (!e1->dead)
{
cout << "Enemy One ";
enemyAttack(p1, p2, e1->currentWeapon);
}
else
{
cout << e1->firstName << " " << e1->lastName << " is dead. Skip turn" << endl;
}
}
else if (*EinsertIt == e2)
{
if (!e2->dead)
{
cout << "Enemy Two ";
enemyAttack(p1, p2, e2->currentWeapon);
}
else
{
cout << e2->firstName << " " << e2->lastName << " is dead. Skip turn" << endl;
}
}
if (p1->dead && p2->dead)
{
cout << "Game Over!" << endl;
}
else if (e1->dead && e2->dead)
{
cout << "You Win!" << endl;
}
}
PinsertIt++;
EinsertIt++;
}
system("pause");
return 0;
}
答案 0 :(得分:0)
更改你的while循环结束条件,检查所有玩家是否死亡或所有敌人都已死亡。在您的循环中,如果PinsertIt
或EinsertIt
点击列表末尾,请将其重置为开头。
while (!isAllPlayersDead() && !isAllEnemiesDead()) {
if (PinsertIt == players.end()) {
PinsertIt = players.begin();
}
if (EinsertIt != enemies.end()) {
EinsertIt = enemies.begin();
}
doSomeThingWithYourPlayersAndEnemies();
PinsertIt++;
EinsertIt++;
}