HTML+js实现简单的打地鼠小游戏

首先是内容和样式
这里是建立了3*3的方格
statu属性用于记录是否砸中了地鼠

	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		.main{
			width: 300px;
			height: 300px;
			margin:100px auto;
		}
		tr{
			height: 100px;
		}
		td{
			width: 100px;
		}
		
	</style>
	<body>
		<div class="main">
		<form>
			<div class="curResult">
				<input type="text" id="time" value="剩余时间"/>
				<input type="text" id="put" value="打到0个"/>
			</div>
			<div>
			<table frame="box" rules="all">
				<tr>
					<td id="0" onclick="onClick(this)" state="no"></td>
					<td id="1" onclick="onClick(this)" state="no"></td>
					<td id="2" onclick="onClick(this)" state="no"></td>
				</tr>
				<tr>
					<td id="3" onclick="onClick(this)" state="no"></td>
					<td id="4" onclick="onClick(this)" state="no"></td>
					<td id="5" onclick="onClick(this)" state="no"></td>
				</tr>
				<tr>
					<td id="6" onclick="onClick(this)" state="no"></td>
					<td id="7" onclick="onClick(this)" state="no"></td>
					<td id="8" onclick="onClick(this)" state="no"></td>
				</tr>
			</table>
		 </div>
		 <input type="button" onclick="start()" value="开始"/>
		</form>
		<div/>
	</body>

然后是script

<script>
		
		var curCount;
		var ranCount;
		var curTotal=0;
		var Count = document.getElementsByTagName("td");
		var time = 10;  //初始时间为10
        var overRandom;
        var overClear;
		var overSub;
		
		function randomCount(){
			var ran = Math.random()*9|0;//随机一个1到9的数
			curCount = document.getElementById(ran);
			curCount.style.backgroundImage="url(img/1.jpg)"; //背景图片为地鼠出现
			curCount.style.backgroundSize="cover";
			curCount.state="yes";                            
			ranCount=ran;
		}
		//清空9个方格
		function clear(){
			for(var i=0;i<9;i++){
		       var forCount = document.getElementById(i);
			   forCount.style.backgroundImage="url(img/0.jpg)";
			   forCount.style.backgroundSize="cover";
			   forCount.state="no";
			}
		}
		//点击砸中地鼠
		function onClick(v){
			
		    if(v.state=="yes"){
			v.style.backgroundImage="url(img/2.jpg)";
			v.style.backgroundSize="cover";
			curTotal++;
			document.getElementById("put").value="打到"+curTotal+"个";
		    }
		    
		}
		//时间减少
		function timeSub(){
			time--;
		    document.getElementById("time").value="剩余时间"+time+"s";
		    if(time<=0){
		    	window.clearInterval(overRandom);
		    	window.clearInterval(overClear);
		    	window.clearInterval(overSub);
		    	clear();
		    	alert("游戏结束,你打到了"+curTotal+"个");
		    }
		}
		//用定时器周期生成和清空地鼠
		function start(){
		 time=10;
		 curTotal=0;
		 overRandom = window.setInterval("randomCount()",600);
		 overClear = window.setInterval("clear()",2100);
		 overSub = window.setInterval("timeSub()",1000);
		}
	</script>

效果演示
在这里插入图片描述

  • 12
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值