// class Treasure: Models an individual item of treasure: a star // sbj May 1998; updated to Java 1.1 May 1999 import java.awt.*; class Treasure { // The next four lines define the applet game area. // They assume the applet tag says WIDTH=400, HEIGHT=300 // and allow 20 pixel borders at top and bottom for widgets, // and all treasures centred at least 20 pixels from the edge private final int windowWidth = 400; private final int windowHeight = 300; private final int minX = 20, maxX = windowWidth-20;; private final int minY = 40, maxY = windowHeight-40; private final int scale = (int)(Math.random()*19+2); // A random size measure for the treasure icon // Half the star's height in pixels private int[] xs, ys; // To hold the points of the star icon private Color color; // Its colour public boolean collected; // False to start with, then set true when collected public Treasure() { // Constructor: Define a star polygon at a random position color = new Color((int)(Math.random()*256), // Pick a random colour usign RGB coding (int)(Math.random()*256), (int)(Math.random()*256)); collected = false; int baseX = (int) (Math.random()*(maxX-minX)+minX); // Random centre position in window int baseY = (int) (Math.random()*(maxY-minY)+minY); xs = new int[9]; // Set up the star's points at coordinates ys = new int[9]; // (x[0],y[0]), x[1],y[1]), ... etc xs[0] = baseX; xs[1] = baseX+scale/4; xs[2] = baseX+scale; xs[3] = baseX+scale/4; ys[0] = baseY-scale; ys[1] = baseY-scale/4; ys[2] = baseY; ys[3] = baseY+scale/4; xs[4] = baseX; xs[5] = baseX-scale/4; xs[6] = baseX-scale; xs[7] = baseX-scale/4; ys[4] = baseY+scale; ys[5] = baseY+scale/4; ys[6] = baseY; ys[7] = baseY-scale/4; xs[8] = baseX; ys[8] = baseY-scale; } public boolean within(int x, int y) { // Is x, y inside the star? Polygon p = new Polygon(xs, ys, 9); return p.contains(x, y); // contains is method in Polygon library class } public void collect() { // Record that this treasure has been collected collected = true; } public void display(Graphics g) { if (collected) return; // Don't display if already collected g.setColor(color); g.fillPolygon(xs, ys, 9); // The interior g.setColor(Color.black); g.drawPolygon(xs, ys, 9); // The border } } // End of Treasure