Question
How to not copy the code, but create one method?
I have a method
private void positionMagican() {
int x;
int y;
boolean magicanIsCreated;
magicanIsCreated = false;
while (!magicanIsCreated){
x = random.nextInt(sizeX);
y = random.nextInt(sizeY);
if(field.getFieldable(x,y) instanceof Empty){
mag = new Magician(x,y,sizeX,sizeY,field,player,this);
field.setFieldable(x,y,mag);
magicanIsCreated = true;
}
}
}
And exactly the same methods, but instead of Magican there is a snake, barrels, etc.
Here's an example
private void positionGoblin() {
int x;
int y;
boolean goblinIsCreated;
goblinIsCreated = false;
while (!goblinIsCreated){
x = random.nextInt(sizeX);
y = random.nextInt(sizeY);
if(field.getFieldable(x,y) instanceof Empty){
goblin = new Goblin(x,y,player,field,this,sizeX,sizeY);
field.setFieldable(x,y,goblin);
goblinIsCreated = true;
}
}
} ```
Here the differences are only in the class of the object and in its parameters, because of this there are many of the same methods in the project, and I don’t understand how to create one method into which the desired parameter could be entered. Is it possible to create a method that combines these methods? I don't understand. How to ensure that an object is created of the required class with the required parameters.