确定java赛车计划的赢家

时间:2012-09-29 22:48:25

标签: java

我正试图找到一种方法来确定胜利者,而我却没有太多运气。该计划假设运行三圈,并且首先完成所有圈数的赛车赢家。我可以获得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) {

我真的被困在这里了。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

尝试使用此代码

RacingCar.java

顺便说一句,我让你的计时器更快,以便在非常慢的比赛中不等待3圈! :P

相关问题