001package horstmann.ch06_car;
002import java.awt.Graphics2D;
003import java.awt.geom.Ellipse2D;
004import java.awt.geom.Line2D;
005import java.awt.geom.Point2D;
006import java.awt.geom.Rectangle2D;
007
008/**
009   A car shape.
010 */
011public class CarShape
012{
013        /**
014      Constructs a car shape.
015      @param x the left of the bounding rectangle
016      @param y the top of the bounding rectangle
017      @param width the width of the bounding rectangle
018         */
019        public CarShape(int x, int y, int width)
020        {
021                this.x = x;
022                this.y = y;
023                this.width = width;
024        }
025
026        public void draw(Graphics2D g2)
027        {
028                Rectangle2D.Double body
029                = new Rectangle2D.Double(x, y + width / 6,
030                                width - 1, width / 6);
031                Ellipse2D.Double frontTire
032                = new Ellipse2D.Double(x + width / 6, y + width / 3,
033                                width / 6, width / 6);
034                Ellipse2D.Double rearTire
035                = new Ellipse2D.Double(x + width * 2 / 3,
036                                y + width / 3,
037                                width / 6, width / 6);
038
039                // The bottom of the front windshield
040                Point2D.Double r1
041                = new Point2D.Double(x + width / 6, y + width / 6);
042                // The front of the roof
043                Point2D.Double r2
044                = new Point2D.Double(x + width / 3, y);
045                // The rear of the roof
046                Point2D.Double r3
047                = new Point2D.Double(x + width * 2 / 3, y);
048                // The bottom of the rear windshield
049                Point2D.Double r4
050                = new Point2D.Double(x + width * 5 / 6, y + width / 6);
051                Line2D.Double frontWindshield
052                = new Line2D.Double(r1, r2);
053                Line2D.Double roofTop
054                = new Line2D.Double(r2, r3);
055                Line2D.Double rearWindshield
056                = new Line2D.Double(r3, r4);
057
058                g2.draw(body);
059                g2.draw(frontTire);
060                g2.draw(rearTire);
061                g2.draw(frontWindshield);
062                g2.draw(roofTop);
063                g2.draw(rearWindshield);
064        }
065
066        public boolean contains(Point2D p)
067        {
068                return x <= p.getX() && p.getX() <= x + width
069                                && y <= p.getY() && p.getY() <= y + width / 2;
070        }
071
072        public void translate(int dx, int dy)
073        {
074                x += dx;
075                y += dy;
076        }
077
078        private int x;
079        private int y;
080        private int width;
081}