-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpong.js
308 lines (308 loc) · 9.54 KB
/
pong.js
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
"use strict";
/**
* Main class of this game.
*/
class Pong {
/**
* Creates a new game object.
* @param useAi if true, player 2 will be played by an artifical intelligence
*/
constructor(useAi) {
this.useAi = useAi;
// lag of the AI in milliseconds
this.aiLag = 100;
this.gameSize = [
window.innerWidth,
window.innerHeight
];
this.round = 0;
// inverse framerate
this.intervalTime = 16;
// ball
this.ball = {
radius: Math.min(window.innerWidth, window.innerHeight) / 100,
position: [0, 0],
speed: [0, 0]
};
// players
this.player1 = {
id: 1,
size: 0,
position: 0,
score: 0
};
this.player2 = {
id: 2,
size: 0,
position: 0,
score: 0
};
// canvas
this.canvas = this.createCanvas();
this.ctx = this.canvas.getContext("2d");
this.ctx.font = "20px Consolas";
this.ctx.textAlign = "center";
// initialize game
this.resetComplete();
}
/**
* Removes the canvas from the DOM.
*/
remove() {
this.canvas.remove();
}
/**
* Called when a player has pressed a key.
* @param event keydown event
*/
keyDown(event) {
event.preventDefault();
// start game if it is not running
if (!this.gameRunning) {
if (event.key === "m") {
// change game mode
this.useAi = !this.useAi;
this.resetComplete();
}
else {
this.startGame();
}
}
else {
// process keyboard input
switch (event.key) {
case "w":
if (this.player1.position > 10 && !this.useAi) {
this.player1.position -= 10;
}
break;
case "s":
if (this.player2.position < this.canvas.height - 10 && !this.useAi) {
this.player1.position += 10;
}
break;
case "ArrowUp":
if (this.player2.position > 10) {
this.player2.position -= 10;
}
break;
case "ArrowDown":
if (this.player2.position < this.canvas.height - 10) {
this.player2.position += 10;
}
break;
default:
break;
}
// show current field
this.updateUI();
}
}
/**
* Resets the game to be ready for the next round.
* Makes the game more difficult in each round.
*/
reset() {
this.round++;
// ball
this.ball.position = [
this.gameSize[0] / 2,
this.gameSize[1] / 2
];
const speed = this.gameSize[0] / 200 + this.round * this.gameSize[0] / 2000;
this.ball.speed = [
Math.random() > 0.5 ? speed : -speed,
0
];
// players
this.player1.position = this.gameSize[1] / 2;
this.player2.position = this.gameSize[1] / 2;
// make players smaller every round
// make a player small if they lost, bigger if they won
const size = this.gameSize[1] / 3 - this.round * 5;
this.player1.size = (this.player1.score - this.player2.score) * 10 + size;
this.player2.size = (this.player2.score - this.player1.score) * 10 + size;
}
/**
* Resets the game to the initial conditions.
*/
resetComplete() {
this.round = 0;
this.player1.score = 0;
this.player2.score = 0;
this.reset();
// draw UI
this.updateUI(false);
this.showMessages("P O N G", "~~~ new game ~~~", this.useAi ? "human vs. PC" : "2 player mode", "", "press <m> to change game mode", "press <s> or <⬆> to start", `player1 (left): ${this.useAi ? "PC" : "up <w> down <s>"}`, "player2 (right): up <⬆> down <⬇>", "press <F5> to reset");
}
/**
* Starts the game.
*/
startGame() {
this.gameRunning = true;
this.resetComplete();
this.interval = setInterval(this.animateBall, this.intervalTime, this);
}
/**
* Ends the game.
* @param winner winner of the currently ended game.
*/
endGame(winner) {
clearInterval(this.interval);
this.updateUI(false);
const loser = winner === 1 ? this.player2 : this.player1;
let message;
if (loser.size < 20) {
message = `player ${loser.id} died!`;
this.gameRunning = false;
}
else {
message = `winner: player ${winner}`;
this.reset();
}
this.showMessages("game over!", message, "press <s> or <⬆> to continue");
}
/**
* Creates and returns a canvas object.
*/
createCanvas() {
const canvas = document.createElement("canvas");
canvas.width = this.gameSize[0];
canvas.height = this.gameSize[1];
document.getElementsByTagName("body")[0].appendChild(canvas);
return canvas;
}
/**
* Moves the ball depedning on its current speed.
* @param p this Pong object
*/
animateBall(p) {
// move ball
p.ball.position[0] += p.ball.speed[0];
p.ball.position[1] += p.ball.speed[1];
// reflex ball from upper and lower edge
if (p.ball.position[1] < p.ball.radius
|| p.ball.position[1] > p.canvas.height - p.ball.radius) {
p.ball.speed[1] *= -1;
}
// check if game over
if (p.ball.position[0] < 0) {
// player 2 wins
p.player2.score++;
p.endGame(2);
}
else if (p.ball.position[0] > p.canvas.width) {
// player 1 wins
p.player1.score++;
p.endGame(1);
}
else {
p.updateUI();
}
// check if player hit the ball
const p1hit = p.playerHit(p.player1);
const p2hit = p.playerHit(p.player2);
if (p1hit || p2hit) {
// invert x speed and make faster
p.ball.speed[0] *= -1.1;
// y speed:
// keep it roughly the same but change it
// depending on where the player was hit
p.ball.speed[1] += p.playerHitDeltaYSpeed(p1hit ? p.player1 : p.player2);
}
if (p.useAi) {
// if the AI is playing, let it react to the current ball y-position
// but only slowly
if (p.ball.position[1] > p.player1.position) {
p.player1.position += 0.8;
}
else {
p.player1.position -= 0.8;
}
}
}
/**
* Returns true if the ball hit the specified player.
* @param player one of the two player objects
*/
playerHit(player) {
const playerXPosition = player.id === 1 ? 10 : this.canvas.width - 10;
const xDistance = Math.abs(this.ball.position[0] - playerXPosition);
const yDistance = Math.abs(this.ball.position[1] - player.position);
const hit = xDistance < this.ball.radius + 5
&& yDistance < player.size / 2 + this.ball.radius;
return hit;
}
/**
* Returns a y-speed modificator based on player-ball hit position.
* @param player player that has been hit
*/
playerHitDeltaYSpeed(player) {
// get relative signed distance from player center to ball compared to player size
return (this.ball.position[1] - player.position) / player.size;
}
/**
* Displays a message on the UI.
* @param message
*/
showMessages(...messages) {
let offsetY = this.canvas.height / 2 - 15 * messages.length;
messages.forEach(m => {
this.ctx.fillText(m, this.canvas.width / 2, offsetY);
offsetY += 30;
console.log(m);
});
}
/**
* Draws the UI.
*/
updateUI(drawBall = true) {
// background
this.ctx.fillStyle = "#000";
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// players
this.ctx.fillStyle = "#fff";
this.ctx.fillRect(5, this.player1.position - this.player1.size / 2, 10, this.player1.size);
this.ctx.fillRect(this.canvas.width - 15, this.player2.position - this.player2.size / 2, 10, this.player2.size);
// ball
if (drawBall) {
this.ctx.beginPath();
this.ctx.arc(this.ball.position[0], this.ball.position[1], this.ball.radius, 0, 2 * Math.PI);
this.ctx.fill();
}
// round
this.ctx.fillText(`round ${this.round}`, this.canvas.width / 2, 25);
// score
this.ctx.fillText(`${this.player1.score} : ${this.player2.score}`, this.canvas.width / 2, this.canvas.height - 10);
}
}
let pong;
/**
* Processes keyboard events.
* @param event keyboard event
*/
function keyDownPong(event) {
// some keys should be processed by the browser
switch (event.key) {
case "F5":
return;
case "F11":
return;
case "F12":
return;
default:
// pass on to game
if (pong) {
pong.keyDown(event);
}
}
}
/**
* Starts a new game.
*/
function initPong() {
if (pong) {
pong.remove();
}
pong = new Pong(false);
}