var canvas = document.getElementById ("snakeCanvas");
var ctx = canvas.getContext("2d"); //理解成画笔
var width = 15; //每一个小方格的宽度
//指定初始长度为6
var snakeLen = 6;
var snake = []; //蛇的身体
for (var i = 0; i < snakeLen; i++)
{
snake[i] = new Cell(i, 0, -1);
}
//初始食物的x,y
var foodX = 0;
var foodY = 0;
//定义食物对象
var food;
//蛇的身体构成的元素 x坐标 y坐标 d (1:左边, -1:右边, 2:上, -2:下)
function Cell(x, y, d){
this.x = x;
this.y = y;
this.d = d;
return this;
}
//定义一个食物对象
function Food(x, y){
this.x = x;
this.y = y;
return this;
}
//绘制游戏基本元素
function draw () {
//清空整个画布
ctx.clearRect(0, 0, 600, 525);
//绘制网格
for (var i = 0; i < 40; i ++)
{
ctx.strokeStyle="#ccc"; //线条
ctx.beginPath();
//绘制横线
ctx.moveTo(0, i * width);
ctx.lineTo(600, i * width);
//绘制竖线
ctx.moveTo(i * width, 0);
ctx.lineTo(i * width, 525);
ctx.closePath();
ctx.stroke();
}
//绘制蛇的身体
for (var i = 0; i < snake.length; i++)
{
ctx.fillStyle = "black"; //填充颜色
//蛇的头部
if (i == snake.length -1)
{
ctx.fillStyle="red";
}
ctx.beginPath ();
ctx.rect(snake[i].x * width, snake[i].y * width, width, width);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
drawFood ();
}
//初始化食物的x,y坐标,随机产生
function initFood (){
// Math.random() 返回一个0~1之间的数
// Math.ceil(0.1) 返回到1
foodX = Math.ceil(Math.random() * 38 + 1);
foodY = Math.ceil(Math.random() * 33 + 1);
//判断是否跟蛇的身体有重叠
for (var i = 0; i < snake.length; i++)
{
if (snake[i].x == foodX && snake[i].y == foodY)
{
initFood (); //递归产生食物坐标
}
}
}
//绘制食物
function drawFood () {
initFood ();
food = new Food (foodX, foodY);
ctx.fillStyle = "green";
ctx.beginPath ();
ctx.rect(food.x * width, food.y * width, width, width);
ctx.closePath();
ctx.fill();
}
draw ();
</script>
有人可以告诉我后面的要怎样继续做下去吗?
没做过,不过也想做一下
http://bbs.csdn.net/topics/390988009
定义方向类,坐标类,根据方向定时移动坐标,还要提前思考到坐标是否有身体
这个以前做过的一个游戏,很简单的,js中有个函数setInterval做定时功能的可以去看看,一秒中移动一次就行了。