-
Notifications
You must be signed in to change notification settings - Fork 0
/
reactive_pong.html
332 lines (314 loc) · 7.75 KB
/
reactive_pong.html
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<!doctype html>
<!-- @jalberca -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reactive Pong</title>
<!-- Basic styling, centering the canvas -->
<style>
canvas {
display: block;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div style="max-width:380px; min-width: 300px">
<h1>Q4S Reactive Pong</h1>
<div>Move up: ↑ key.</div>
<div>Move down: ↓ key.</div>
<p> </p>
<button onclick="q4sChange()">Q4S on/off</button>
<div><span id="info">Q4S is currently OFF</span></div>
<p></p>
<div id="latencia">Latency: 0 ms</div>
<p></p>
<div>This is a reactive version of Pong, in which thanks to the use of the Q4S protocol, the game adjusts to the variation of the latency by reducing the speed of the ball. Thus the videogame is playable despite the fact that the latency conditions vary.</div>
</div>
<!--Esta es una versión reactiva de Pong, en la cual gracias a la utilización del protocolo Q4S, el videojuego se ajusta a la variación de la latencia mediante la reducción de la velocidad de la pelota. Así el videojuego es jugable a pesar de que las condiciones de latencia varíen. -->
<script>
//Gestion de la activación y desactivación de Q4S
var q4s = false;
function q4sChange(){
if(!q4s){
q4s=true;
document.getElementById("info").textContent="Q4S is currently ON";
}
else{
q4s=false;
document.getElementById("info").textContent="Q4S is currently OFF";
}
}
//Calcula la latencia, que tiene forma sinusoidal
var i = 30;
var latencia=0;
function latency(){
var valor=300*Math.sin(this.i/10);
this.i=this.i-1;
if(this.i===0){
this.i=30;
}
//console.log(valor);
var n = valor.toFixed(0);
document.getElementById("latencia").textContent="Latency: " + n + " ms.";
this.latencia=valor;
}
//El valor de la latencia se actualiza cada segundo
var aux = setInterval(latency, 1000);
var
/**
* Constants
*/
WIDTH = 700,
HEIGHT = 600,
pi = Math.PI,
UpArrow = 38,
DownArrow = 40,
/**
* Game elements
*/
canvas,
ctx,
keystate,
/**
* The player paddle
*
* @type {Object}
*/
player = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on pressed keys
*/
update: function() {
var lat = latencia;
if (keystate[UpArrow]) {
//Retarda la acción de la pulsación de la tecla en "lat" milisegundos
setTimeout(function(){
this.player.y -= 7;
}, lat);
}
if (keystate[DownArrow]) {
setTimeout(function(){
this.player.y += 7;
}, lat);
}
// keep the paddle inside of the canvas
this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
},
/**
* Draw the player paddle to the canvas
*/
draw: function() {
ctx.fillStyle = 'white';
ctx.fillRect(this.x, this.y, this.width, this.height);
//ctx.fillText("Latency: " + this.latencia + " ms", this.width, this.height-60);
}
},
/**
* The ai paddle
*
* @type {Object}
*/
ai = {
x: null,
y: null,
width: 20,
height: 100,
/**
* Update the position depending on the ball position
*/
update: function() {
// calculate ideal position
var desty = ball.y - (this.height - ball.side)*0.5;
// ease the movement towards the ideal position
this.y += (desty - this.y) * 0.1;
// keep the paddle inside of the canvas
this.y = Math.max(Math.min(this.y, HEIGHT - this.height), 0);
},
/**
* Draw the ai paddle to the canvas
*/
draw: function() {
ctx.fillRect(this.x, this.y, this.width, this.height);
}
},
/**
* The ball object
*
* @type {Object}
*/
ball = {
x: null,
y: null,
vel: null,
side: 20,
speed: 15,
//Actualiza la velocidad de la pelota en función de la latencia
updateSpeed: function() {
var myVar = latencia;
if (latencia<80) this.speed=15;
else if(latencia<100) this.speed= 9;
else if(latencia<200) this.speed=7;
else if(latencia<300) this.speed=7;
},
/**
* Serves the ball towards the specified side
*
* @param {number} side 1 right
* -1 left
*/
serve: function(side) {
//Solo varía la velocidad de la pelota si Q4S está activado
if(q4s){
this.updateSpeed();
} else{
this.speed=12;
}
// set the x and y position
var r = Math.random();
this.x = side===1 ? player.x+player.width : ai.x - this.side;
this.y = (HEIGHT - this.side)*r;
// calculate out-angle, higher/lower on the y-axis =>
// steeper angle
var phi = 0.1*pi*(1 - 2*r);
// set velocity direction and magnitude
this.vel = {
x: side*this.speed*Math.cos(phi),
y: this.speed*Math.sin(phi)
}
},
/**
* Update the ball position and keep it within the canvas
*/
update: function() {
//Solo varía la velocidad de la pelota si Q4S está activado
if(q4s){
this.updateSpeed();
} else{
this.speed=12;
}
// update position with current velocity
this.x += this.vel.x;
this.y += this.vel.y;
// check if out of the canvas in the y direction
if (0 > this.y || this.y+this.side > HEIGHT) {
// calculate and add the right offset, i.e. how far
// inside of the canvas the ball is
var offset = this.vel.y < 0 ? 0 - this.y : HEIGHT - (this.y+this.side);
this.y += 2*offset;
// mirror the y velocity
this.vel.y *= -1;
}
// helper function to check intesectiont between two
// axis aligned bounding boxex (AABB)
var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
};
// check againts target paddle to check collision in x
// direction
var pdle = this.vel.x < 0 ? player : ai;
if (AABBIntersect(pdle.x, pdle.y, pdle.width, pdle.height,
this.x, this.y, this.side, this.side)
) {
// set the x position and calculate reflection angle
this.x = pdle===player ? player.x+player.width : ai.x - this.side;
var n = (this.y+this.side - pdle.y)/(pdle.height+this.side);
var phi = 0.25*pi*(2*n - 1); // pi/4 = 45
// calculate smash value and update velocity
var smash = Math.abs(phi) > 0.2*pi ? 1.5 : 1;
this.vel.x = smash*(pdle===player ? 1 : -1)*this.speed*Math.cos(phi);
this.vel.y = smash*this.speed*Math.sin(phi);
}
// reset the ball when ball outside of the canvas in the
// x direction
if (0 > this.x+this.side || this.x > WIDTH) {
this.serve(pdle===player ? 1 : -1);
}
},
/**
* Draw the ball to the canvas
*/
draw: function() {
ctx.fillRect(this.x, this.y, this.side, this.side);
}
};
/**
* Starts the game
*/
function main() {
// create, initiate and append game canvas
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
// keep track of keyboard presses
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
});
init(); // initiate game objects
// game loop function
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
/**
* Initatite game objects and set start positions
*/
function init() {
player.x = player.width;
player.y = (HEIGHT - player.height)/2;
ai.x = WIDTH - (player.width + ai.width);
ai.y = (HEIGHT - ai.height)/2;
ball.serve(1);
}
/**
* Update all game objects
*/
function update() {
ball.update()
player.update();
ai.update();
}
/**
* Clear canvas and draw all game objects and net
*/
function draw() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
ball.draw();
player.draw();
ai.draw();
// draw the net
var w = 4;
var x = (WIDTH - w)*0.5;
var y = 0;
var step = HEIGHT/20; // how many net segments
while (y < HEIGHT) {
ctx.fillRect(x, y+step*0.25, w, step*0.5);
y += step;
}
ctx.restore();
}
// start and run the game
main();
</script>
</body>
</html>