gpt4 book ai didi

Java 具有随机颜色的弹跳球应用程序

转载 作者:行者123 更新时间:2023-12-01 11:36:24 25 4
gpt4 key购买 nike

我被交给了在我成功创建的程序中使球弹跳的任务。现在,我尝试专注于更高级的功能,例如第二个球(我已经成功完成),并使球每次弹跳时都变为随机颜色。

我对 Java 和一般编码都很陌生,但我已经成功地做到了,当它们第一次撞到墙上时,它们都会变成随机颜色。但是,我似乎无法让它每次弹跳时都变成不同的颜色。有人对如何实现这一目标有任何建议吗?

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;


public class MainClass extends javax.swing.JFrame implements Runnable {
int width ;
int height ;
int ball;
int ball2;
int posX;
int posY;
int posX2;
int posY2;
int dx = 8;
int dy = 8;//dx dy are varuiables for the movement of the ball
int dx2 = -8;
int dy2 = -8;
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
float r2 = rand.nextFloat();
float g2 = rand.nextFloat();
float b2 = rand.nextFloat();
Color randomColor = new Color(r, g, b);
Color randomColor2 = new Color(r2,g2,b2);
Color c1 = Color.BLUE;
Color c2 = Color.GREEN;
Thread move = new Thread (this);


public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0,0,width,height);
g.setColor(c1);
g.fillOval(posX ,posY ,ball,ball);
g.setColor(c2);
g.fillOval(posX2,posY2, ball2,ball2);

// sets starting position of Oval(ball)
}

public void run(){
try {
while (true){
posX=posX+dx;
posY=posY+dy;
posX2=posX2+dx2;
posY2=posY2+dy2;
//this is the speed of the ball
repaint();

move.sleep(100);


//This shows the ball on the screen
if (posY > height - ball)
{
dy = dy *-1;
c1 = randomColor;
}
if ( posY <0 - ball)
{
dy = dy *-1;
c1 = randomColor;
}
if(posX > width - ball)
{
c1 = randomColor;
dx = dx*-1;
}
if(posX <0 - ball )
{
c1 = randomColor;
dx = dx*-1;
}
// This code is for the first ball
if(posX > width - ball2 || posX <0 - ball2)
{
dx2 = dx2*-1;
c2 = randomColor2;
}
if(posY > height - ball2 || posY <0 - ball2)
{
dy2 = dy2 *-1;
c2 = randomColor2;
}
}
}
catch(Exception ex) {
ex.printStackTrace();

}
}

public MainClass() {
initComponents();
this.setResizable(false);
width = getWidth();
height = getHeight();
//this code creates the program dimensions
posX = width/2;
posY = height/2;
posX2 = width/2;
posY2 = height/2;
ball = 20;
ball2= 20;

最佳答案

每次设置后更改randomColor的颜色,这样下次设置时它就会不同。

关于Java 具有随机颜色的弹跳球应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29947900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com