//1.定义地图类
function Map(){
//1.1定义地图的属性
this.width = 800;
this.height = 400;
this.color = "gray";
this.position = "absolute";
//1.2定义show方法,用于显示地图
this.show = function(){
//生成div元素,用于放置地图
var div = document.createElement('div');
//为div元素生成属性
div.style.width = this.width+"px";
div.style.height = this.height+"px";
div.style.backgroundColor = this.color;
div.style.position = this.position;
//把div放入body元素中
document.getElementsByTagName('body')[0].appendChild(div);
}
}
//2.定义实物类
function Food(){
//2.1定义事物的属性
this.width = 20;
this.height = 20;
this.color = "green";
this.position = "absolute";
this.x = 0;//40
this.y = 0;//20
//2.2定义show方法,用于随机显示食物
this.show = function(){
//生成div元素,用于放置食物
var div = document.createElement('div');
//为div元素生成属性
div.style.width = this.width+'px';
div.style.height = this.height+'px';
div.style.backgroundColor = this.color;
div.style.position = this.position;
div.style.left = this.x*20+'px';
div.style.top = this.top*20+'px';
//把生成的div追加到地图中
map._map.appendChild(div);
//随机显示食物的坐标
var left,top;
left = Math.floor(Math.random()*40);
top = Math.floor(Math.random()*20);
}
}
//3.定义蛇类
function Snake(){
//3.1定义相关的属性和方法
this.width = 20;
this.height = 20;
this.position = 'absolute';
//定义蛇节
this.body = [[3,2,'red'],[2,2,'blue'],[1,2,'blue']];
//定义show方法,显示蛇类
this.show = function(){
var length = this.body.length;
for(var i=0;i
var div = document.createElement('div');
div.style.width = this.width+'px';
div.style.height = this.height+'px';
div.style.position = this.position;
div.style.left = this.body[i][0]*20+'px';
div.style.top = this.body[i][1]*20+'px';
div.style.backgroundColor = this.body[i][2];
//追加div到map地图中
map._map.appendChild(div);
}
}
this.move = function(){
//获取蛇节
var length = this.body.length;
for(var i=length-1;i>0;i--){
this.body[i][0] = this.body[i-1][0];
this.body[i][1] = this.body[i-1][1];
}
//判断蛇的运动方向
if(this.direct == 'left'){
this.body[0][0] -= 1;
}
if(this.direct == 'right'){
this.body[0][0] += 1;
}
if(this.direct == 'up'){
this.body[0][1] -= 1;
}
if(this.direct == 'down'){
this.body[0][1] += 1;
}
//判断是否吃到食物
if(this.body[0][0] == food.x&&this.body[0][1]==food.y){
//吃到食物,增加身体
this.body.push([0,0,'blue',null]);
//重新显示食物坐标
food.show();
}
//重新显示蛇类
this.show();
}
//定义setDirect方法,用于判断蛇的运动方向
this.setDirect = function(){
switch(code){
case 37:
this.direct = 'left';
break;
case 38:
this.direct = 'up';
break;
case 39:
this.direct = 'right';
break;
case 40:
this.direct = 'down';
break;
}
}
//
}
//4.定义页面载入事件
window.οnlοad=function(){
//实例化地图
var map = new Map();
//显示地图
map.show();
//实例化食物
var food = new Food();
//显示食物
food.show();
//实例化蛇类
var snake = new Snake();
//显示蛇
snake.show();
snake.move();
setInterval("snake.move",300);
document.onkeydown = function(event){
//定义一个code
var code;
if(window.event){
code=window.event.keyCode;
}else {
code = event.keyCode;
}
snake.setDirect(code);
}
}
一键复制
编辑
Web IDE
原始数据
按行查看
历史