-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEngine.java
63 lines (57 loc) · 1.48 KB
/
Engine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferStrategy;
public abstract class Engine implements Runnable{
private int fps = 60;
private volatile boolean running;
private Gui gui;
public abstract void onStart();
public abstract void onTick();
public abstract void onRender(Graphics g);
public abstract void onExit();
public Engine(Gui gui, int fps){
this.fps = fps;
this.gui = gui;
this.gui.getJFrame().addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
onExit();
System.exit(0);
}
});
}
public Engine(Gui gui){
this(gui, 60);
}
public void setFps(int n){
this.fps = n;
}
public void run() {
onStart();
if(!running){
running = true;
while(running){
onTick();
render();
sleep(); }
}
}
public void render(){
Graphics g = gui.getGraphics();
BufferStrategy bs = gui.getBs();
g.clearRect(0, 0, gui.getWidth(), gui.getHeight());
onRender(g);
bs.show();
}
private void sleep(){
try {
Thread.sleep(1000/fps);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Gui getGui(){
return gui;
}
}