| CSCI A201/A597Solutions Assignment Ten: Packing Bins |
import element.*;
public class hw10 {
public static void main(String[] args) {
Circle[] circles = new Circle[100];
DrawingWindow d = new DrawingWindow();
d.invertMode();
Rect bin= new Rect(10, 10, 130, 180);
d.draw(bin);
int radius = (int)(Math.random() * 20 + 10);
Pt start = new Pt(175, 175);
Circle c = new Circle(start, radius);
d.draw(c);
boolean gameOn = true;
int number = 0;
int score = 0;
Library.showScore(d, score);
while (gameOn) {
d.awaitMousePress();
while (d.mousePressed()) {
Pt m = d.getMouse();
d.draw(c);
c.center(m);
d.draw(c);
}
boolean placementOK = true;
Rect vb = new Rect(bin.left() + c.radius(),
bin.top() + c.radius(),
bin.width() - 2 * c.radius(),
bin.height() - 2 * c.radius());
if (!vb.contains(c.center())) {
placementOK = false;
gameOn = false;
}
for (int i = 0; i < number; i++) {
if (Library.overlap(c, circles[i])) {
placementOK = false;
}
}
if (placementOK) {
score += Math.PI * c.radius() * c.radius();
Library.showScore(d, score);
circles[number] = c;
number += 1;
d.fill(c);
radius = (int)(Math.random() * 20 + 10);
c = new Circle(start, radius);
d.draw(c);
} else {
d.draw(c);
c.center(start);
d.draw(c);
}
}
System.out.println("Thanks for playing, your final score was: " +
score);
Pt m = d.awaitMouseClick();
System.exit(0);
}
}
class Library {
public static void showScore(DrawingWindow d, int score) {
Rect scoreBox = new Rect(150, 30, 40, 20);
d.paintMode();
d.clear(scoreBox);
d.draw(scoreBox);
Text t = new Text(score);
t.center(scoreBox.center());
d.draw(t);
d.invertMode();
}
public static boolean overlap(Circle a, Circle b) {
return Library.distance(a.center(), b.center()) <
a.radius() + b.radius();
}
public static double distance(Pt a, Pt b) {
int h = a.x() - b.x(),
v = a.y() - b.y();
return Math.sqrt(h * h + v * v);
}
}