-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.html
More file actions
124 lines (110 loc) · 2.56 KB
/
Snake.html
File metadata and controls
124 lines (110 loc) · 2.56 KB
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> </title>
</head>
<body>
<canvas id="myCanvas" width="1366" height=768" style="border:1px solid #d3d3d3" >
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas")
var cxt=c.getContext("2d")
cxt.fillRect(20,20,20,20)//绘制“已填色”的矩形。默认的填充颜色是黑色
cxt.strokeRect(20,20,1300,560)//绘制矩形(无填充)。笔触的默认颜色是黑色
var x=1300,y=20
var d=2
var foodX=30,foodY=30
var body=new Array()//声明数组存储蛇的身体坐标
body.push({px:x,py:y})//蛇的头部坐标
function go()
{
cxt.clearRect(20,20,1300,560)//清空一个区域的矩形范围
cxt.fillStyle="red"
for(var i=0;i<body.length;i++)//遍历蛇身,画出蛇的每个节点
{
cxt.fillRect(body[i].px,body[i].py,20,20)
}
setTimeout("go()",500)
cxt.beginPath();//画圆形
cxt.arc(foodX,foodY,10,0,2*Math.PI)
cxt.closePath();
cxt.fillStyle="green";
cxt.fill()
if(x+10==foodX&&y+10==foodY)
{
body.unshift({px:x,py:y})//在头部添加一个新节点
foodX=parseInt((Math.random()*1300/20))*20+30//食物出现
foodY=parseInt((Math.random()*560/20))*20+30
}
if(d==2)
{
x=x+20
}
if(d==3)
{
y=y+20
}
if(d==0)
{
x-=20
}
if(d==1)
{
y-=20
}
if(x>1300)
{
x=20
}
if(y>560)
{
y=20
}
if(x<20)
{
x=1300
}
if(y<20)
{
y=560
}
body.unshift({px:x,py:y})//添加蛇头
body.pop()//删除蛇尾节点
}
function moveRight()
{
d=2
}
function moveDown()
{
d=3
}
function moveUp()
{
d=1
}
function moveLeft()
{
d=0
}
go()
document.onkeydown=KeyDown
//方向
function KeyDown() {
Key=event.keyCode
switch(Key) {
case 37:
moveLeft();break; //左方向键
case 39:
moveRight();break; //右方向键
case 38:
moveUp();break; //上方向键
case 40:
moveDown();break; //下方向键
}
return false
}
</script>
</body>
</html>