# Game matrix bounds checking

• 02-04-2003
Panopticon
Game matrix bounds checking
An AI for a game like connect 4 that uses a game matrix, would it be wise to check bounds using a nested if structure, or are there more efficient alternatives?

e.g:
Code:

```if(x>1&&y>1) { //bounds check if(matrix[y-2][x-2]==1) { //first index. //... } }```
or is it ok to index an array element that does not exist? (renderring the bounds check redundant) I think this will cause the program to crash:

Code:

`matrix[y-2][x-2]; //when x=1 and y=1`
• 02-04-2003
Polymorphic OOP
Re: Game matrix bounds checking
Quote:

Originally posted by Panopticon
An AI for a game like connect 4 that uses a game matrix, would it be wise to check bounds using a nested if structure, or are there more efficient alternatives?

e.g:
Code:

```if(x>1&&y>1) { //bounds check if(matrix[y-2][x-2]==1) { //first index. //... } }```

Can't really say without seeing context. Depending on how you do other things in your code it may be beneficial to take other approaches. Post some more and I can tell you how I would personally handle the situation.

Quote:

Originally posted by Panopticon
or is it ok to index an array element that does not exist? (renderring the bounds check redundant) I think this will cause the program to crash:

Code:

`matrix[y-2][x-2]; //when x=1 and y=1`

Depends on what your definition of "okay" is. In logic it will be wrong, but your example is perfectly valid code which in most cases wouldn't even cause a runtime error. The only times that simply referencing (not writing to) an out-of-bounds index would cause a crash would be if the resultant memory location was 0 or some other invalid memory location.

If, however, you were to attempt to write to an invalid array index, you can't be certain of the result. If the array was on the stack, it could very well just write to another variable on the stack and not know it was doing so, or possibly to something on the heap, or it could crash your program. Obviously, none of which are good.

What it comes down to is just simply don't do it.
• 02-04-2003
Panopticon
In context, Im asking this question because Im writing a simple connect 4 game and I feel the following is inefficient.
Code:

```//finds ascending positive gradient threats if(i<5&&j<5) { //check bounds if(matrix[j+1][i+1]==1&&matrix[j+2][i+2]==1&& matrix[j+3][i+3]==1) { setcounter(i,j); return true; } }```
As you could imagine, for an algorithm of this type, there are countless more possible moves the ai must account for, and everytime i must have at least a 2 level nested if to suit the bounds checking.

Im sure there are other more efficient alternatives.

edit: the matrix is int matrix[8][8] where 0 indicates empty, 1 indicates player counter, and 2 indicates computer counter