This is the update loop for the game I’m working on:
public void update() {
Jukebox.play(currSong, true);
for (int i = 0; i < spawners.size(); i++)
spawners.get(i).update();
for (int i = 0; i < decorations.size(); i++)
decorations.get(i).update();
removeSpawners();
removeDecorations();
if (levelUp) {
if (count++ == 60 * 3)
loadNextGameState();
return;
}
if(player.getState() instanceof StatePrimaryPlayerDead) {
if (count++ == 60 * 2)
loadNextGameState();
return;
}
player.update();
if (forceField != null) forceField.update();
for (int i = 0; i < balls.size(); i++)
balls.get(i).update();
int numBricks = 0;
for (int i = 0; i < bricks.size(); i++) {
bricks.get(i).update();
if (bricks.get(i).getState() instanceof BrickDestructibleState) numBricks++;
}
if (numBricks == 0) levelUp = true;
for (int i = 0; i < powerups.size(); i++)
powerups.get(i).update();
for (int i = 0; i < projectiles.size(); i++)
projectiles.get(i).update();
checkMobCollision();
removeTargets();
removeBalls();
removePowerups();
removeProjectiles();
removeForceField();
if (balls.size() == 0) {
if (!(player.getState() instanceof StatePrimaryPlayerDead)) {
player.setState(new StatePrimaryPlayerDead().init(player));
addSpawner(new ParticleSpawner(player.getx() + player.getWidth() / 2,
player.gety() + player.getHeight() / 2, 100));
}
}
}
It uses the “instanceof” keyword 3 times, and is used another 3 times in other methods of the same class. In every case it is to detect the state of an entity. I really don’t like coupling the loop to external code like that, but I can’t think of a way to detect entity states without using “instanceof”, and I was looking for suggestions on what to do, as I feel that such extended use of “instanceof” smells of bad design. Any suggestions are greatly appreciated!