-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
93 lines (71 loc) · 1.86 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
var canvas;
var paddle;
var balls = [];
class Paddle {
constructor() {
this.x = 0;
this.y = 220;
}
draw() {
ctx.fillStyle = "grey";
ctx.fillRect(this.x, this.y, 20, 100);
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
this.dx = -1 * Math.random();
this.dy = 2 * Math.random();
}
draw() {
// Draw ball
ctx.fillStyle = "yellow";
ctx.fillRect(this.x, this.y, 20, 20);
}
move() {
// Movement
this.x += this.dx;
this.y += this.dy;
}
}
$(document).ready(() => {
document.body.onmousedown = () => { return false; } //so page is unselectable
// Canvas stuff
canvas = $("#canvas")[0];
ctx = canvas.getContext("2d");
w = $("#canvas").width();
h = $("#canvas").height();
init();
paddle = new Paddle();
for (var i = 0; i < 100; i++) {
balls.push(new Ball(Math.random() * 100 + 200, Math.random() * 100));
}
});
////////////////////////////////
//////// GAME INIT
/////// Runs this code right away, as soon as the page loads.
////// Use this code to get everything in order before your game starts
//////////////////////////////
function init() {
requestAnimationFrame(paint);
}
//////////////////////////////////////////////////////
//////// Main Game Engine
////////////////////////////////////////////////////
function paint(timestamp) {
ctx.fillStyle = "red";
ctx.fillRect(0,0, w, h)
paddle.draw();
for (var ball of balls) {
ball.draw();
ball.move();
var right_paddle_x = paddle.x + 20;
var bottom_paddle_y = paddle.y + 100;
var bottom_ball_y = ball.y + 20;
if (ball.x < right_paddle_x && ball.y < bottom_paddle_y && bottom_ball_y > paddle.y) {
ball.dx *= -1;
}
}
requestAnimationFrame(paint);
}/////////////////////////////END PAINT/ GAME ENGINE