-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
73 lines (62 loc) · 2.1 KB
/
script.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
const output = document.querySelector (".output");
const messageOut = document.querySelectorAll (".message span");
let score = 0;
output.addEventListener ("mouseenter", function () {
output.style.backgroundColor = "cyan";
});
output.addEventListener ("mouseleave", function () {
output.style.backgroundColor = "darkcyan";
});
output.addEventListener ("mousemove", function (e) {
messageOut[0].innerText = e.x
messageOut[1].innerText = e.y
});
document.addEventListener ("DOMContentLoaded", function () {
let div = document.createElement ("div");
div.classList.add ("box");
output.appendChild(div);
div.x = div.offsetLeft;
div.y = div.offsetTop;
div.tempColor = "#" + Math.random().toString(16).substr(-6);
div.style.backgroundColor = div.tempColor;
div.addEventListener ("mouseenter", function(e) {
div.style.backgroundColor = "red";
});
div.addEventListener ("mouseleave", function(e) {
div.style.backgroundColor = div.tempColor;
});
div.addEventListener ("click", function(e) {
div.tempColor = "#" + Math.random().toString(16).substr(-6);
div.style.backgroundColor = div.tempColor;
score++;
messageOut[2].innerText = score;
});
div.steps = Math.random() * 20;
div.direction = Math.floor (Math.random() * 4);
window.requestAnimationFrame(move);
})
function move () {
let speed = Math.random() * 4 + 8;
const box = document.querySelector (".box");
let bounds = output.getBoundingClientRect();
box.steps--;
if (box.steps < 0) {
box.direction = Math.floor(Math.random() * 4);
box.steps = Math.random() * 20;
}
if (box.direction == 0 && box.x < bounds.right - 100) {
box.x += speed;
}
if (box.direction == 1 && box.x > bounds.left) {
box.x -= speed;
}
if (box.direction == 2 && box.y < bounds.bottom - 100) {
box.y += speed;
}
if (box.direction == 3 && box.y > bounds.top) {
box.y -= speed;
}
box.style.top = box.y + "px";
box.style.left = box.x + "px";
window.requestAnimationFrame(move);
}