-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.java
More file actions
115 lines (95 loc) · 2.11 KB
/
Game.java
File metadata and controls
115 lines (95 loc) · 2.11 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game implements Runnable {
private Display display;
private boolean running = false;
Graphics g;
BufferStrategy bs;
int width, height, FPS = 30;
boolean isGameover = false;
String title;
Snake snake;
Apples apple;
Thread thread;
public Game(String title, int width, int height) {
this.title = title;
this.width = width;
this.height = height;
this.start();
}
// Init objects
public void init() {
display = new Display(title, width, height);
snake = new Snake(this);
apple = new Apples(snake);
display.getJFrame().addKeyListener(snake);
}
public void update() {
//update the snake
if (!isGameover) {
snake.update(apple, this);
}
}
public void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
g.clearRect(0, 0, width, height);
// Draw
g.setColor(Color.black);
g.fillRect(0, 0, width, height);
//Check to see if the game is over
if (isGameover) {
g.setColor(Color.white);
g.setFont(new Font("SansSerif", Font.PLAIN, 18));
g.drawString("You Died", SnakeGame.width/2 - 32, SnakeGame.height/2);
} else {
snake.render(g);
apple.render(g);
}
// End Draw
bs.show();
g.dispose();
}
public void run() {
init();
//Create constant framerate
double timePerTick = 1000000000 / FPS;
double delta = 0;
long now;
long lastTime = System.nanoTime();
while (running) {
now = System.nanoTime();
delta += (now - lastTime) / timePerTick;
lastTime = now;
if (delta >= 1) {
update();
render();
delta--;
}
}
}
public void start() {
if (running) {
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public void stop() {
if (!running) {
return;
}
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}