我正试图找到一种方法来决定胜利者,但我运气不太好。这个程序假设要跑三圈,哪辆车先跑完所有的圈才是赢家。我能跑3圈,但这不是一个很好的方法。我希望有人能告诉我一个更好的方法,以及我如何能“数”那些圈的具体获胜的汽车。汽车的数量是随机的,从2-4和“速度”也是随机的。有人能帮帮我吗?有代码就好了。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class RacingCar extends JFrame {
public RacingCar() {
int x = (int)(Math.random() * 3) + 2;
setLayout(new GridLayout(x, 1, 5,5));
for (int i = 0; i < x; i++){
add(new CarImage());
}
}
public static void main(String[] args) {
JFrame frame = new RacingCar();
frame.setTitle("Racing Car");
frame.setSize(1200, 350);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class CarImage extends JPanel {
protected int x = 0;
protected int y = 350;
protected int z = 1200;
protected int c = 0;
public CarImage() {
int j = (int)(Math.random() * 500) + 2;
Timer timer1 = new Timer(j, new ActionListener(){
public void actionPerformed(ActionEvent e) {
x += 10;
c ++;
repaint();
}
});
timer1.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//x = 0;
y = getHeight();
z = getWidth();
g.setColor(Color.WHITE);
g.fillRect(0, 0, z, y);
Polygon polygon = new Polygon();
polygon.addPoint(x + 10, y - 21);
polygon.addPoint(x + 20, y - 31);
polygon.addPoint(x + 30, y - 31);
polygon.addPoint(x + 40, y - 21);
if (x < z - 50) {
g.setColor(Color.BLACK);
g.fillOval(x + 10, y - 11, 10, 10);
g.fillOval(x + 30, y - 11, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(x, y - 21, 50, 10);
g.setColor(Color.GRAY);
g.fillPolygon(polygon);
g.setColor(Color.RED);
}
else {
x = 0;
/*if (c < z - 86) {
g.drawString("Clint's Car", c, y - 51);
}
else {
c = 0;
}*/
}
}
}
}
我对圈圈做的是:
if (k < 341){
repaint();
k++;
{
此循环插入到:
public void paintComponent(Graphics g) {
我真的被困在这里了。谢谢你的帮助。
最佳答案
试试这个代码
新的RacingCar.java
顺便说一下,我让你的计时器更快,这样你就不会在真正慢的比赛中等3圈了!:p页