package carracing;
import javafx.application.Application;
import javafx.animation.KeyFrame;
import javafx.scene.Scene;
import javafx.animation.Timeline;
import static javafx.application.Application.launch;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author Shak
*/
public class CarRacing extends Application {
@Override
public void start(Stage primaryStage) {
class CarPane extends Pane
{
private double paneWidth = 200; //Width of the pane
private double paneHeight = 200; //Height of the pane
private double baseX = 0; //Intial X placement of Car
private double baseY = paneHeight; //Intial y placement of Car
private Circle c1 = new Circle (baseX+15, baseY-5, 5); // Placement of first wheel
private Circle c2 = new Circle (baseX+35, baseY-5, 5); //Placement of second wheel
private Rectangle carBody = new Rectangle (baseX,baseY-20,50,10); //Car body
private Polygon carTop = new Polygon (baseX+10,baseY-20, //Car top
baseX+20, baseY-30, baseX+30, baseY-30,
baseX+40, baseY-20);
public CarPane()
{
carBody.setFill (Color.CYAN);
carTop.setFill (Color.BLUE);
this.getChildren().addAll (c1,c2,carBody,carTop );
}
public void setValues()
{
c1.setCenterX (baseX+15);
c1.setCenterY (baseY-5);
c2.setCenterX (baseX+35);
c2.setCenterY (baseY-5);
carBody.setX(baseX);
carBody.setY(baseY-20);
carTop.getPoints().clear();
carTop.getPoints().addAll(baseX+10,baseY-20,
baseX=20,baseY-30,baseX+30,baseY-30,baseX+40,baseY-20);
}
public void move()
{
if (baseX > paneWidth)
{
baseX=-20;
}
else
{
baseX+= 1;
}
setValues();
}
public void setW( double newWidth)
{
this.paneWidth =newWidth;
setValues();
}
public void setH (double newHeight)
{
this.paneHeight = newHeight;
setValues();
}
{
//Create a new CarPane
CarPane car=new CarPane();
//Create a scene and place it in the stage
Scene scene=new Scene (car,200,200);
primaryStage.setTitle("Racing Car"); // Set the stage title
primaryStage.setScene(scene); //Place the scene in the stage
primaryStage.show(); // Display the stage
Timeline animation = new Timeline ( new KeyFrame(Duration.millis(100),
e->car.move()));
animation.setCycleCount ( Timeline.INDEFINITE);
animation.play(); // Start animation
scene.widthProperty().addListener (e->car.setW( car.getWidth()));
scene.heightProperty().addListener (e->car.setH (car.getHeight()));
car.setOnMousePressed(e->animation.pause());
car.setOnMouseReleased(e->animation.play());
car.requestFocus();
car.setOnKeyPressed(e ->
{
switch ( e.getCode())
{
case UP:
animation.setRate( animation.getRate()+1);
break;
case DOWN:
animation.setRate (animation.getRate()-1);
break;
}};