Html5代码一条蛇如果碰到自己就会死
代码如下:
复制代码
代码如下:
var画布;
var ctx
var定时器;
//度量值
var x _ CNT = 15;
var y _ CNT = 15;
var单位= 48;
var box _ x = 0;
var box _ y = 0;
var box_width = 15 *单位;
定义变量
box_height = 15 *单位;
var bound _ left = box _ x;
var bound_right = box_x
+box _ width;
var bound _ up = box _ y;
var bound _ down = box _ y+box _ height;
//图像
var image _ sprite
//对象
var蛇;
var食物;
var food _ x;
var food _ y;
//函数
功能角色(sx,sy,sw,
sh、方向、状态、速度、图像、标志)
{
this.x = sx
this.y =
sy;
this.w = sw
this.h = sh
this.direction =方向;
this.status = status
this.speed =速度;
this.image = image
this.flag = flag
}
功能转移(键码)
{
转换
(键码)
{
案例37:
返回1;
案例38:
返回3;
情况
39:
return 2;
案例40:
返回0;
}
}
函数addFood()
{
//food _ x = box _ x+math . floor(math . random()*(box _ width-unit));
//food _ y = box _ y+math . floor(math . random()*(box _ height-unit));
food_x =
unit * math . floor(math . random()* x _ CNT);
food_y =单位*
math . floor(math . random()* y _ CNT);
food =新角色(food_x,food_y,unit
unit,0,0,0,image_sprite,true);
}
功能播放(事件)
{
定义变量
键码;
if (event == null)
{
key code = window . event . key code;
window . event . prevent default();
}
其他
{
键码=
event.keyCode
event . prevent default();
}
var cur_direction =
转移(键码);
蛇[0]。方向= cur _ direction
}
功能
更新()
{
//在移动蛇之前向蛇添加新的部分
如果
(蛇[0]。x == food。& amp蛇[0]。y == food.y)
{
变量长度=
蛇.长度;
var tail _ x = snake[length-1]。x;
var tail_y =
蛇[长度- 1]。y;
var tail =新角色(tail_x,tail_y,unit,unit,
蛇[长度- 1]。方向,0,0,image_sprite,true);
snake.push(尾巴);
add food();
}
//修改属性
//移动头部
转换
(蛇[0]。方向)
{
案例0://向下
蛇[0]。y +=单位;
如果
(蛇[0]。y & gt下界单位)
蛇[0]。y = bound _ down-unit;
打破;
案例1: //left
蛇[0]。x -=单位;
if (snake[0].x & lt
绑定_左)
蛇[0]。x = bound _ left
打破;
案例2://对
蛇[0]。x +=单位;
if (snake[0].x & gt有界_右-单位)
蛇[0]。x = bound _ right-unit;
打破;
案例3://上
蛇[0]。y
-=单位;
if (snake[0].y & lt装订好的)
蛇[0]。y = bound _ up
打破;
}
//移动蛇的其他部分
for(var I = snake . length-1;我
& gt= 0;我-)
{
如果(i & gt0)
//snake[i]。方向=蛇[i-1]。方向;
{
蛇[我]。x = snake[i -
1].x;
蛇[我]。y = snake[i - 1]。y;
}
}
}
功能
绘图场景()
{
ctx.clearRect(box_x,box_y,box_width,box _ height);
ctx.strokeStyle = "rgb(0,0,0 ";
ctx.strokeRect(box_x,box_y,box_width,
box _ height);
//检测冲突
//绘制图像
for(var I = 0;我
& lt蛇.长度;i++)
{
ctx.drawImage(image_sprite,snake[i])。x,
蛇[我]。y);
}
ctx.drawImage(image_sprite,food.x,food . y);
}
函数init()
{
canvas = document . getelementbyid(" scene ");
ctx
= canvas . get context(' 2d ');
//图像
Image _ sprite = new Image();
image _ sprite . src = " images/sprite . png ";
image_sprite.onLoad =函数
()
{}
//对象
snake = new Array();
var head =新角色(0 *
unit,0 * unit,unit,unit,5,0,1,image_sprite,true);
snake.push(头);
window . addevent listener(' keydown ',play,false);
add food();
setInterval(更新,300);//注意
setInterval(drawScene,30);
}
望采纳!!!!