Javascript实现找不同色块的游戏

编程入门 行业动态 更新时间:2024-10-11 07:35:19

Javascript实现找不<a href=https://www.elefans.com/category/jswz/34/1008694.html style=同色块的游戏"/>

Javascript实现找不同色块的游戏

游戏规则:在变化数量的颜色块里找出一个不同颜色的块点击

这里使用了JS中的构造函数来创建元素

<!DOCTYPE html>
<html>
<head lang="en"><meta charset="UTF-8"><title>找不同色块的游戏(构造函数)</title>
</head>
<style>*{margin: 0;padding: 0;}#box{width: 600px;height: 600px;margin: auto;margin-top: 100px;}#score{width: 180px;height: 50px;line-height: 150%;font-size: 2em;position: absolute;top: 30px;left: 35%;}.creat{float: left;border-radius: 100%;}
</style>
<body><div id="score">关卡:1</div><div id="box"></div><script>var n=1;//关卡值var Create=new creat(3);//定义构造函数对象,传入一个参数(开始时的布局3x3)Create.go();//调用构造函数里面的函数属性function creat(event){//定义构造函数creatvar obox=document.getElementById("box");this.className="creat";//设置classNamethis._creat=null;//事先创建出一个属性_creat用于指向一个对象this.go=function(){//创建颜色块的方法函数var colorNum1=Math.floor(Math.random()*253)+1;//随机数取一个值范围是(1~254)防止白色块出现var colorNum2=Math.floor(Math.random()*253)+1;var colorNum3=Math.floor(Math.random()*253)+1;this.color="rgb("+colorNum1+","+colorNum2+","+colorNum3+")";//定义rgb颜色属性this.diffOpacity=0.7;//用于改变其中一个颜色快的颜色(这里可以自定义改变透明度)for(var i=0;i<event*event;i++){//创建循环循环event*2次,每当点击颜色块后event变化this._creat=document.createElement("div");//动态创建一个div赋给this._creat属性this._creat.style.width=Math.floor(600/event)+"px";//设置div的宽,高,颜色和classNamethis._creat.style.height=Math.floor(600/event)+"px";this._creat.style.backgroundColor=this.color;this._creat.className=this.className;//在样式中给div左浮动obox.appendChild(this._creat);//作为孩子添加到obox中}var odiv=document.getElementsByClassName("creat");//获取一下创建好的divvar numRandom=parseInt(Math.random()*odiv.length);//随机取到其中一个改变其透明度值odiv[numRandom].style.opacity=this.diffOpacity;odiv[numRandom].onclick=function(){/*给取到的div绑定事件,当点击时先清空obox中元素即上一关卡的div*获取score改变n的值*改变event的值,可以自定义难度*再调用一下调用构造函数里面的go函数属性,创建一组新的元素*/var oScore=document.getElementById("score");n++;oScore.innerHTML="关卡:"+n+"";obox.innerHTML="";event++;Create.go();}}}</script>
</body>
</html>

更多推荐

Javascript实现找不同色块的游戏

本文发布于:2024-02-06 08:23:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1747406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:同色   游戏   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!