-
Notifications
You must be signed in to change notification settings - Fork 0
/
ball.html
114 lines (111 loc) · 2.79 KB
/
ball.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
<!DOCTYPE html>
<html>
<head>
<meta charset = 'utf-8'>
<title>Ball</title>
<style type = 'text/css'>
body, html {
margin: 0;
width: 100%;
height: 100%;
overflow: none;
}
#main {
position: absolute;
height: 100%;
width: 100%;
top: 0;
right: 0;
left: 0;
bottom: 0;
background-color: #A7C4EB;
}
#ball {
height: 50px;
width: 50px;
border-radius: 100%;
background-color: #2266a4;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div id = 'main'>
<div id = 'ball'>
</div>
</div>
<script type = 'text/javascript'>
// make the ball move
var x = 0;
var dx = 5;
var y = 0;
var dy = 5;
var ball = document.getElementById('ball');
function changeColor() {
var r = Math.floor(Math.random() * (255 - 1) + 1);
var g = Math.floor(Math.random() * (255 - 1) + 1);
var b = Math.floor(Math.random() * (255 - 1) + 1);
ball.style.backgroundColor = "rgb(" + r + ", " + g + ", " + b + ")";
}
document.addEventListener('keydown', function (e) {
if (e.keyCode == 37) { // left
dx--;
} else if (e.keyCode == 39) { // right
dx++;
} else if (e.keyCode == 38) { // up
dy--;
} else if (e.keyCode == 40) { // down
dy++;
} else if (e.keyCode == 32) { // space
ball.style.height = 200 + 'px';
ball.style.width = 200 + 'px';
} else if (e.keyCode == 65) { // a
ball.style.height = 50 + 'px';
ball.style.width = 50 + 'px';
}
});
setInterval(function () {
ball.style.top = y + 'px';
ball.style.left = x + 'px';
x += dx;
y += dy;
if (y + 50 > window.innerHeight) {
dy *= -1;
y = window.innerHeight - 51;
changeColor();
} else if (y < 0) {
dy *= -1;
y = 1;
changeColor();
}
if (x + 50 > window.innerWidth) {
dx *= -1;
x = window.innerWidth - 51;
changeColor();
} else if (x < 0) {
dx *= -1;
x = 1;
changeColor();
}
}, 20);
// document.addEventListener('keydown', function(e) {
// switch (e.keyCode) {
// case 38: // up
// dy--;
// break;
// case 37: // left
// dx--;
// break;
// case 40: // down
// dy++;
// break;
// case 39: // right
// dx++;
// break;
// }
// });
</script>
</body>
</html>