-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
546 lines (439 loc) · 12.7 KB
/
main.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
} )();
var globalY;
var canvas,
ctx , // Create canvas context
W , // Window's width
H , // Window's height
particles, // Array containing particles
ball , // Ball object
paddles , // Array containing two paddles
mouse, // Mouse object to store it's current position
points , // Varialbe to store points
fps , // Max FPS (frames per second)
particlesCount, // Number of sparks when ball strikes the paddle
flag , // Flag variable which is changed on collision
particlePos, // Object to contain the position of collision
multipler , // Varialbe to control the direction of sparks
startBtn , // Start button object
restartBtn, // Restart button object
over , // flag varialbe, cahnged when the game is over
init, // variable to initialize animation
paddleHit;
$(document).ready(function(){
// Initialize canvas and required variables
canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"), // Create canvas context
W = $("#canvas").width(), // Window's width
H = $("#canvas").height(), // Window's height
particles = [], // Array containing particles
ball = {}, // Ball object
paddles = [2], // Array containing two paddles
mouse = {}, // Mouse object to store it's current position
points = 0, // Varialbe to store points
fps = 60, // Max FPS (frames per second)
particlesCount = 20, // Number of sparks when ball strikes the paddle
flag = 0, // Flag variable which is changed on collision
particlePos = {}, // Object to contain the position of collision
multipler = 1, // Varialbe to control the direction of sparks
startBtn = {}, // Start button object
restartBtn = {}, // Restart button object
over = 0, // flag varialbe, cahnged when the game is over
init, // variable to initialize animation
paddleHit;
// Add mousemove and mousedown events to the canvas
canvas.addEventListener("mousemove", trackPosition, true);
canvas.addEventListener("mousedown", btnClick, true);
// Initialise the collision sound
collision = document.getElementById("collide");
// Set the canvas's height and width to full screen
canvas.width = W;
canvas.height = H;
// Push two new paddles into the paddles[] array
paddles.push(new Paddle("left"));
paddles.push(new Paddle("right"));
// Ball object
ball = {
x: W/2,
y: H/2,
r: 5,
c: "red",
vx: 6,
vy: 6,
// Function for drawing ball on canvas
draw: function() {
ctx.beginPath();
ctx.fillStyle = this.c;
ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false);
ctx.fill();
}
};
// Start Button object
startBtn = {
w: 100,
h: 50,
x: W/2 - 50,
y: H/2 - 125,
draw: function() {
ctx.strokeStyle = "red";
ctx.lineWidth = "2";
ctx.strokeRect(this.x, this.y, this.w, this.h);
ctx.font = "18px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStlye = "red";
ctx.fillText("Start", W/2, H/2 - 100 );
}
};
// Restart Button object
restartBtn = {
w: 100,
h: 50,
x: W/2 - 50,
y: H/2 - 50,
draw: function() {
ctx.strokeStyle = "red";
ctx.lineWidth = "2";
ctx.strokeRect(this.x, this.y, this.w, this.h);
ctx.font = "18px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStlye = "red";
ctx.fillText("Restart", W/2, H/2 - 25 );
}
};
// Show the start screen
startScreen();
$("#detected").css("color","red");
$("#detected").text("Leap sensor not detected")
$("#detected").show();
});// end of $(document).ready(..)
// Function to paint canvas
function paintCanvas() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, W, H);
}
// Function for creating paddles
function Paddle(pos) {
// Height and width
this.h = 150;
this.w = 10;
// Paddle's position
this.y = H/2 - this.h/2;
this.x = (pos == "left") ? 0 : W - this.w;
}
// Function for creating particles object
function createParticles(x, y, m) {
this.x = x || 0;
this.y = y || 0;
this.radius = 1.2;
this.vx = -1.5 + Math.random()*3;
this.vy = m * Math.random()*1.5;
}
// Draw everything on canvas
function draw() {
paintCanvas();
for(var i = 0; i < paddles.length; i++) {
p = paddles[i];
ctx.fillStyle = "black";
ctx.fillRect(p.x, p.y, p.w, p.h);
}
ball.draw();
update();
}
// Function to increase speed after every 5 points
function increaseSpd() {
if(points % 4 == 0) {
if(Math.abs(ball.vx) < 15) {
ball.vx += (ball.vx < 0) ? -1 : 1;
ball.vy += (ball.vy < 0) ? -2 : 2;
}
}
}
// Track the position of mouse cursor
function trackPosition(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}
// Function to update positions, score and everything.
// Basically, the main game logic is defined here
function update() {
// Update scores
updateScore();
// Move the paddles on mouse move
if(mouse.x && mouse.y) {
p = paddles[1];
p.y = mouse.y - p.h/2 - $("#canvas").offset().top;
//console.log(p.y);
}
p = paddles[2]
// Move the ball
ball.x += ball.vx;
ball.y += ball.vy;
// Collision with paddles
p1 = paddles[1];
p2 = paddles[2];
// If the ball strikes with paddles,
// invert the y-velocity vector of ball,
// increment the points, play the collision sound,
// save collision's position so that sparks can be
// emitted from that position, set the flag variable,
// and change the multiplier
if(collides(ball, p1)) {
collideAction(ball, p1);
}
else if(collides(ball, p2)) {
collideAction(ball, p2);
}
else {
// Collide with walls, If the ball hits the left/right,
// walls, run gameOver() function
if(ball.x + ball.r > W) {
ball.x = W - ball.r;
gameOver();
}
else if(ball.x < 0) {
ball.x = ball.r;
gameOver();
}
// If ball strikes the horizontal walls, invert the
// y-velocity vector of ball
if(ball.y + ball.r > H) {
ball.vy = -ball.vy;
ball.y = H - ball.r;
}
else if(ball.y - ball.r < 0) {
ball.vy = -ball.vy;
ball.y = ball.r;
}
}
// If flag is set, push the particles
if(flag == 1) {
for(var k = 0; k < particlesCount; k++) {
particles.push(new createParticles(particlePos.x, particlePos.y, multiplier));
}
}
// Emit particles/sparks
emitParticles();
// reset flag
flag = 0;
}
//Function to check collision between ball and one of
//the paddles
function collides(b, p) {
if(b.y + ball.r >= p.y && b.y - ball.r <=p.y + p.h) { //a collision took place
if(b.x >= (p.x - p.w) && p.x > 0){
paddleHit = 1;
console.log("paddleHit 1");
return true;
}
else if(b.x <= p.w && p.x == 0) {
paddleHit = 2;
console.log("paddleHit 2");
return true;
}
else return false;
}
}
//Do this when collides == true
function collideAction(ball, p) {
console.log("**collision**")
ball.vx = -ball.vx;
if(paddleHit == 1) {
ball.x = p.x - p.w;
particlePos.x = ball.x + ball.r;
multiplier = -1;
}
else if(paddleHit == 2) {
ball.x = p.w + ball.r;
particlePos.x = ball.x - ball.r;
multiplier = 1;
}
points++;
increaseSpd();
if(collision) {
//if(points > 0)
// collision.pause();
collision.currentTime = 0;
collision.src = "hit.mp3";
collision.play();
}
particlePos.x = ball.x;
flag = 1;
}
// Function for emitting particles
function emitParticles() {
for(var j = 0; j < particles.length; j++) {
par = particles[j];
ctx.beginPath();
ctx.fillStyle = "black";
if (par.radius > 0) {
ctx.arc(par.x, par.y, par.radius, 0, Math.PI*2, false);
}
ctx.fill();
par.x += par.vx;
par.y += par.vy;
// Reduce radius so that the particles die after a few seconds
par.radius -= 0.05;
}
}
// Function for updating score
function updateScore() {
ctx.fillStlye = "black";
ctx.font = "16px Arial, sans-serif";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Score: " + points, 20, 20 );
}
// Function to run when the game overs
function gameOver() {
ctx.fillStlye = "black";
ctx.font = "20px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Game Over - You scored "+points+" points!", W/2, H/2 + 25 );
// Stop the Animation
cancelRequestAnimFrame(init);
// Set the over flag
over = 1;
// Show the restart button
restartBtn.draw();
if( points > parseInt(readCookie("high-score")) ){
createCookie("high-score", points )
}
}
// Function for running the whole animation
function animloop() {
init = requestAnimFrame(animloop);
draw();
}
// Function to execute at startup
function startScreen() {
draw();
startBtn.draw();
}
// On button click (Restart and start)
function btnClick(e) {
// Variables for storing mouse position on click
var mx = e.pageX - $("#canvas").offset().left,
my = e.pageY - $("#canvas").offset().right;
// Click start button
if(mx >= startBtn.x && mx <= startBtn.x + startBtn.w) {
animloop();
// Delete the start button after clicking it
startBtn = {};
}
// If the game is over, and the restart button is clicked
if(over == 1) {
if(mx >= restartBtn.x && mx <= restartBtn.x + restartBtn.w) {
ball.x = 20;
ball.y = 20;
points = 0;
ball.vx = 6;
ball.vy = 6;
animloop();
over = 0;
}
}
}
var x =0;
var controllerOptions = {enableGestures: true};
var previousFrame = null;
Leap.loop(controllerOptions, function(frame) {
if(x==0){
if(frame){
console.log("Leap sensor detected");
$("#detected").css("color","green");
$("#detected").text("Leap detected")
$("#detected").show()
}
}
x++;
// Frame motion factors
if (previousFrame && previousFrame.valid) {
var translation = frame.translation(previousFrame);
var rotationAxis = frame.rotationAxis(previousFrame);
var rotationAngle = frame.rotationAngle(previousFrame);
var scaleFactor = frame.scaleFactor(previousFrame);
}
// Display Pointable (finger and tool) object data
var pointableOutput = document.getElementById("pointableData");
var pointableString = "";
if (frame.pointables.length > 0) {
mainPointable = frame.pointables[0]
//console.log("main pointer: ")
//console.log(mainPointable.tipVelocity[0]/100 + ", " + mainPointable.tipVelocity[1]/100);
movePaddle(mainPointable.tipVelocity[1]/20);
}
// Store frame for motion functions
previousFrame = frame;
});
function movePaddle(y){
var p2 = paddles[2];
//var x=event.clientX;
//var y=event.clientY;
//console.log("X coords: " + x + ", Y coords: " + y);
if(y){
var oldy = p2.y;
if(oldy-y > 0 && oldy-y < H){
globalY = oldy-y;
p2.y = globalY;
}
//console.log("p.y: ");
//console.log(p.y)
}
}
/*
creates cookies
@param {String} name - of coookie
@param {String} valie - value of coookie
@param {number} days - number of days for coookie to stay active
*/
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
/*
creates cookies
@param {String} name - of coookie
@return {String} valie - value of coookie
*/
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
/*
* erases cookies
* @param {String} name - of coookie
*/
function eraseCookie(name) {
createCookie(name,"",-1);
}