如何用JavaScript做一个贪吃蛇游戏,贪吃蛇系列_02自动走



<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			*{
				margin:0; 
				padding:0;
				list-style: none
			}
			.divClass{
				position:absolute;
				width:20px;
				height:20px;
				background-color:pink;
				border-radius:50%;
			}
			#box{
				position:relative;
			}
		</style>
	</head>
	<body style="height:1000px">
		<div id="box">
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass"></div>
			<div class="divClass">头</div>
		</div>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<br/>
		<input id="btnRight" type="button" value="右移"   />
		<input id="btnDown" type="button" value="下移"   />
		<input id="btnUp" type="button" value="上移"   />
		<input id="btnLeft" type="button" value="左移"   />
	</body>
</html>
<script type="text/javascript" src="js/tools.js"></script>
<script type="text/javascript" src="js/moveJS1705.js"></script>
<script type="text/javascript">

//蛇的每一节的宽和高(20)
var unitWidth = 20;
var unitHeight = 20;
var direction = "右";

function initUI(){
	let divObjs = $("#box").children;
	for(let i=0;i<divObjs.length;i++){
		divObjs[i].style.left = i*unitWidth+"px";
		divObjs[i].style.top = "20px";
	}
}

function startGo(){
	setInterval(goStep,200);
}

//
function goStep(){
	let divObjs = $("#box").children;
	for(let i=0;i<divObjs.length-1;i++){
		divObjs[i].style.left = divObjs[i+1].style.left;
		divObjs[i].style.top = divObjs[i+1].style.top;
	}	
	switch(direction){
		case "左":{
			//改变蛇头的位置
			let left = parseInt(divObjs[divObjs.length-1].style.left);
			divObjs[divObjs.length-1].style.left = left-unitWidth+"px";
		} break;
		case "上":{
			//改变蛇头的位置
			let top = parseInt(divObjs[divObjs.length-1].style.top);
			divObjs[divObjs.length-1].style.top = top-unitHeight+"px";
		} break;
		case "右":{
			//改变蛇头的位置
			let left = parseInt(divObjs[divObjs.length-1].style.left);
			divObjs[divObjs.length-1].style.left = left+unitWidth+"px";
		} break;
		case "下":{
			//改变蛇头的位置
			let top = parseInt(divObjs[divObjs.length-1].style.top);
			divObjs[divObjs.length-1].style.top = top+unitHeight+"px";
		} break;
		default:;
	}	
}


window.onload = function(){
	initUI();
	startGo();
}
</script>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值