Start with the Car, CarPanel and CarFrame provided. Add a CarQueue class that ma
ID: 3695999 • Letter: S
Question
Start with the Car, CarPanel and CarFrame provided.
Add a CarQueue class that maintains a queue of random directions that the car should go.
1.There is an addToQueue method that has a class that implements runnable, define the run method (add random directions into the queue and then sleep), creates an instance of the runnable object, creates a thread and starts the thread.
/** Adds 0,1,2 or 3 to queue
* 0 = up
* 1 = down
* 2 = right
* 3 = left
*/
2.It also has a deleteQueue method that returns an Integer;
3.In your constructor, place 5 or 6 numbers in the queue so that when the animation starts – there will be something to retrieve from the queue
Modify the run method of the startAnimation in CarPanel so that the car will go to the right, left, up or down depending on what is retrieved from the CarQueue. The cars should go in the opposite direction if they hit a boundary.
/*******************************************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************/
/**********************************************************************************************************************************************************************************************/
Explanation / Answer
import java.util.ArrayDeque;import java.util.Queue;import java.util.Random;public class CarQueue {Queue queue;Random direction;public CarQueue(){ queue = new ArrayDeque(); direction = new Random(); queue.add(direction.nextInt(4)); queue.add(direction.nextInt(4)); queue.add(direction.nextInt(4)); queue.add(direction.nextInt(4)); queue.add(direction.nextInt(4)); queue.add(direction.nextInt(4)); queue.add(direction.nextInt(4));}public Integer deleteQueue(){ return (Integer)queue.remove();}public void addToQueue() { // TODO Auto-generated method stub}}carpanel.java
import java.awt.Graphics;import java.awt.Graphics2D;import javax.swing.JComponent;/**This component draws two car shapes.*/public class CarPanel extends JComponent{ private Car car1;private int x,y, delay;private CarQueue carQueue;private int direction;CarPanel(int x1, int y1, int d, CarQueue queue){ delay = d; x=x1; y=y1; car1 = new Car(x, y, this); carQueue = queue;}public void startAnimation() { class AnimationRunnable implements Runnable { public void run() { try { for(int i=0;i
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.