Task: it is necessary to implement AI when playing tic-tac-toe on Java. The very first step is a random cell selection and verification of neighboring cells for, say, zeroes. implemented in the forehead:

if (map[i+1][j] == DOT_O || map[i+1][j+1] == DOT_O || map[i+1][j-1] == DOT_O || map[i][j+1] == DOT_O || map[i][j-1] == DOT_O || map[i-1][j] == DOT_O || map[i-1][j+1] == DOT_O || map[i-1][j-1] == DOT_O ) { x = i; y = j; } 

but there was an error right away, because when accessing a cell of type i + 1, you can go beyond the edge of the array. Now I myself do not understand how to approach the problem. Help, please.

  • Usually in such games they do not check ALL winning options after each move, but only for the last move. Of course, if classic X-0 (3x3) is okay, but if you want to make the field 100500x100500, then it is more logical to check only the vertical-horizontal-diagonal only from the last move. - Olexiy Morenets

2 answers 2

 boolean checkNearCell(int row, int col, int val) { int startRow = Math.max(row - 1, 0); int stopRow = Math.min(row + 1, map.length - 1); for (int i = startRow; i <= stopRow; i++) { int startCol = Math.max(col - 1, 0); int stopCol = Math.min(col + 1, map[i].length - 1); for (int j = startCol; j <= stopCol; j++) { if (map[i][j] == val && !(i == row && j == col)) return true; } } return false; } if (checkNearCell(i, j, DOT_O) { x = i; y = j; } 

    I decided all the same to the forehead, just before each check "or" added check "and" on (i + 1 <SIZE), i.e. that would not check the cell with the coordinate outside the array. thank.