我正在开展一个项目,我们应该让随机大小的矩形从墙上反弹,并在每次反弹时改变颜色。
当你点击它们时,它们应该冻结到位并变成红色。我只是在让它们停下来时遇到麻烦,因为某些原因它们在点击时会变慢。
import java.util.Random;
public class Main {
public static void main(String[] args) {
MovingRectangles[] rectangles = new MovingRectangles[5];
Random rng = new Random();
for (int i = 0; i < rectangles.length; i++) {
rectangles[i] = new MovingRectangles(rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble(), rng.nextDouble());
}
for (int g = 0; g < rectangles.length; g++) {
rectangles[g] = new MovingRectangles(
rng.nextDouble(),
rng.nextDouble(),
rng.nextDouble() / 50 - 0.01,
rng.nextDouble() / 50 - 0.01,
rng.nextDouble() * 0.04 + 0.03,
rng.nextDouble() * 0.04 + 0.03
);
}
while (true) {
StdDraw.clear();
for (int h = 0; h < rectangles.length; h++) {
rectangles[h].draw();
rectangles[h].update();
}
int count = 0;
for (int i =0; i < rectangles.length; i++) {
rectangles[i].draw();
if (StdDraw.mousePressed() && rectangles[i].containsPoint(StdDraw.mouseX(), StdDraw.mouseY())) {
rectangles[i].freeze();
}
if (rectangles[i].isFrozen()) {
count++;
StdDraw.show(25);
}
}
}
}}
这是移动矩形的类。 Stackoverflow说我需要添加上下文来解释这段代码是什么。
import java.util.Random;
public class MovingRectangles {
private double x;
private double y;
private double vx;
private double vy;
private double hx;
private double hy;
private boolean isFrozen;
private int red;
private int green;
private int blue;
public MovingRectangles(double x, double y, double vx, double vy, double hx, double hy) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
isFrozen = false;
this.hx = hx;
this.hy = hy;
randomColor();
}
public void randomColor() {
Random rng = new Random();
red = rng.nextInt(256);
blue = rng.nextInt(256);
green = rng.nextInt(256);
}
public void draw() {
if (isFrozen) {
StdDraw.setPenColor(StdDraw.RED);
} else {
StdDraw.setPenColor(red, green, blue);
}
StdDraw.filledRectangle(x, y, hx, hy);
}
public void update() {
x += vx;
y += vy;
if (x - hx < 0) {
vx *= -1;
x = 0 + hx;
randomColor();
}
if (x + hx > 1) {
vx *= -1;
x = 1 - hx;
randomColor();
}
if (y - hy < 0) {
vy *= -1;
y = 0 + hy;
randomColor();
}
if (y + hy > 1) {
vy *= -1;
y = 1 - hy;
randomColor();
}
}
public void freeze() {
isFrozen = true;
}
public boolean isFrozen() {
return isFrozen;
}
public boolean containsPoint(double a, double b) {
return
a > x - hx &&
a < x + hx &&
b > y - hy &&
b < y + hy;
}
}
我需要添加的另一件事就是打印&#34; You Win&#34;当所有五个方框都被点击时。谢谢你的帮助。
答案 0 :(得分:0)
在更新方法行的最开头添加,如
if(isFrozen)return;
它应该停止你的矩形。
另一种方式(如果你不想触摸矩形类)。 之后
for (int h = 0; h < rectangles.length; h++) {
rectangles[h].draw();
添加 if(!rectangles [h] .isFrozen())rectangles [h] .update();
答案 1 :(得分:0)
我的想法是你没有停止矩形的实际更新。
public void update() {
if(!this.isFrozen) {
{...your code...}
}
}
答案 2 :(得分:0)
这次绘制的更新修复了我遇到的问题。
public void draw() {
if (isFrozen) {
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledRectangle(x, y, hx, hy);
vx = 0;
vy = 0;
} else {
StdDraw.setPenColor(red, green, blue);
}
StdDraw.filledRectangle(x, y, hx, hy);
}