JS100行代码实现 贪吃蛇 ,快写给你的女朋友
YPE html>
标签:html load() code star screen start doctype white next
`;
}
document.getElementById(‘root‘).innerHTML = map;
}
//生成地图 end
let snake_list = [0]; //蛇身
let snake_length = 1; //蛇身长度
let block_list = document.getElementsByClassName(‘block‘); //方格列表
function creat_food(){ //生成食物
let sub = 0;
if(snake_list.length / (w_size * h_size) ){
sub = Math.floor(Math.random()*(w_size*
h_size));
while(block_list[sub].style.backgroundColor !=
BLOCK_COLOR){
sub = Math.floor(Math.random()*(w_size*
h_size));
}
}else{
let block_arr =
[];
for(let i = 0, len = w_size * h_size; i i){
if(block_list[i].style.backgroundColor ==
BLOCK_COLOR){
block_arr.push(i);
}
}
sub = block_arr[Math.floor(Math.random()*
(block_arr.length))];
}
block_list[sub].style.backgroundColor =
FOOD_COLOR;
}
let dir = 4;
//移动方向(上:1下:2左:3右:4)
function move(){
//移动
let handle =
function(next){
let max = next > snake_list[snake_length - 1] ? next : snake_list[snake_length - 1
];
if(
block_list[next] == undefined ||
block_list[next].style.backgroundColor == BODY_COLOR ||
(
Math.abs(next - snake_list[snake_length - 1]) == 1 &&
max % w_size == 0
)
){
clearInterval(js);
alert("得分:" +
snake_length);
location.reload();
}else if(block_list[next].style.backgroundColor ==
FOOD_COLOR){
block_list[snake_list[snake_length - 1]].style.backgroundColor =
BODY_COLOR;
snake_list.push(next);
++
snake_length;
block_list[next].style.backgroundColor =
HEAD_COLOR;
creat_food();
}else{
block_list[snake_list[snake_length - 1]].style.backgroundColor =
BODY_COLOR;
block_list[snake_list[0]].style.backgroundColor =
BLOCK_COLOR;
snake_list.shift();
snake_list.push(next);
block_list[snake_list[snake_length - 1]].style.backgroundColor =
HEAD_COLOR;
}
};
switch(dir){
case 1
:
handle(snake_list[snake_length - 1] -
w_size);
break;
case 2
:
handle(snake_list[snake_length - 1] +
w_size);
break;
case 3
:
handle(snake_list[snake_length - 1] - 1
);
break;
case 4
:
handle(snake_list[snake_length - 1] + 1
);
break;
default:
;
}
}
document.onkeypress =
function(e){
let theEvent = e ||
window.event;
let code = theEvent.keyCode || theEvent.which ||
theEvent.charCode;
switch(code){
case 38:
case 119
:
(dir == 1 || dir == 2) ?
void 0 : dir = 1
;
break;
case 37:
case 97
:
(dir == 3 || dir == 4) ?
void 0 : dir = 3
;
break;
case 40:
case 115
:
(dir == 1 || dir == 2) ?
void 0 : dir = 2
;
break;
case 39:
case 100
:
(dir == 3 || dir == 4) ?
void 0 : dir = 4
;
break;
default:
;
}
};
block_list[snake_list[0]].style.backgroundColor =
HEAD_COLOR;
creat_food();
js = setInterval(move, 300
);
代码易读不用解释,只提一个事,蛇移动的时候,没必要每个部位都动,只处理头尾就可以了,这个应该也是显而易见的
JS100行代码实现 贪吃蛇 ,快写给你的女朋友
标签:html load() code star screen start doctype white next
原文地址:https://www.cnblogs.com/zhenfeishi/p/13399314.html
评论