Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Game in JavaFX: Two classes to create games using JavaFX
package org.jugvale.javafx;
import javafx.scene.canvas.GraphicsContext;
/**
*
* @author william
*/
public abstract class Game {
/*
The GraphicsContext so the game can draw stuff
*/
GraphicsContext gc;
GameEngine engine;
/*
The size of the game playing area
*/
float MAX_W;
float MAX_H;
public Game(float w, float h, GraphicsContext _gc) {
MAX_W = w;
MAX_H = h;
gc = _gc;
gc.getCanvas().setWidth(w);
gc.getCanvas().setHeight(h);
}
final public void setEngine(GameEngine _engine) {
engine = _engine;
}
public abstract void update();
public abstract void display();
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.jugvale.javafx;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.Event;
import javafx.util.Duration;
/**
*
* @author william
*/
public class GameEngine {
private int frameCount = 0;
private int frameRate;
private final Game game;
private final Timeline gameLoop;
public GameEngine(int frameRate, Game game) {
this.frameRate = frameRate;
this.game = game;
game.setEngine(this);
gameLoop = createLoop();
}
public int getFrameCount() {
return frameCount;
}
public int getFrameRate() {
return frameRate;
}
public void setFrameRate(int frameRate) {
this.frameRate = frameRate;
}
private void run(Event e) {
frameCount++;
game.update();
game.display();
}
public void start() {
gameLoop.playFromStart();
}
public void stop() {
gameLoop.stop();
}
private Timeline createLoop() {
// inspired on https://carlfx.wordpress.com/2012/04/09/javafx-2-gametutorial-part-2/
final Duration d = Duration.millis(1000 / frameRate);
final KeyFrame oneFrame = new KeyFrame(d, this::run);
Timeline t = new Timeline(frameRate, oneFrame);
t.setCycleCount(Animation.INDEFINITE);
return t;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment