vendredi 29 mai 2015

Avoiding use of instance of:

I'm writing a simple game where we have a collection of objects where a player moves around on a grid, collecting coin and avoid monsters.

My class structure looks as follows.

Game Controller - Reponsible for spawing coins and tracking game state

Grid - A class which stores the objects which are currently on the grid, and a few grid related methods.

GridObject - An abstract class representing an object on the grid. e.g. player, monster or coin.

Player, Monster, Coin - All extend GridObject.

My question is what is the most OOP way to program collision handling. The desired result is: Player hits Monster - end game, Player hits Coin - increase score, Monster hits Coin - nothing.

At present, when a GridObject moves, it notifies the board object that it wants to move, if this will cause a collision, I call a handler on the GameController (through a listener pattern), to handle the collision. In that handler, which takes two GridObjects as parameters, I'm using a lot of "instanceof" commands to distinguish the above cases.

What is the best way to avoid using all this "instanceof", which I have read usually means bad design.

Thanks for any input!

Will

Aucun commentaire:

Enregistrer un commentaire