tic tac toe crashes :(

This is a discussion on tic tac toe crashes :( within the Game Programming forums, part of the General Programming Boards category; Hi guys, I made a version of tic tac toe from a book i needed to change some of the ...

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    31

    tic tac toe crashes :(

    Hi guys,

    I made a version of tic tac toe from a book i needed to change some of the code to get it to work but it was only a consol program.

    So i decided to try to use sdl to make it better ive changed the the code slightly
    to make it work with sdl and instead of displaying an empty board at first it displays pieces in a zigzag way?

    i have a string stream in some of my functions but i havent wrote them into the main program, i mean i dont display them yet.

    i need to get the game to work then ill do that but when i run it it freezes and wont exit, i have to end prosses with task manager to get rid of it i just finished writing it so it may be somthing simple but like some people im easily annoyed when a plan doesnt come together

    i think maybe the string stream creates the problems?
    my code is very long the "original" book functions are under main and the sdl functions are above it dont ask why beacause i dont know it just ended up that way
    im quite lazy so i adaped my last game to accept this new tic tac toe code
    i appologise for the bad code hope you can read it
    well id apreciate any help

  2. #2
    Registered User
    Join Date
    Jan 2007
    Posts
    31
    Code:
    /*This source code copyrighted by Lazy Foo' Productions (2004-2007) and may not be redestributed without written permission.*/
    
    //The headers
    #include "SDL/SDL.h"
    #include "SDL/SDL_image.h"
    #include "SDL/SDL_ttf.h"
    #include <string>
    #include <sstream>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <cstdlib>
    using namespace std;
    const char empty = ' ';
    const char tie = 't';
    const char no_one = 'n';
    const char x = 'x';
    const char o = 'o';
    //original tic tac toe functions
    void instructions();
    char askyesno ();
    int asknumber ();
    char humanpiece ();
    char opponent (char piece);
    void displayboard (const vector<char>& board);
    char winner (const vector<char>& board);
    bool islegal (int move, const vector<char>& board);
    int humanmove (vector<char>& board, char human);
    int computermove (vector<char> board, char computer);
    void announcewinner (char winner, char human, char computer);
    
    std::stringstream word;
    //Screen attributes
    const int SCREEN_WIDTH = 150;
    const int SCREEN_HEIGHT = 150;
    const int SCREEN_BPP = 32;
    
    //The frames per second
    const int FRAMES_PER_SECOND = 10;
    
    
    //The surfaces
    SDL_Surface *space = NULL;
    SDL_Surface *message = NULL;
    SDL_Surface *board = NULL;
    SDL_Surface *background = NULL;
    SDL_Surface *screen = NULL;
    
    //The event structure
    SDL_Event event;
       
       //The font that's going to be used
    TTF_Font *font = NULL;
    
    //The color of the font
    SDL_Color textColor = { 0,0,0 };
    
    //The areas of the sprite sheet
    SDL_Rect pieces[ 3 ];
    
    //clip board pieces
    void clip();
    void clip()
    {
        //piece x
        pieces[0].x = 0;
        pieces[0].y = 0;
        pieces[0].w = 50;
        pieces[0].h = 50;
        //pieces o
        pieces[1].x = 50;
        pieces[1].y = 0;
        pieces[1].w = 50;
        pieces[1].h = 50;
        //pieces empty
        pieces[2].x = 100;
        pieces[2].y = 0;
        pieces[2].w = 50;
        pieces[2].h = 50;
    }
    //The timer
    class Timer
    {
        private:
        //The clock time when the timer started
        int startTicks;
        
        //The ticks stored when the timer was paused
        int pausedTicks;
        
        //The timer status
        bool paused;
        bool started;
        
        public:
        //Initializes variables
        Timer();
        
        //The various clock actions
        void start();
        void stop();
        void pause();
        void unpause();
        
        //Gets the timer's time
        int get_ticks();
        
        //Checks the status of the timer
        bool is_started();
        bool is_paused();    
    };
    
    SDL_Surface *load_image( std::string filename ) 
    {
        //The image that's loaded
        SDL_Surface* loadedImage = NULL;
        
        //The optimized surface that will be used
        SDL_Surface* optimizedImage = NULL;
        
        //Load the image
        loadedImage = IMG_Load( filename.c_str() );
        
        //If the image loaded
        if( loadedImage != NULL )
        {
            //Create an optimized surface
            optimizedImage = SDL_DisplayFormat( loadedImage );
            
            //Free the old surface
            SDL_FreeSurface( loadedImage );
            
            //If the surface was optimized
            if( optimizedImage != NULL )
            {
                //Color key surface
                SDL_SetColorKey( optimizedImage, SDL_RLEACCEL | SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 0, 0, 0xFF ) );
            }
        }
        
        //Return the optimized surface
        return optimizedImage;
    }
    
    void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL )
    {
        //Holds offsets
        SDL_Rect offset;
        
        //Get offsets
        offset.x = x;
        offset.y = y;
        
        //Blit
        SDL_BlitSurface( source, clip, destination, &offset );
    }
    
    bool init()
    {
        //Initialize all SDL subsystems
        if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
        {
            return false;    
        }
        
        //Set up the screen
        screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
        
        //If there was in error in setting up the screen
        if( screen == NULL )
        {
            return false;    
        }
         //Initialize SDL_ttf
        if( TTF_Init() == -1 )
        {
            return false;    
        }
    
        //Set the window caption
        SDL_WM_SetCaption( "o's + x's", NULL );
        
        //If everything initialized fine
        return true;
    }
    
    bool load_files()
    {
        //Load the sprite sheet
        space = load_image( "xox.png" );
        background = load_image ( "background.png" );
        board = load_image ( "board.png" );
          //Open the font
        font = TTF_OpenFont( "ballon.ttf", 50 );
    
        //If there was a problem in loading the sprite
        //if( foo == NULL )
        //{
       //     return false;    
       // }
        //If there was an error in loading the font
        if( font == NULL )
        {
            return false;
        }
        //If everything loaded fine
        return true;
    }
    
    void clean_up()
    {
        //Free the surface
        SDL_FreeSurface( space );
        SDL_FreeSurface (background);
        SDL_FreeSurface (screen);
        SDL_FreeSurface( message );
        SDL_FreeSurface( board );
        //Close the font that was used
        TTF_CloseFont( font );
        
        //Quit SDL_ttf
        TTF_Quit();
      
        //Quit SDL
        SDL_Quit();
    }
    
    Timer::Timer()
    {
        //Initialize the variables
        startTicks = 0;
        pausedTicks = 0;
        paused = false;
        started = false;    
    }
    
    void Timer::start()
    {
        //Start the timer
        started = true;
        
        //Unpause the timer
        paused = false;
        
        //Get the current clock time
        startTicks = SDL_GetTicks();    
    }
    
    void Timer::stop()
    {
        //Stop the timer
        started = false;
        
        //Unpause the timer
        paused = false;    
    }
    
    void Timer::pause()
    {
        //If the timer is running and isn't already paused
        if( ( started == true ) && ( paused == false ) )
        {
            //Pause the timer
            paused = true;
        
            //Calculate the paused ticks
            pausedTicks = SDL_GetTicks() - startTicks;
        }
    }
    
    void Timer::unpause()
    {
        //If the timer is paused
        if( paused == true )
        {
            //Unpause the timer
            paused = false;
        
            //Reset the starting ticks
            startTicks = SDL_GetTicks() - pausedTicks;
            
            //Reset the paused ticks
            pausedTicks = 0;
        }
    }
    
    int Timer::get_ticks()
    {
        //If the timer is running
        if( started == true )
        {
            //If the timer is paused
            if( paused == true )
            {
                //Return the number of ticks when the the timer was paused
                return pausedTicks;
            }
            else
            {
                //Return the current time minus the start time
                return SDL_GetTicks() - startTicks;
            }    
        }
        
        //If the timer isn't running
        return 0;    
    }
    
    bool Timer::is_started()
    {
        return started;    
    }
    
    bool Timer::is_paused()
    {
        return paused;    
    }
    
       
    
    int main( int argc, char* args[] )
    {
    
             //load background
        //Quit flag
        bool quit = false;
     
        //Initialize
        if( init() == false )
        {
           return 1;
        }
         
        //Load the files
        if( load_files() == false )
        {
            return 1;
        }
       
        //Clip the sprite sheet
        clip();
        //The frame rate regulator
        Timer fps;
          
        //While the user hasn't quit
        while( quit == false )
        {
            //Start the frame timer
            fps.start();
        
            //While there's events to handle
            while( SDL_PollEvent( &event ) )
            {                      
               //   //If the user has Xed out the window
                if( event.type == SDL_QUIT )
                {
             //       //Quit the program
                   quit = true;
                }
            }
            
           
            //Fill the screen white
           // SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );
             //load background
          //Render the text 
       // message = TTF_RenderText_Solid( font, word.str().c_str(), textColor );
       //SDL_FreeSurface ( message);
      //problem from here
        int move;
        int num_squares =9;
        vector<char> board (num_squares, empty);
     for( ;;)
        {
       
        instructions ();
        char human = humanpiece();
        char computer = opponent(human);
        char turn = x;
        displayboard (board);
    
    
    board[0]= empty;
    board[1]= empty;
    board[2]= empty;
    board[3]= empty;
    board[4]= empty;
    board[5]= empty;
    board[6]= empty;
    board[7]= empty;
    board[8]= empty;
        while (winner(board) == no_one)
        {
            if (turn == human)
            {
            move = humanmove(board, human);
            board[move] = human;
            }
            else
            {
            move = computermove(board, computer);
            board[move] = computer;
            }
            displayboard(board);
            turn = opponent(turn);
        }
        announcewinner(winner(board), computer, human);
       // apply_surface(0,0,background,screen);
        //apply_surface( (SCREEN_WIDTH - message->w ) / 2, 100, message, screen );
          //system("pause");
            
            
            if( SDL_Flip( screen ) == -1 )
            {
                return 1;    
            }
            
            //Cap the frame rate
            while( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
            {
                //wait...    
            }
        
            
        //Clean up
        clean_up();
        
        return 0;    
    }}}
    //instructions
    void instructions ()
    {
    word <<"welcome to o's and x's";
    
    
    
    SDL_Flip( screen );
    }
    
    // ask if wanna go first
    char askyesno ()
    {
    char response;
    
    
         while( SDL_PollEvent( &event ) )
         {
          if( event.type == SDLK_y)
          {
          response = 'y';
          }
          else if( event.type == SDLK_n)
          {
          response = 'n';
          }
         }
    
    return response;
    }
    int asknumber ()
    {
    int high = 8;
    int low = 0;
        int number;
        do
        {
            word<<"pick a number "<<"("<<low<<"-"<<high<<");";
             while( SDL_PollEvent( &event ) )
             { 
              if( event.type == SDLK_0)
              {
              number = 0;
              }
              else if( event.type == SDLK_1)
              {
              number = 1;
              }
              else if( event.type == SDLK_2)
              {
              number = 2;
              }
              else if( event.type == SDLK_3)
              {
              number = 3;
              }
              else if( event.type == SDLK_4)
              {
              number = 4;
              }
              else if( event.type == SDLK_5)
              {
              number = 5;
              }
              else if( event.type == SDLK_6)
              {
              number = 6;
              }
              else if( event.type == SDLK_7)
              {
              number = 7;
              }
              else if( event.type == SDLK_8)
              {
              number = 8;
              }
              else number = 9;     
            }
        }
        while (number > high || number < low);
        
        return number;
    }
    
    char humanpiece ()
    {
        char go_first = askyesno ();
        if (go_first == 'y')
        {
            word<<"\n then take the first move u will need it.\n";
            return 'x';
        }
        else
        {
            word<<"\n your bravery will be your undoing... i will go first\n";
            return 'o';
        }
    }  
    
    char opponent(char piece)
    {
        if (piece == 'x')
            return 'o';
        else 
            return 'x';
    }
    
    void displayboard (const vector<char>& board)
    {
         if (board[0] == 'x')
        {apply_surface(0,0,space,screen,&pieces[0]);}
    else if (board[0] == 'o')
        {apply_surface(0,0,space,screen,&pieces[1]);}
    else if (board[0] == ' ')
        {apply_surface(0,0,space,screen,&pieces[2]);}
    
         if (board[1] == 'x')
        {apply_surface(50,0,space,screen,&pieces[0]);}
    else if (board[1] == 'o')
        {apply_surface(50,0,space,screen,&pieces[1]);}
    else if (board[1] == ' ')
        {apply_surface(50,0,space,screen,&pieces[2]);}
        
         if (board[2] == 'x')
        {apply_surface(100,0,space,screen,&pieces[0]);}
    else if (board[2] == 'o')
        {apply_surface(100,0,space,screen,&pieces[1]);}
    else if (board[2] == ' ')
        {apply_surface(100,0,space,screen,&pieces[2]);}
    
         if (board[3] == 'x')
        {apply_surface(0,50,space,screen,&pieces[0]);}
    else if (board[3] == 'o')
        {apply_surface(0,50,space,screen,&pieces[1]);}
    else if (board[3] == ' ')
        {apply_surface(0,50,space,screen,&pieces[2]);}
        
         if (board[4] == 'x')
        {apply_surface(50,50,space,screen,&pieces[0]);}
    else if (board[4] == 'o')
        {apply_surface(50,50,space,screen,&pieces[1]);}
    else if (board[4] == ' ')
        {apply_surface(50,50,space,screen,&pieces[2]);}
        
         if (board[5] == 'x')
        {apply_surface(100,50,space,screen,&pieces[0]);}
    else if (board[5] == 'o')
        {apply_surface(100,50,space,screen,&pieces[1]);}
    else if (board[5] == ' ')
        {apply_surface(100,50,space,screen,&pieces[2]);}
        
         if (board[6] == 'x')
        {apply_surface(0,100,space,screen,&pieces[0]);}
    else if (board[6] == 'o')
        {apply_surface(0,100,space,screen,&pieces[1]);}
    else if (board[6] == ' ')
        {apply_surface(0,100,space,screen,&pieces[2]);}
        
        if (board[7] == 'x')
        {apply_surface(50,100,space,screen,&pieces[0]);}
    else if (board[7] == 'o')
        {apply_surface(50,100,space,screen,&pieces[1]);}
    else if (board[7] == ' ')
        {apply_surface(50,100,space,screen,&pieces[2]);}
        
        if (board[8] == 'x')
        {apply_surface(100,100,space,screen,&pieces[0]);}
    else if (board[8] == 'o')
        {apply_surface(100,100,space,screen,&pieces[1]);}
    else if (board[8] == ' ')
        {apply_surface(100,100,space,screen,&pieces[2]);}
        SDL_Flip(screen);
    }
    
    char winner (const vector<char>& board)
    {
        const int winning_rows[8][3] ={ {0, 1, 2},
                                        {3, 4, 5},
                                        {6, 7, 8},
                                        {0, 3, 6},
                                        {1, 4, 7},
                                        {2, 5, 8},
                                        {0, 4, 8},
                                        {2, 4, 6} };
        const int total_rows = 8;
        
        for (int row = 0;row < total_rows;++ row)
        {
        
            if ( (board[winning_rows[row][0]] != empty) &&
                (board[winning_rows[row][0]] == board[winning_rows[row][1]]) &&
                (board[winning_rows[row][1]] == board[winning_rows[row][2]]) )
                {
                return board[winning_rows[row][0]];
                }
        }
        if (count(board.begin(), board.end(), empty) == 0)
            {return tie;}
            
            return no_one;
    }
    
    bool islegal(int move, const vector<char>& board)
    {
        return(board[move] == empty);
    }
    int humanmove (vector<char>& board, char human)
    {
    
        int move = asknumber();
        while (!islegal(move, board))
        {
            word<<"you cant move there\n";
            move = asknumber();
        }
        word<<"fine...\n";
        return move;
    }
    int computermove (vector<char> board, char computer)
    {
        word<<"i will take square number ";
        for (int move = 0; move < board.size (); ++move)
        {
            if (islegal(move, board))
            {
                    board[move] = computer;
                    if (winner(board) == computer)
                    {
                    cout<< move << endl;
                    return move;
                    }
                    board[move] = empty;
            }
        }
        
        char human = opponent(computer);
        
        for (int move = 0; move < board.size(); ++move)
        {
            if (islegal(move, board))
            {
                    board[move] = human;
                    if (winner(board) == human)
                    {
                    word<< move << endl;
                    return move;
                    }
                    board[move] = empty;
            }
        }
        
        const int best_move [] = {4, 0, 2, 6, 8, 1, 3, 5, 7};
        for (int n = 0; n < board.size();)
        {
            int move = best_move[n];
            if (!islegal(move, board))
            {n++;
                    //cout<< move<< endl;
                   // return move;
            }
            else 
            {word<< move<< endl;
            return move;
            }
        }
    }
    
    void announcewinner (char winner, char human, char computer)
    {
        if (winner == human)
        {
        word<<"ha ha ha i won";
        }
        else if (winner == computer)
        {
        word<<"nooooo!! how did you win";
        }
        else
        {
        word<<"we are evanly matched or you was lucky...";
        }
    }

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    1,208
    That is some seriously messed up indenting, and in general, aweful to read code!

    I wont go through that and I dont think anybody else will either. Start from scratch, get a window up and working, then add SMALL pieces of code, press compile and run it to make sure it all works.
    Last edited by Shakti; 05-13-2007 at 03:54 PM.
    STL Util a small headers-only library with various utility functions. Mainly for fun but feedback is welcome.

  4. #4
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434
    Yes, and if you want help with it, show us the lines with errors, (ie Highlight Them ) good luck!
    "Anyone can aspire to greatness if they try hard enough."
    - Me

  5. #5
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    Agreed. We will help but we won't debug the whole program for you.

    Post the offending lines according to your compiler and we will start from there.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help me with my simple Tic tac toe prog
    By maybnxtseasn in forum C Programming
    Replies: 2
    Last Post: 04-04-2009, 06:25 PM
  2. Tic Tac Toe AI help please...
    By Rune Hunter in forum Game Programming
    Replies: 12
    Last Post: 11-05-2004, 03:24 PM
  3. tic tac toe
    By holden in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 05-09-2004, 09:59 AM
  4. Help with Tic Tac Toe game
    By snef73 in forum C++ Programming
    Replies: 1
    Last Post: 04-25-2003, 08:33 AM
  5. Tic Tac Toe Help
    By aresashura in forum C++ Programming
    Replies: 1
    Last Post: 11-21-2001, 11:52 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21