Skip to content
Snippets Groups Projects
GameController.java 1.72 KiB
Newer Older
Jan Kožusznik's avatar
Jan Kožusznik committed
	package lab;
Jan Kožusznik's avatar
Jan Kožusznik committed

import javafx.animation.AnimationTimer;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
Jan Kožusznik's avatar
Jan Kožusznik committed
import javafx.scene.canvas.Canvas;
Jan Kožusznik's avatar
Jan Kožusznik committed
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
Jan Kožusznik's avatar
Jan Kožusznik committed

public class GameController {

	private World world;
	
	@FXML
	private Slider angleSlider;
	
Jan Kožusznik's avatar
Jan Kožusznik committed
	@FXML
	private Slider strengthSlider;
	
Jan Kožusznik's avatar
Jan Kožusznik committed
	private Canvas canvas;
Jan Kožusznik's avatar
Jan Kožusznik committed
	@FXML
	private Label shoots;
	
	@FXML
	private Label hits;
	
Jan Kožusznik's avatar
Jan Kožusznik committed
	private AnimationTimer animationTimer;
	
	public GameController() {
Jan Kožusznik's avatar
Jan Kožusznik committed
	}
	
	public void startGame() {
		this.world = new World(canvas.getWidth(), canvas.getHeight());	
		//Draw scene on a separate thread to avoid blocking UI.
		animationTimer = new AnimationTimer() {
			private Long previous;
			
			@Override
			public void handle(long now) {
				if (previous == null) {
					previous = now;
				} else {
					drawScene((now - previous)/1e9);
					previous = now;
				}
			}
		};
		angleSlider.valueProperty().addListener(this::angleChanged);
		world.setCannonAngle(angleSlider.getValue());
Jan Kožusznik's avatar
Jan Kožusznik committed
		
		strengthSlider.valueProperty().addListener(this::strenghtChanged);
		world.setCannonStrength(strengthSlider.getValue());
Jan Kožusznik's avatar
Jan Kožusznik committed
		animationTimer.start();
	}


	public void stopGame() {
		animationTimer.stop();
	}
	
	private void drawScene(double deltaT) {
		world.draw(canvas);
		world.simulate(deltaT);
	}
	
	@FXML
	private void firePressed() {
Jan Kožusznik's avatar
Jan Kožusznik committed
		world.fire();
	}
	
	
	private void angleChanged(ObservableValue<? extends Number> observable
								, Number oldValue, Number newValue) {
		world.setCannonAngle(newValue.doubleValue());
	}
Jan Kožusznik's avatar
Jan Kožusznik committed

Jan Kožusznik's avatar
Jan Kožusznik committed
	private void strenghtChanged(ObservableValue<? extends Number> observable
			, Number oldValue, Number newValue) {
		world.setCannonStrength(newValue.doubleValue());
	}
Jan Kožusznik's avatar
Jan Kožusznik committed
}