I've recently begun to learn the concepts of OOP in Java, and have started building a game which involves a ball and pegs scattered around a screen. The aim of this game is to remove all the pegs off the screen by having the ball collide with them. There are different types of pegs which have certain behaviours when they are destroyed. (I.e. black pegs can't be destroyed, red pegs spawn two new balls etc.)
The following method is what I am using to check for collisions between the ball and the peg by iterating through each peg in an ArrayList. If a collision is detected, the peg will execute an action before getting removed from the ArrayList.
// inside MainGame class
public void checkCollisions(Ball ball) {
for (GameObject peg: pegs) {
if (peg.checkCollision(ball)) {
// peg does something before getting removed from the ArrayList
}
}
}
My first approach was to have a bunch of if statements to check the type of the peg using instanceOf, but although it may work for a small game like mine with very few peg types, I doubt that this solution would work elegantly in a game with many different types of game objects such as an RPG.
What if some types couldn't be destroyed (such as the black peg), or that it affected other pegs around it?
I'm trying to find a flexible solution which would make it easy to add "death" behaviours which could potentially affect/create other pegs / game objects, but I am unaware of a design pattern which addresses this problem and would love some tips/resources that could aid me with this question.