Java – how to avoid instanceof calls?

I defined this simple method:

public static boolean isBorder(int x,int y) throws CollisionDetectionException {
        try {
            if ( (levelItems[x][y] instanceof StaticGameObject && levelItems[x][y].isVisible()) ||
                (levelItems[x-1][y] instanceof StaticGameObject && levelItems[x-1][y].isVisible()) ||
                (levelItems[x][y+1] instanceof StaticGameObject && levelItems[x][y+1].isVisible()) ||
                (levelItems[x][y-1] instanceof StaticGameObject && levelItems[x][y-1].isVisible()) ||
                (levelItems[x-1][y-1] instanceof StaticGameObject && levelItems[x-1][y-1].isVisible()) ||
                (levelItems[x-1][y+1] instanceof StaticGameObject &&levelItems[x-1][y+1].isVisible()) ||
                (levelItems[x+1][y] instanceof StaticGameObject && levelItems[x+1][y].isVisible()) ||
                (levelItems[x+1][y+1] instanceof StaticGameObject && levelItems[x+1][y+1].isVisible()) ||
                (levelItems[x+1][y-1] instanceof StaticGameObject && levelItems[x+1][y-1].isVisible()) ) {
                return true;
            } else {
                return false;
            } 
        } catch (Arrayindexoutofboundsexception e) {
            throw new CollisionDetectionException("Collision Couldn't be checked because checking position " + x + "/" + y + " caluclated values below (0/0)");
        }
    }

As you can see, I have a two - dimensional array Now I want to check for a specific location ((x / y) – > method parameters) if there are any visible staticgameobjects in the adjacent fields of the 2-dimensional array

The levelitems array consists of so - called GameObjects Staticgameobject is a direct subclass of GameObject

Any tips on how to improve this method?

Solution

Add method to GameObject

bool isBorderObject() { return false; }

Then override in staticgameobject

bool isBorderObject() { return true; }

Change test to

(levelItems[x][y].isBorderObject() && levelItems[x][y].isVisible())

In addition, if may be nested

for (int i = x-1; i <= x+1; ++i) {
   for (int j = y-1; j <= y+1; ++j) {
       GameObject item = levelItems[i][j];
       if (item.isBorderObject() && item.isVisible()) 
           return true;
   }
}
return false;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>