I have already done most of the program, ask the user for the move, see if it is a valid move, make the move, test if the perimeter is full, etc... but now I see myself troubled with testing if someone has won the game, I could just make a lot of if and else if and test all the possible winning moves, but I would like to know if there is any better way.

The board is represented by a 2D array called board, 9 columns, 9 rows (board[9][9]), player 1's pieces are represented with the ascII code 88 and player 2's pieces with 79, if there is 4 88 in board[0][0], [0][1], [0][2], and [0][3] the player 1 would win, the same would be with diagonals: board[0][0], [1][1], [2][2], [3][3]. As I said, I suppose I can make it with a lot of ifs, but I would like to know if there is a better way.

Thank you.

Recommended Answers

All 2 Replies

yes you can try something like this

bool isAWin(char &winner)
{
    if(isWin('O'))   /*considering your players as X and O (change to whatever u are using)*/
    {
           winner = 'O';
           return true;
     }
    if(isWin('X'))
    {
           winner = 'X';
           return true;
     }
     winner = ' ';
     return false;
}

bool isWin(char player)
{
     if(isWinRow(player))
           return true;
    if(isWinCol(player))
           return true;
     if(isWinDiag(player))
           return true;
     return false;
}

bool isWinRow(char player)
{
      int r, c;
      bool win;
      for(r=0;r<rows;r++) /*rows considered to have number of rows*/
      {
             win = true;
             for(c=0;c<cols;c++)/*rows considered to have number of rows*/
             {
                   if(board[r][c] != player)
                   {
                          win = false;
                          break;
                    }
             }
              if(win)
                    return true;
       }
       return false;
}
bool isWinCol(char player)
{
   /* do it yourself*/
}
bool isWinDiag(char player)
{
   /*do it yourself*/
}

Thank you for the help, you enlightened me :P.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.