I am writing a window in which circles \ squares must constantly move. Only circles \ squares are shown, but at this time other figures are moving.

(here's the source git: https://github.com/Kaper156/MovingFigures )

I decided to add classes of standard shapes (MovingCircle, MovingSquare) and implement in them the direction and calculation of the next point (as well as the change of direction in the collision).

The problem is this: I had to write two almost identical classes (MovingCircle, MovingSquare) , which complement Ellipse2d.Double and Rectangle2d.Double respectively. How to make common for these two classes "shifter"? After all, the coordinates and dimensions I need are available only in the latest implementation.

public class MovingSquare extends Rectangle2D.Double implements MovingFigure { private float angle; public Color color; MovingSquare() { Random r = new Random(); this.width = this.height = r.nextInt(20) + 5; this.angle = r.nextFloat() * 360; this.x = width * 3 + r.nextDouble() * (CANVAS_W - width * 6); this.y = height * 3 + r.nextDouble() * (CANVAS_H - height * 6); this.color = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()); } public void MoveSelf() { x = x + Math.cos(angle * Math.PI / 180) * SPEED; y = y + Math.sin(angle * Math.PI / 180) * SPEED; if (x <= this.width || x >= CANVAS_W - width * 2) { angle = 180 - angle; } if (y <= this.height || y >= CANVAS_H - height * 2) { angle = 360 - angle; } } } public class MovingCircle extends Ellipse2D.Double implements MovingFigure { private float angle; public Color color; MovingCircle() { Random r = new Random(); this.width = this.height = r.nextInt(20) + 5; this.angle = r.nextFloat() * 360; this.x = width * 3 + r.nextDouble() * (CANVAS_W - width * 6); this.y = height * 3 + r.nextDouble() * (CANVAS_H - height * 6); this.color = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()); } public void MoveSelf() { x = x + Math.cos(angle * Math.PI / 180) * SPEED; y = y + Math.sin(angle * Math.PI / 180) * SPEED; //TODO radius if (x <= this.width || x >= CANVAS_W - width * 2) { angle = 180 - angle; } if (y <= this.height || y >= CANVAS_H - height * 2) { angle = 360 - angle; } } } 
  • Will it be correct to create two appropriate classes (ExtCircle, ExtSquare) that will have a link to MovingFigure (there will be a duplicate code in it)? - Kar Ner
  • And who should know how to move the figure? - Chad
  • The figures move in the same way (I didn’t begin to separate apart the contact between the radius of the circle and the wall of the square). Displacements are calculated for each shape when redrawing. The panel owns two lists of these figures - Kar Ner

1 answer 1

I would take a look at the generic tars, and define the base class, indicating the shape as a generic parameter.

  • I can not turn to the generic fields, maybe there are more options? - Kar Ner
  • And why not the opportunity? - Chad