Thread: checking for win in tic tac toe

  1. #1
    Unregistered Leeman_s's Avatar
    Join Date
    Oct 2001
    Posts
    753

    checking for win in tic tac toe

    in my last tic tac toe game, checking for the win was very primative. my board array is set up like this:

    [1,1] [1,2] [1,3]
    [2,1] [2,2] [2,3]
    [3,1] [3,2] [3,3]

    this is how my old checkforwin looked:
    Code:
    void checkforwin()
    	{
    		int w=1;
    		char d='X';
    		win=0;
    		for(int p=1;p<=2;p++)
    		{
    			if(p==2)
    			{
    				d='O';
    				w=2;
    			}
    		for(int g=1;g<4;g++)
    		{
    			if(board[1][g]==d && board[2][g]==d && board[3][g]==d)
    			{
    				win=w;
    			}
    		}
    		for(int t=1;t<4;t++)
    		{
    			if(board[t][1]==d && board[t][2]==d && board[t][3]==d)
    			{
    				win=w;
    			}
    		}
    		if(board[1][1]==d && board[2][2]==d && board[3][3]==d)
    		{
    			win=w;
    		}
    		if(board[3][1]==d && board[2][2]==d && board[1][3]==d)
    		{
    			win=w;
    		}
    		}
    	}
    im thinking of this: perhaps i could search the array for x (or 0), and then see if it is in a line or something. just anything better than what is above. also, sorry for so much posting.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Break it down into its component steps
    Code:
    #define BOARD   3
    
    // checks all rows
    int checkboardrow ( int board[BOARD][BOARD], int player ) {
        int win = 1;
        int row, col;
        for ( row = 0 ; row < BOARD && win ; row++ ) {
            for ( col = 0 ; col < BOARD && win ; col++ ) {
                if ( board[row][col] != player ) win = 0;
            }
        }
        return win;
    }
    
    // checks all rows, cols and diagonals
    int checkboard ( int board[BOARD][BOARD], int player ) {
        return checkboardrow(board,player) ||   // checks all rows
               checkboardcol(board,player) ||   // checks all cols
               checkboardleft(board,player)||   // checks left diagonal
               checkboardright(board,player);   // checks right diagonal
    }

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 program
    By muzihc in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 08:08 PM
  3. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  4. Problems about gcc installation
    By kevin_cat in forum Linux Programming
    Replies: 4
    Last Post: 08-09-2005, 09:05 AM
  5. Help with Tic Tac Toe game
    By snef73 in forum C++ Programming
    Replies: 1
    Last Post: 04-25-2003, 08:33 AM