1

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.

Oliver Benning
  • 1,281
  • 2
  • 8
  • 14
  • Why would you think a tighter approach should be taken? This code satisfies all of your requirements; unless you're thinking about breaking them out into separate functions (or even separate `BiFunction`s), this seems to be as good as you'd want to get. – Makoto Mar 10 '17 at 00:58
  • http://stackoverflow.com/a/929781/4280359 – Grzegorz Górkiewicz Mar 10 '17 at 00:58
  • @Makoto because I anticipate much adding more into the body of each if statement in the future. – Oliver Benning Mar 10 '17 at 01:00
  • So it sounds like they need to be separate functions, then. Especially if you're considering expanding what they do. If nothing else, it'll make your code more readable. – Makoto Mar 10 '17 at 01:02

0 Answers0