-
Notifications
You must be signed in to change notification settings - Fork 0
/
0921-練習-貓咪躲手手.html
109 lines (105 loc) · 2.54 KB
/
0921-練習-貓咪躲手手.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
<html lang="en">
<head>
<meta charset="UTF-8">
<title>game</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*{
padding: 0;
margin: 0;
}
#game{
width: 300px;
height: 500px;
border: 1px solid black;
margin: auto;
box-sizing: border-box;
}
#character{
width: 100px;
height: 100px;
background-color: red;
position: relative;
top: 300px;
left: 0px;
}
#white{
top: 500px;
z-index: 100;
position: absolute;
width: 300px;
height: 130px;
background-color: white;
}
#block{
width: 100px;
height: 100px;
top: 500px;
background-color: black;
position: relative;
animation: slide 1s infinite linear;
}
@keyframes slide{
0%{top:-100px};
100%{top:500px};
}
#left, #right{
width:50%;
position: absolute;
height: 500px;
}
#right{
left: 50%;
}
</style>
</head>
<body>
<div id="game">
<div id="left"></div>
<div id="right"></div>
<div id="block"></div>
<div id="character"></div>
<div id="white"></div>
</div>
</body>
<script>
document.addEventListener("keydown", event => {
if(event.key==="ArrowLeft"){moveLeft();}
if(event.key==="ArrowRight"){moveRight();}
});
var character = document.getElementById("character");
function moveLeft(){
let left = parseInt(window.getComputedStyle(character).getPropertyValue("left"));
left -= 100;
if(left>=0){
character.style.left = left + "px";
}
}
function moveRight(){
let left = parseInt(window.getComputedStyle(character).getPropertyValue("left"));
left += 100;
if(left<300){
character.style.left = left + "px";
}
}
var block = document.getElementById("block");
var counter = 0;
block.addEventListener('animationiteration', () => {
var random = Math.floor(Math.random() * 3);
left = random * 100;
block.style.left = left + "px";
counter++;
});
setInterval(function(){
var characterLeft = parseInt(window.getComputedStyle(character).getPropertyValue("left"));
var blockLeft = parseInt(window.getComputedStyle(block).getPropertyValue("left"));
var blockTop = parseInt(window.getComputedStyle(block).getPropertyValue("top"));
if(characterLeft==blockLeft && blockTop<500 && blockTop>300){
alert("Game over. Score: " + counter);
block.style.animation = "none";
}
},1);
document.getElementById("right").addEventListener("touchstart", moveRight);
document.getElementById("left").addEventListener("touchstart", moveLeft);
</script>
</html>