Connect 4 building methods suggestions?

Started by
11 comments, last by alvaro 9 years, 5 months ago
I understand you are putting some real effort into this, but you just ignored my advice to make those variables into an array and get rid of repetitive code.

About detecting four in a row, can you describe how you would do it in English? Maybe we can help you translate that into code.
Advertisement

You ought to fix what Alvaro mentioned - this will not only make your code shorter and easier to handle, but it will add the additional possibility of using a board with more than 6 rows.

About checking whether there are number pieces in a row/column/diagonally you could try this:


//Let's say you just put a new piece with coordinates x,y and it's color is col then:
if( countPieces(x,y,col, -1, 0) + countPieces(x,y,col, 1, 0) - 1 >= number )
{
   //4 in a row
}
if( countPieces(x,y,col, 0, -1) + countPieces(x,y,col, 0, 1) - 1 >= number )
{
   //4 in a column
}
if( countPieces(x,y,col, 1, 1) + countPieces(x,y,col, -1, -1) - 1 >= number )
{
   //4 diagonally
}
if( countPieces(x,y,col, -1, 1) + countPieces(x,y,col, 1, -1) - 1 >= number )
{
    //4 diagonally
}

What this does is basically check the number of pieces left of your new piece with color == col then adds this number with the number of pieces right of your new piece with color == col and subtracts 1 because we counted the new piece twice. If this number proves to be higher or equal to number(=4) then we have 4 or more pieces in the row with the same color. Analogically for the other cases.

lightxbulb's code is probably fine, but while you are learning how to get rid of repetitive code, here's another idea:
bool Board::is_last_move_a_win(int x, int y) const {
  int dx_table[4] = {1, 0, 1, -1};
  int dy_table[4] = {0, 1, 1, 1};
  
  for (int d = 0; d < 4; ++d) {
    int dx = dx_table[d];
    int dy = dy_table[d];
      if(countPieces(x, y, dx, dy) + countPieces(x, y, -dx, -dy) >= 3)
        return true;
  }
  
  return false;
}

This topic is closed to new replies.

Advertisement