For my project we have to have four square moving and bouncing off the sides and when it hits a side it changes color. When you click on one of the squares it freezes and turns red. So far i have the four squares and when I click them it says it freezes them. However, I'm not positive how to get them to move and bounce off the sides. Below is the code i have written so far.
MAIN:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StationarySquare[] squares = new StationarySquare[4];
Random rng = new Random();
for (int i = 0; i < squares.length; i++) {
squares[i] = new StationarySquare(rng.nextDouble(), rng.nextDouble());
}
while (true) {
StdDraw.clear();
int count = 0;
for (int i = 0; i < squares.length; i++) {
squares[i].draw();
if (StdDraw.mousePressed()
&& squares[i].containsPoint(StdDraw.mouseX(), StdDraw.mouseY())) {
squares[i].freeze();
}
if (squares[i].isFrozen()) {
count++;
}
}
StdDraw.text(0.5, 0.5, "Frozen: " + count);
StdDraw.show(25);
}
}
}
My other class
import java.util.Random;
public class StationarySquare {
private double x;
private double y;
private double halfLength;
private int red;
private int green;
private int blue;
private boolean isFrozen;
public StationarySquare(double x, double y) {
this.x = x;
this.y = y;
halfLength = 0.1;
isFrozen = false;
randomColor();
}
public void draw() {
if (isFrozen) {
StdDraw.setPenColor(StdDraw.RED);
} else {
StdDraw.setPenColor(red, green, blue);
}
StdDraw.filledSquare(x, y, halfLength);
}
public void randomColor() {
Random rng = new Random();
red = rng.nextInt(256);
green = rng.nextInt(256);
blue = rng.nextInt(256);
}
public void freeze() {
isFrozen = true;
}
public boolean containsPoint(double a, double b) {
return a > x - halfLength &&
a < x + halfLength &&
b > y - halfLength &&
b < y + halfLength;
}
public boolean isFrozen() {
return isFrozen;
}
}