I am trying to check for a win in a connect 4 game, I managed to check diagonall right, But I need help with checking diagonally left, vertically and horizontally, Its a matter of changing the algorithm I have already created and tweaking it. How do you check vertically, horizontally and diagonally left?
public class Game {
private static final int COLS = 7;
private static final int ROWS = 6;
public State[][] count = new State[COLS][ROWS];
boolean player1Turn = true;
public static final int LEN = 4;
protected Context context;
public enum State {
RED, YELLOW, BLANK;
}
public State checkWinner() {
for (int col = 0; col < count.length; ++col) {
for (int row = 0; row < count[col].length; ++row) {
State result = checkWinner(col, row);
if (result != null) {
return result;
}
}
}
return null;
}
//This method is called in a another class
public State checkWinner(int col, int row) {
State cell = count[col][row];
if (cell == null || cell == State.BLANK) {
return null;
}
// Here I am checking for a win Diagonally Right
// The next step is to check vertically and horizontelly and Diagnollly left
// There needs to be a pattern of four reds or yellow counters either horizontelly or vertically
// My guess to check horizentally or vertically and diagonally left would be to copy this algorithm and possibly change the coordinates
// Checking four up for horizontal and four across for vertical, four for diagnoally left
if ((col + LEN <= COLS) && (row + LEN <= ROWS)) {
boolean same = true;
for (int i = 1; i < LEN; ++i) {
if (count[col + i][row + i] != cell) {
same = false;
break;
}
}
if (same) {
return cell;
}
}
// TODO Auto-generated method stub
return null;
}
}