-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
161 lines (139 loc) · 4.08 KB
/
index.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
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
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Snake Game</title>
<style>
body {
width: 99vw;
height: 95vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: gray;
}
#stage {
background-color: black;
height: 70%;
width: 50%;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 50%;
height: 25%;
margin-top: 5vh;
}
.container > div {
background-color: black;
width: 25%;
height: 30%;
}
.container > div:nth-child(2) {
background-color: transparent;
display: flex;
flex-direction: row;
width: 50%;
margin-bottom: 20px;
}
.container > div:nth-child(2) > div {
background-color: black;
width: 50%;
height: 100%;
margin: 10px 10px 10px 10px;
}
</style>
</head>
<body>
<canvas id="stage"></canvas>
<div class="container">
<div></div>
<div>
<div></div>
<div></div>
</div>
<div></div>
</div>
<script type="text/javascript">
window.onload = function() {
var stage = document.getElementById('stage')
var ctx = stage.getContext('2d')
document.addEventListener('keydown', keyPush)
setInterval(game, 100)
const vel = 1;
var vx = vy = 0
var px = 10
var py = 15
var tp = 10
var qp = 30
var ax = ay = 15
var trail = []
tail = 5
function game() {
px += vx
py += vy
if (px < 0) {
px = qp - 1
}
if (px > qp - 1) {
px = 0
}
if (py < 0) {
py = qp - 1
}
if (py > qp - 1) {
py = 0
}
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, stage.width, stage.height)
ctx.fillStyle = 'red'
ctx.fillRect(ax*tp, ay*tp, tp, tp)
ctx.fillStyle = 'gray'
for (let index = 0; index < trail.length; index++) {
ctx.fillRect(trail[index].x*tp, trail[index].y*tp, tp - 1, tp - 1)
if (trail[index].x == px && trail[index].y == py) {
vx = vy = 0
tail = 5
}
}
trail.push({x: px, y: py})
while (trail.length > tail) {
trail.shift()
}
if (ax == px && ay == py) {
tail++
ax = Math.floor(Math.random() * qp)
ay = Math.floor(Math.random() * qp)
}
}
function keyPush(event) {
switch (event.keyCode) {
case 37:
vx = -vel
vy = 0
break;
case 38:
vx = 0
vy = -vel
break;
case 39:
vx = vel
vy = 0
break;
case 40:
vx = 0
vy = vel
break;
default:
break;
}
}
}
</script>
</body>
</html>