简体   繁体   English

使用数组条件跳出循环

[英]Break out of Loop with Array Condition

I'm currently making a Chutes and Ladders game for class.我目前正在为课堂制作滑梯和梯子游戏。 The win condition for this game is if a player lands on Square 100, they win.此游戏的获胜条件是,如果玩家登陆 Square 100,则他们获胜。 If they happen to go past 100, they stay there until everyone finishes the game (Either someone lands on 100 or everyone goes past 100).如果他们碰巧超过 100,他们会一直呆在那里,直到每个人都完成游戏(要么有人登陆 100,要么每个人都超过 100)。 I'm having trouble breaking out of the while loop if EVERYONE is past 100.如果每个人都超过 100,我就无法摆脱 while 循环。

There's a lot of code so I'll simplify as much as I can.有很多代码,所以我会尽可能地简化。 Under !!!HERE IS THE PROBLEM!!!!在!!!这里是问题!!!! is where I need help.是我需要帮助的地方。

Is there a way to specify once ALL the elements in an array are ABOVE 100 to break?有没有办法指定一旦数组中的所有元素都超过 100 就可以打破? Sorry if the question is a repeat...this post has a lot more detail.对不起,如果问题是重复的……这篇文章有更多的细节。

string name[MAXplayers]; //Array to store names
int position[MAXplayers]; //Array to store board position

unsigned seed; //Random Number Generator Seed
seed = time(0); //Set seed to 0
srand(seed); //Call srand function

int spin;
bool done = false;
int counter = 0;
const int WIN = 100;

while (done != true)
{
    if (counter == WIN)
    {
        cout << "That's it, game over!" << endl << endl;
        done = true;
    }
    else 
    {
        for (int i = 0; i < players; i++)
        {
            if (position[i] > WIN) //!!!!!HERE IS THE PROBLEM!!!!!!
            {
                cout << "Sorry " << name[i] << "! You can't move! You're stuck at " << position[i] << endl << endl;
            }
            else
            {
                cout << name[i] << "'s turn! Pres [Enter] to spin the wheel!";
                cin.get();
                spin = rand() % 12 + 1;
                cout << "You spun the number " << spin << "!" << endl;

                int temploc = position[i] += spin;
etc...etc...etc...etc...etc...etc...

To break out of the inter for loop when your WIN condition is met, you can use the keyword break .要在满足 WIN 条件时跳出 inter for循环,可以使用关键字break This will stop the loop processing regardless of the conditional on the for loop.无论for循环的条件如何,这都将停止循环处理。

Note however after breaking out, the program will still iterate around your while loop until it's conditional done != true is met.但是请注意,在爆发后,程序仍将围绕您的while循环进行迭代,直到满足条件done != true为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM