Page 1 of 1

[SOLVED] Broken game loop.

Posted: Mon Apr 04, 2011 9:41 pm
by jakobnator
This is my ticktacktoe game loop, please criticize if there is anything wrong but its supposed to switch between x and o. X being true and o being false, then alternate but its just giving me random x's or o's not in a pattern like it should

Code: Select all

int main ( int argc, char *args[] )
{
    //check for errors
    bool quit = false;
    if( init() == false ) { return 1;}
    if( load_files() == false ) { return 2;}
    apply_surface( 0,0,background,screen);
    //game loop
    while (quit == false)
    {

        Target myTarget1(2,2,247,119);
        Target myTarget2(251,2,247,119);
        Target myTarget3(502,2,247,119);
        Target myTarget4(2,127,247,119);
        Target myTarget5(251,127,247,119);
        Target myTarget6(502,127,247,119);
        Target myTarget7(2,249,247,119);
        Target myTarget8(251,249,247,119);
        Target myTarget9(502,249,247,119);

        if(SDL_PollEvent(&event))
        {
            myTarget1.handle_events();
            myTarget2.handle_events();
            myTarget3.handle_events();
            myTarget4.handle_events();
            myTarget5.handle_events();
            myTarget6.handle_events();
            myTarget7.handle_events();
            myTarget8.handle_events();
            myTarget9.handle_events();
            if( event.type == SDL_QUIT )
            {
                //Quit the program
                quit = true;
            }
        }
        if (Turn == true)
        {
            current_turn = target_X;
            Turn = false;
        }
        else
        if (Turn == false)
        {
            current_turn = target_O;
            Turn = true;
        }
        if (SDL_Flip( screen ) == -1)
            {
            return 3;
            }
    }

Re: Broken game loop.

Posted: Mon Apr 04, 2011 11:05 pm
by krilik
Its not random X's and O's. It just looks random because your loop is constantly switching the current_turn from target_X to target_O.

Code: Select all

if (Turn == true)
        {
            current_turn = target_X;
            Turn = false;
        }
        else
        if (Turn == false)
        {
            current_turn = target_O;
            Turn = true;
        }
Turn is (assuming) going to be true the first loop, once it hits the if statement its going to be set to false. The next iteration is going to be set to true again. And so on and so forth. (Assuming this is player controlled) it never waits for any input before deciding to change the current turn.

You should be doing this check after an input by the player, or the computer, and not every loop iteration.

Re: Broken game loop.

Posted: Tue Apr 05, 2011 8:15 am
by jakobnator
Thanks, I was assuming to put it in the handle events so I did and it worked :)