Hello everyone,
I have a program here that will display between 2 -4 cars "racing" accross the track. I am trying to get the cars to move at random speeds. Some faster, some slower but always different. I have tried a for loop and if it is working it is so neglible I cannot tell the difference. Here is the code I did for the loop:
public CarImage() { int y = (int)(Math.random() * 10) + 10; Timer timer1 = new Timer(y, new ActionListener(){ public void actionPerformed(ActionEvent e) { x += 10; c ++; repaint(); } }); timer1.start(); }
Here is the complete code in case someone needs to see what is going on:
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 = 150; protected int z = 300; protected int c = 0; public CarImage() { Timer timer1 = new Timer(40, new ActionListener(){ public void actionPerformed(ActionEvent e) { x += 10; c ++; repaint(); } }); timer1.start(); } 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; } } }
Please note that the loop I tried is NOT in the above program.
If anyone has a suggestion as to how I can get the different speeds I could use some help. A snippet of code would be nice. Yes this is homework. I did try what I thought would work but obviously it did not work.
Thank you in advance.