这一节主要根据第一节进行升级,修改内容如下:
- 添加撞墙提示
- 添加食物
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>我的贪吃蛇02</title>
<script type="text/javascript" src="jquery-3.3.1.min.js" ></script>
<script type="text/javascript" src="snake.js" ></script>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<div id="map">
<div id="snake_div">
</div>
<div class="food_div"></div>
</div>
</body>
</html>
index.css
body {
margin: 0;
padding: 0;
}
#map{
width: 800px;
height: 500px;
margin: 10% auto;
background-color:darkgrey ;
position: relative;
}
#snake_div{
width: 50px;
height: 50px;
background-color:red ;
position: absolute;
}
.food_div{
width: 50px;
height: 50px;
margin: 100px 100px;
background-color:yellow ;
position: absolute;
}
snake.js
$(document).ready(function(){
var s_div=$("#snake_div");
var f_div=$(".food_div");
var s_h=parseInt(s_div.css("height"));
var s_w=parseInt(s_div.css("width"));
$(document).keydown(function(e){
var left=parseInt(s_div.css("margin-left"));
var top=parseInt(s_div.css("margin-top"));
var code=e.keyCode;
var move_num=50;
s_div.text("x:"+left+",y:"+top);
var f_x=parseInt(f_div.css("margin-left"));
var f_y=parseInt(f_div.css("margin-top"));
if(f_x==(left+s_h)&&f_y==top){
alert("吃到食物了!!!!!");
}
switch(code){
case 37://左
if(left<1){
alert("撞墙了!!!!!");
s_div.css({"margin-left":0,"margin-top":0});
}else{
s_div.css({"margin-left":left-move_num});
}
break;
case 39://右
if(left+s_w>799){
alert("撞墙了!!!!!");
s_div.css({"margin-left":0,"margin-top":0});
}else{
s_div.css({"margin-left":left+move_num});
}
break;
case 38://上
if(top<1){
alert("撞墙了!!!!!");
s_div.css({"margin-left":0,"margin-top":0});
}else{
s_div.css({"margin-top":top-move_num});
}
break;
case 40://下
if(top+s_h>499){
alert("撞墙了!!!!!");
s_div.css({"margin-left":0,"margin-top":0});
}else{
s_div.css({"margin-top":top+move_num});
}
break;
}
});
});