cs151/hw4/src/CarShape.java
2025-04-19 16:36:31 -07:00

78 lines
2.4 KiB
Java

import java.awt.*;
import java.awt.geom.*;
/**
* A car shape.
* Partially taken from the textbook (Cay S. Horstmann - OO Design & Patterns, 2nd ed.)
*/
public class CarShape implements CompositeShape {
private final int x; // Base x-coordinate (relative to drawing origin)
private final int y; // Base y-coordinate (relative to drawing origin)
private final int width;
public CarShape() {
this(0, 0, 60); // Default position and width
}
/**
* Constructs a car shape.
*
* @param x the left of the bounding rectangle
* @param y the top of the bounding rectangle
* @param width the width of the bounding rectangle
*/
public CarShape(int x, int y, int width) {
this.x = x;
this.y = y;
this.width = width;
}
@Override
public int getWidth() {
return width; // Width of the car body
}
@Override
public int getHeight() {
// Approximate height: body height + wheel radius
return width / 2 + width / 6;
}
@Override
public void draw(Graphics2D g2) {
Rectangle2D.Double body = new Rectangle2D.Double(x, y + width / 6.0, width - 1, width / 6.0);
Ellipse2D.Double frontTire = new Ellipse2D.Double(
x + width / 6.0,
y + width / 3.0,
width / 6.0,
width / 6.0
);
Ellipse2D.Double rearTire = new Ellipse2D.Double(
x + width * 2 / 3.0,
y + width / 3.0,
width / 6.0,
width / 6.0
);
// The bottom of the front windshield
Point2D.Double r1 = new Point2D.Double(x + width / 6.0, y + width / 6.0);
// The front of the roof
Point2D.Double r2 = new Point2D.Double(x + width / 3.0, y);
// The rear of the roof
Point2D.Double r3 = new Point2D.Double(x + width * 2 / 3.0, y);
// The bottom of the rear windshield
Point2D.Double r4 = new Point2D.Double(x + width * 5 / 6.0, y + width / 6.0);
Line2D.Double frontWindshield = new Line2D.Double(r1, r2);
Line2D.Double roofTop = new Line2D.Double(r2, r3);
Line2D.Double rearWindshield = new Line2D.Double(r3, r4);
// Draw the parts
g2.draw(body);
g2.draw(frontTire);
g2.draw(rearTire);
g2.draw(frontWindshield);
g2.draw(roofTop);
g2.draw(rearWindshield);
}
}