<!DOCTYPE html>
<html>
<head>
<title>贪吃蛇</title>
<meta charset="UTF-8">
<style type="text/css">
.map
{
height:600px;
width:900px;
background:#0f0;
}
</style>
</head>
<body>
<div class="map">
<canvas id="canvas" height="600" width="900">
</canvas>
</div>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var snake = []; //定义一条蛇,画蛇的身体
var snakeCount = 6; //初始化蛇的长度
var foodx = 0;
var foody = 0;
var togo = 0;
function DrawSnakeAndFood()
{
for(var k = 0; k < 6; k++)//画蛇的身体
{
ctx.fillRect(snake[k].x, snake[k].y, 15, 15); //前两个数是矩形的起始坐标,后两个数是矩形的长宽。
}
//绘制食物
ctx.fillStyle = "black";
ctx.fillRect(foodx, foody, 15, 15);
ctx.fill();
}
function CreateFood()
{
foodx = Math.floor(Math.random() * 60) * 15; //随机产生一个0-1之间的数
foody = Math.floor(Math.random() * 40) * 15;
for (var k = 0; k < snake; k++)
{
if (foodx == snake[k].x && foody == sanke[k].y) //防止产生的随机食物落在蛇身上
{
CreateFood();
}
}
}
function move()
{
var temp_x = snake[snakeCount-1].x;
var temp_y = snake[snakeCount-1].y;
switch (togo)
{
case 1: snake.push({x:temp_x - 15, y:temp_y}); break; //向左走
case 2: snake.push({x:temp_x, y:temp_y-15}); break;
case 3: snake.push({x:temp_x + 15, y:temp_y}); break;
case 4: snake.push({x:temp_x, y:temp_y+15}); break;
default: snake.push({x:temp_x + 15, y:temp_y}); //默认
}
snake.shift(); //删除数组第一个元素
ctx.clearRect(0, 0, 900, 600); //清除画布重新绘制
EatFood();
CheckDead();
DrawSnakeAndFood();
}
function EatFood() //吃到食物后长度加1
{
if(snake[snakeCount - 1].x == foodx && snake[snakeCount - 1].y == foody)
{
CreateFood();
snakeCount++;
snake.unshift({x:-15, y:-15});
}
}
function CheckDead() /* 如果碰到边框,则死亡 */
{
if (snake[snakeCount-1].x > 885
||snake[snakeCount-1].y > 585
||snake[snakeCount-1].x < 0
||snake[snakeCount-1].y < 0)
{
alert("GAME OVER!");
}
}
document.onkeydown = function(e)
{
switch(e.keyCode)
{
case 37: togo = 1; break; //Left
case 38: togo = 2; break; //Up
case 39: togo = 3; break; //Right
case 40: togo = 4; break; //Down
}
}
window.onload = function()//调用函数
{
for(var k = 0; k < snakeCount; k++)
{
snake[k] = { x: k * 15, y: 0};
}
CreateFood(); //在start中调用添加食物函数
setInterval(move, 150);
DrawSnakeAndFood();
}
</script>
</body>
</html>