1 <!DOCTYPE HTML>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>Snake</title>
6 <style>
7 canvas{width:100%;height:100%;border:solid 1px;}
8 </style>
9 </head>
10
11 <body>
12 <canvas id="snake" width="600" height="400">
13 </canvas>
14 <button id="startGame">Start Game</button>
15 <script>
16 var ctx=document.querySelector("#snake").getContext("2d");
17 var startBtn=document.querySelector("#startGame");
18 var snake=[{x:-1,y:-1}];//蛇
19 var perLen=9;//单位长度
20 var food={x:-1,y:-1};//食物
21 var direction;//蛇移动的方向
22 window.onload=function(){
23 startBtn.addEventListener("click",initGame,false);
24 }
25 var initGame=function(){
26 startBtn.disabled = true;//如果游戏已经开始了,就不要再点了。
27 snake[0].x= Math.floor(Math.random() *59)*10;
28 snake[0].y= Math.floor(Math.random() * 39)*10;
29 direction=Math.ceil(Math.random()*4);
30 //direction=2;//test
31 for(i=0;i<3;i++){
32 switch(direction){
33 case 1:
34 snake.push({ x: snake[i].x, y:snake[i].y+10 });
35 break;
36 case 2:
37 snake.push({ x: snake[i].x-10, y:snake[i].y });
38 break;
39 case 3:
40 snake.push({ x: snake[i].x, y:snake[i].y -10});
41 break;
42 case 4:
43 snake.push({ x: snake[i].x+10, y:snake[i].y });
44 break;
45 }
46 }
47 for(i=0;i<snake.length;i++){//画个蛇
48 ctx.fillStyle = '#FF0000';
49 ctx.fillRect(snake[i].x,snake[i].y,perLen,perLen);
50 }
51 setInterval(function(){snakeMove(direction)},200);
52 //snakeMove(direction);//test
53 drawFood();
54 document.onkeydown = function (e) {
55 var key = e.keyCode || e.which || e.charCode;
56 if ((key == 38 || key == 87)&&direction!=3) direction=1; //上或者W被按下
57 if ((key == 39 || key == 68)&&direction!=4) direction=2; //右或者D被按下
58 if ((key == 40 || key == 83)&&direction!=1) direction=3; //下或者S被按下
59 if ((key == 37 || key == 65)&&direction!=2) direction=4; //左或者A被按下
60 }
61 }
62 var drawFood=function(){
63 while(food.x==snake[0].x&&food.y==snake[0].y||food.x==-1){//食物不能与蛇头重复
64 food.x= Math.floor(Math.random() *59)*10;
65 food.y= Math.floor(Math.random() * 39)*10;
66 }
67 ctx.fillStyle = '#00FF00';
68 ctx.fillRect(food.x,food.y,perLen,perLen);//画个吃的
69 }
70 var snakeMove=function(direction){
71 if(snake[0].x==food.x&&snake[0].y==food.y){
72 drawFood();
73 }
74 else if(snake[0].x==0||snake[0].x==600||snake[0].y==0||snake[0].y==400){
75 alert("Game Over!");
76 location.reload();
77 }
78 else{
79 ctx.clearRect(snake[snake.length-1].x,snake[snake.length-1].y,perLen+1,perLen+1);
80 snake.pop();
81 }
82 switch(direction){
83 case 1:
84 snake.unshift({x:snake[0].x,y:snake[0].y-10});//向上移动
85 break;
86 case 2:
87 snake.unshift({x:snake[0].x+10,y:snake[0].y});//向右移动
88 break;
89 case 3:
90 snake.unshift({x:snake[0].x,y:snake[0].y+10});//向下移动
91 break;
92 case 4:
93 snake.unshift({x:snake[0].x-10,y:snake[0].y});//向左移动
94 break;
95 }
96 ctx.fillStyle = '#FF0000';
97 ctx.fillRect(snake[0].x,snake[0].y,perLen,perLen);
98 }
99 </script>
100 </body>
101 </html>