-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameHandler.java
More file actions
77 lines (58 loc) · 1.64 KB
/
Copy pathGameHandler.java
File metadata and controls
77 lines (58 loc) · 1.64 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package game_template;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import javax.swing.JPanel;
public class GameHandler extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
final int width = 100, height = 100;
final int fps = 30; // how often the game updates
Thread gameThread;
KeyHandler kh = new KeyHandler();
MouseHandler mh = new MouseHandler();
SoundManager sm = new SoundManager();
Player player;
public GameHandler() {
setPreferredSize(new Dimension(width, height));
setDoubleBuffered(true);
addKeyListener(kh);
addMouseListener(mh);
setFocusable(true);
initialize();
gameThread = new Thread(this);
gameThread.start();
}
public void initialize() {
this.setBackground(Color.black);
player = new Player(0, 0, 5, 5); // x, y, w, h
}
@Override
public void run() {
double loopInterval = 1000000000/fps;
double nextLoopTime = System.nanoTime() + loopInterval;
while (gameThread != null) {
update();
repaint();
try {
double remainingTime = (nextLoopTime - System.nanoTime())/1000000;
if (remainingTime < 0) remainingTime = 0;
Thread.sleep((long) remainingTime);
nextLoopTime += loopInterval;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update() {
mh.updateMouseLocation(this);
player.update(kh);
}
@Override
public void paintComponent(Graphics g_) {
super.paintComponent(g_);
Graphics2D g = (Graphics2D) g_;
player.draw(g);
g.dispose();
}
}