Main.java (1674B)
1 import java.util.Random; 2 3 public class Main { 4 static int width, height; 5 static Random random; 6 7 private static void moveball(Circle c) { 8 if (c.getX() >= width || c.getX() <= 0) 9 c.setDx(-c.getDx()); 10 if (c.getY() >= height || c.getY() <= 0) 11 c.setDy(-c.getDy()); 12 c.move(); 13 } 14 15 private static boolean istouching(Circle c1, Circle c2) { 16 int rad = c2.getDiamiter() / 4; 17 int upperX = (c2.getX()) + rad; 18 int lowerX = (c2.getX()) - rad; 19 int upperY = (c2.getY()) + rad; 20 int lowerY = (c2.getY()) - rad; 21 22 return ((c1.getX() <= upperX && c1.getX() >= lowerX) 23 || (c1.getY() <= upperY && c1.getY() >= lowerY)); 24 } 25 26 public static void main(String[] args) { 27 Canvas canvas = Canvas.getCanvas(); 28 width = canvas.getWidth(); 29 height = canvas.getHeight(); 30 random = new Random(); 31 32 Circle c1 = new Circle(); 33 Circle c2 = new Circle(); 34 35 c1.changeColor("brown"); 36 c1.makeVisible(); 37 38 c2.changeColor("green"); 39 c2.makeVisible(); 40 41 for (;;) { 42 if (istouching(c1, c2)) { 43 c1.setDx(-c1.getDx() + random.nextInt() % 3); 44 c1.setDy(-c1.getDy() + random.nextInt() % 3); 45 c2.setDx(-c2.getDx() + random.nextInt() % 3); 46 c2.setDy(-c2.getDy() + random.nextInt() % 3); 47 moveball(c1); 48 moveball(c2); 49 } 50 51 if (istouching(c2, c1)) { 52 c1.setDx(-c1.getDx() + random.nextInt() % 3); 53 c1.setDy(-c1.getDy() + random.nextInt() % 3); 54 c2.setDx(-c2.getDx() + random.nextInt() % 3); 55 c2.setDy(-c2.getDy() + random.nextInt() % 3); 56 moveball(c1); 57 moveball(c2); 58 } 59 60 moveball(c1); 61 moveball(c2); 62 63 64 c1.setDx(c1.getDx() % 10); 65 c1.setDy(c1.getDy() % 10); 66 c2.setDx(c1.getDx() % 10); 67 c2.setDy(c1.getDy() % 10); 68 } 69 } 70 }