-
Notifications
You must be signed in to change notification settings - Fork 2
/
snake.html
95 lines (94 loc) · 2.97 KB
/
snake.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
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<!--[if lte IE 9]><script src="select/selectivizr.js"></script><![endif]-->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" sizes="any" />
<title>Snake</title>
<style>
body ::selection{
color: #FFFFFF;
background: #FF1493;
}
body {
display: flex;
height: 100vh;
margin: 0;
padding: 0;
justify-content: center;
align-items: center;
background: #000000;
color: #FFFFFF;
}
</style>
</head>
<body>
<a href="index.html">
<font style="font-size:28px;color:white;text-shadow: 5px 5px 5px #00FF00;">
<b>
HOMEPAGE
</b>
</font>
</a>
<br />
<canvas id="can" width="400" height="400" style="background-color: plum">
Your browser doesn't support HTML5 canvas, update your IE to at least IE10 and allow 'ActiveX and Script', recommend Google Chrome.
</canvas>
<script>
var snake = [41, 40],
//snake队列表示蛇身,初始节点存在但不显示
direction = 1,
//1表示向右,-1表示向左,20表示向下,-20表示向上
food = 43,
//食物的位置
n,
//与下次移动的位置有关
box = document.getElementById('can').getContext('2d');
//从0到399表示box里[0~19]*[0~19]的所有节点,每20px一个节点
function draw(seat, color) {
box.fillStyle = color;
box.fillRect(seat % 20 *20 + 1, ~~(seat / 20) * 20 + 1, 18, 18);
//用color填充一个矩形,以前两个参数为x,y坐标,后两个参数为宽和高。
}
document.onkeydown = function(evt) {
//当键盘上下左右键按下的时候改变direction
direction = snake[1] - snake[0] == (n = [-1, -20, 1, 20][(evt || event).keyCode - 37] || direction) ? direction : n;
};
!function() {
snake.unshift(n = snake[0] + direction);
//此时的n为下次蛇头出现的位置,n进入队列
if(snake.indexOf(n, 1) > 0 || n < 0 || n > 399 || direction == 1 && n % 20 == 0 || direction == -1 && n % 20 == 19) { //if语句判断贪吃蛇是否撞到自己或者墙壁,碰到时返回,结束程序
return alert("GAME OVER");
}
draw(n, "darkviolet");
//画出蛇头下次出现的位置
if(n == food) {
//如果吃到食物时,产生一个蛇身以外的随机的点,不会去掉蛇尾
while (snake.indexOf(food = ~~(Math.random() * 400)) > 0);
draw(food, "deeppink");
} else {
//没有吃到食物时正常移动,蛇尾出队列
draw(snake.pop(),"plum");
}
setTimeout(arguments.callee, 100);
//每隔x毫秒执行函数一次,可以调节蛇的速度
}();
</script>
<br />
<br />
<button type="button" onclick="alert('Version 1 Stable_Build20171007A GameVersion1.21')">
Version
</button>
<p>
;
</p>
<button type="button" onclick="alert('100ms/step')">
Speed
</button>
<p>
PoweredByYaozeYE
</p>
</body>
</html>