在培训的时候老师带着写的一个小游戏,页面上随机出现星星图案,鼠标点击图案消失,可自定义时间,速度等,没有完善过,很粗糙的一个小游戏。
html如下
<body>
<input type="button" value="点击开始游戏" onclick="init()">
<span id="span1">游戏进行0秒</span>
<input type="button" value="暂停游戏" onclick="zanting()">
<span id="span2"><span id="span3"></span></span>
</body>
css如下
<style type="text/css">
#span2{
border:1px solid red;
display:inline-block;
width:100px;
height:20px;
}
#span3{
display:inline-block;
height:20px;
}
</style>
js如下
<script type="text/javascript">
//window.init;
var dingshiqi;//创建星星的定时器
var game=0;//game用来表示游戏时间的
var shijian;//记录时间的定时器
var count=0;//count用来记录星星个数的
function init(){
window.clearInterval(dingshiqi);
window.clearInterval(shijian);
dingshiqi=window.setInterval("newstar()",400);
shijian=window.setInterval("gametime()",1000);
}
function newstar(){
//创建星星
var obj=document.createElement("img");
//给星星添加src属性
obj.src="images/xingxing.gif";
//设置星星随即大小
var w=Math.floor(Math.random()*60)+30;
obj.width=w;
//设置星星随即出现的位置
var x=Math.floor(Math.random()*1200)+30;
var y=Math.floor(Math.random()*500)+60;
obj.style.position="absolute";
obj.style.top=y+"px";
obj.style.left=x+"px";
//把星星放到body中
//记录星星个数
count++;
//游戏进度记录
var jindu=document.getElementById("span3");
jindu.style.width=count*5+"px";
jindu.style.backgroundColor="yellow";
if(count>=20){
window.clearInterval(dingshiqi);
window.clearInterval(shijian);
alert("游戏结束");
}
document.body.appendChild(obj);
obj.onclick=removestar;
}
//删除星星函数
function removestar(){
count--;
var jindu=document.getElementById("span3");
jindu.style.width=count*5+"px";
jindu.style.backgroundColor="yellow";
this.parentNode.removeChild(this);
}
//暂停游戏函数
function zanting(){
alert("暂停游戏");
}
//记录游戏时间的函数
function gametime(){
var obj=document.getElementById("span1");
game++;
obj.innerHTML="游戏进行"+game+"秒";
}
</script>