-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game.java
142 lines (103 loc) · 2.56 KB
/
Game.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package PongGame;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 1000;
public static final int HEIGHT = WIDTH * 9/16;
Ball ball;
Paddle paddle1;
Paddle paddle2;
public static boolean running = false;
private Thread gameThread;
public static void main(String[] args) {
new Game();
}
public Game() {
canvasSetup();
initialize();
new Window("Meghna's Pong",this);
this.addKeyListener(new KeyInput(paddle1, paddle2));
this.setFocusable(true);
}
private void initialize() {
// initialize ball
ball = new Ball();
// initialize paddles
paddle1 = new Paddle(Color.CYAN, true);
paddle2 = new Paddle(Color.ORANGE, false);
}
private void canvasSetup() {
this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
this.setMaximumSize(new Dimension(WIDTH, HEIGHT));
this.setMinimumSize(new Dimension(WIDTH, HEIGHT));
}
@Override
public void run() {
this.requestFocus();
//game timer
long lastTime = System.nanoTime();
double maxFPS = 60.0;
double frameTime = 1000000000/maxFPS;
double delta = 0;
while(running) {
long now = System.nanoTime();
delta += (now - lastTime)/frameTime;
lastTime = now;
if(delta>=1) {
update();
delta--;
draw();
}
}
stop();
}
private void update() {
// update ball
ball.update(paddle1, paddle2);
// update paddles
paddle1.update(ball);
paddle2.update(ball);
}
private void draw() {
// initialize drawing tools
BufferStrategy buffer = this.getBufferStrategy();
if (buffer == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = buffer.getDrawGraphics();
// draw background
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
// draw ball
ball.draw(g);
// draw paddles
paddle1.draw(g);
paddle2.draw(g);
// dispose all on screen
g.dispose();
buffer.show();
}
public void start() {
gameThread = new Thread(this);
gameThread.start();
running = true;
}
public void stop() {
try {
gameThread.join();
running = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int sign(double d) {
if (d>=0) {return 1;}
else {return -1;}
}
}