// Representation of a fish import java.awt.*; import java.util.*; public class Fish implements Drawable { // instance variables Color fishColor; Polygon fishShape; int currentX; int currentY; // Fish(): default constructor public Fish() { Fish fish = makeRandomColoredFish(); setColor(fish.getColor()); setShape(fish.getShape()); setPosition(fish.getX(), fish.getY()); } // Fish(): constructor for specified color, shape, and position public Fish(Color c, Polygon p, int x, int y) { setColor(c); setShape(p); setPosition(x, y); } // getColor(): returns the color of the fish public Color getColor() { return fishColor; } // setColor(): sets the color of the fish to c public void setColor(Color c) { fishColor = c; } // getShape(): returns the shape of the fish public Polygon getShape() { return fishShape; } // setShape(): sets the shape of the fish to a clone of p public void setShape(Polygon p) { fishShape = new Polygon(p.xpoints, p.ypoints, p.npoints); } // getX(): returns the fish’s x-coordinate position public int getX() { return currentX; } // setX(): sets the fish’s x-coordinate position public void setX(int x) { currentX = x; } // getY(): returns the fish’s y-coordinate position public int getY() { return currentY; } // setY(): sets the fish’s y-coordinate position public void setY(int y) { currentY = y; } // setPosition(): sets the fish’s x- and y-coordinate position public void setPosition(int x, int y) { setX(x); setY(y); } // paint(): draws the fish in graphical context g public void paint(Graphics g) { Polygon p = getShape(); int[] x = (int[]) p.xpoints.clone(); int[] y = (int[]) p.ypoints.clone(); int n = p.npoints; for (int i = 0; i < n; ++i) { x[i] += getX(); y[i] += getY(); } p = new Polygon(x, y, n); Color c = getColor(); g.setColor(c); g.fillPolygon(p); } // makeRandomColoredFish(): create fish with random color public static Fish makeRandomColoredFish() { int[] x = { 0, 30, 40, 50, 60, 70, 90, 100, 115, 130, 115, 100, 90, 70, 60, 50, 40, 30, 0, 15 }; int[] y = { 5, 15, 10, 7, 0, 7, 12, 15, 22, 25, 28, 35, 40, 43, 50, 43, 40, 35, 45, 25 }; Random die = new Random(); int red = die.nextInt(255); int yellow = die.nextInt(255); int green = die.nextInt(255); Color c = new Color(red, yellow, green); Polygon p = new Polygon(x, y, x.length); return new Fish(c, p, 0, 0); } }