简单贪吃蛇

 

 

简单贪吃蛇_第1张图片

在游戏开始时,分数为0,游戏结束时会弹出分数。

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>贪吃蛇</title>
<style>
*{padding: 0;margin: 0;}
#layer{border-collapse:collapse; border-spacing:0;}
#layer td{width: 40px;height: 20px;}
#controller{margin-top: 50px;}
#layer td.snake{background-color:green}
#layer td.food{background-color:red}
#show_score{
position:absolute;
top:70px;
left:180px;
width:100px;
height:40px;
}
#button{width:150px;
height:50px}
</style>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
</head>
<body>
<center>

<input id="show_score" type="reset" value="score:0">

<div id="controller">
<!--不知道怎么用button传参数-->

<button onclick="ready()" id="button">开始游戏</button>

<script>

</script>
<table id="layer" background='background.jpg'></table>
</center>
<script>
function ready(){
//绘制地图
var layer={x:20,y:20}
var str='';
var score = 0;
for (var y = 1; y<=layer.y; y++) {
str+='<tr>';
for (var x = 1; x<=layer.x; x++) {
str+='<td id="'+x+'_'+y+'"></td>';//?
};
str+='</tr>';
};
$('#layer').html(str);
//放置小蛇
var moveTime=500;
var sanke=[{//蛇的数组
x:Math.floor(layer.x/2),//得到一个数的整数
y:Math.floor(layer.y/2)
}];

var snakHead=sanke[0].x+'_'+sanke[0].y;
$('#'+snakHead).addClass('snake');

//改变方向
var direction=38;
function go(num){direction=num;}

//监听键盘
$(document).keydown(function(event){ go(event.keyCode); });
//小蛇移动
function snakeMove(){
var nextPoint={};
switch(direction){
case 38://上
nextPoint.x=sanke[0].x;nextPoint.y=sanke[0].y-1;
break;
case 40://下
nextPoint.x=sanke[0].x;nextPoint.y=sanke[0].y+1;
break;
case 37://左
nextPoint.x=sanke[0].x-1;nextPoint.y=sanke[0].y;
break;
case 39://右
nextPoint.x=sanke[0].x+1;nextPoint.y=sanke[0].y;
break;
}
var nextBody=$('#'+nextPoint.x+'_'+nextPoint.y);//?

if(nextBody.length>0){
if(nextBody.hasClass('snake')){
alert('自残而死!你的得分为'+score);clearInterval(timer);
}else{
sanke.unshift(nextPoint);//蛇头增加
nextBody.addClass('snake');

if(nextBody.hasClass('food')){
nextBody.removeClass('food');
makeFood();
//分数
score++;
var show_score = document.getElementById('show_score');
show_score.value="score:"+score;
}else{
var lastSnake=sanke[sanke.length-1];
$('#'+lastSnake.x+'_'+lastSnake.y).removeClass('snake');
sanke.pop();//删除尾部 
}
}
}else{
alert('撞墙而死!你的得分为'+score);clearInterval(timer);
}
}

//随机产生食物
function makeFood(){
var empty=$('#layer td:not(.sanke)');
var rnd=Math.floor(Math.random() * (empty.length- 1));
empty.eq(rnd).addClass('food');
}

//动画
makeFood();
var timer=setInterval(snakeMove,moveTime);
}
</script>

</body>
</html>

 

你可能感兴趣的:(简单贪吃蛇)