I'm currently developing a simple game (Flood-It) using the Model-View-Controller design pattern.
I have a segment of code which takes the (x, y) coordinates of a given point and checks for a certain Boolean in the strictly adjacent points, i.e. directly up, down, left, right, then executing certain operations with said point if boolean is true.
A sufficient implementation using if statements:
if (point(x-1, y).getBoolean()) { // Left
point(x-1,y).set(args);
Stack.push(point(x-1,y);
}
if (point(x+1, y).getBoolean()) { // Right
//...
}
if (point(x, y-1).getBoolean()) { // Down
//...
}
if (point(x, y+1).getBoolean()) { // Up
//...
}
I'd like to know if there's a tighter way to do this. Even if it is just 4 if statements it is quite redundant. I've tried for
loop iterations but none have been more efficient than the if statements.
Here are the conditions:
- Check only the directly adjacent points, no diagonals and not the point itsself.
- Execute the operations (set method, add to stack) only if the point object getter returns true.
- Brownie points if unnecessary checks are excluded (i.e. top right selected would only check below and to the left). Assume square grid with each axis being from 0 to
int size
.
Thanks in advance.