简体   繁体   中英

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. 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). I'm having trouble breaking out of the while loop if EVERYONE is past 100.

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? 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 . This will stop the loop processing regardless of the conditional on the for loop.

Note however after breaking out, the program will still iterate around your while loop until it's conditional done != true is met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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