小言_互联网的博客

使用javascript实现简单的龟兔赛跑小游戏

218人阅读  评论(0)

使用javascript实现简单的龟兔赛跑小游戏

以下是实现代码

//javascript实现代码
function start(){

	t=document.getElementById('t')
	r=document.getElementById('r')
	t.style.left='200px';
	t.style.top='200px';
	
	r.style.left='200px';
	r.style.top='300px';
	
	t.style.display='block'
	r.style.display='block'
	
	star=setInterval(move,100)
}
function move(){
	t=document.getElementById('t')
	r=document.getElementById('r')
	rleft=r.style.left
	tleft=t.style.left
	
	rleft=Number.parseInt(rleft.split('px')[0])
	tleft=Number.parseInt(tleft.split('px')[0])
	
	rleft+=10
	tleft+=5
	
	t.style.left=tleft+'px';
	r.style.left=rleft+'px';
	
	//alert(t.style.left)
	if(t.style.left=='1000px'){
		clearInterval(star)
		alert('游戏已结束!乌龟取得胜利!')
		t.style.left='200px'
		r.style.left='200px'
		
	}else if(r.style.left=='1000px'){
		clearInterval(star)
		alert('游戏已结束!兔子取得胜利!')
		t.style.left='200px'
		r.style.left='200px'
	}
}
function stop(){
	clearInterval(star)
}
function restart(){
	star=setInterval(move,100)
}

css代码

#map{
	width: 800px;
	height: 400px;
	position: absolute;
	left: 200px;
	top: 100px;
	border: solid 1px #90E090;
	text-align: center;
}
img{
	display: none;
	position: absolute;
	width: 32px;
	height: 32px;
	
}

html代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="css/mystyle.css" />
		<script type="text/javascript" src="js/myjs1.js" ></script>
	</head>
	<body>
		<div id='map'>
			<input type="button" value="开始" onclick="start()"/>
			<input type="button" value="暂停" onclick="stop()"/>
			<input type="button" value="继续" onclick="restart()"/>
		</div>
		<img id='r' src="img/r.jpg" />
		<img id='t' src="img/t.jpg" />
	</body>
</html>

以下为实现展示


转载:https://blog.csdn.net/g1x2w3/article/details/101173258
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场