首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >确定java赛车程序中的获胜者

确定java赛车程序中的获胜者
EN

Stack Overflow用户
提问于 2012-09-30 06:48:25
回答 1查看 3.3K关注 0票数 3

我试图找到一种方法来确定获胜者,但我没有太多的运气。这个程序应该跑三圈,先跑完所有圈的赛车就是赢家。我可以跑3圈,但这不是一个很好的方法。我希望有人能告诉我一个更好的方法,以及我如何才能“计算”这些圈数的具体获胜赛车。汽车的数量在2-4之间是随机的,“速度”也是随机的。有人能帮帮我吗?一些代码会更好。

代码语言:javascript
复制
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;
                }*/
            }
    }

}
}

我为laps循环做的是这样的:

代码语言:javascript
复制
 if (k < 341){
     repaint();
     k++;
 {

此循环插入在以下位置的末尾:

代码语言:javascript
复制
public void paintComponent(Graphics g) {

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-30 07:35:54

试一下这段代码

新的RacingCar.java

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12657192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档