标签:
之前用WPF的方式做了个简单的小游戏,找不同色块,WPF可以实现,JS更加Easy,于是又用JS做了一个,逻辑差不多,只是代码的实现方式有所不同
先上效果
关键代码如下
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>小游戏</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <script src="Scripts/jquery-1.8.2.min.js"></script> <style> .divHead { height: 50px; vertical-align: middle; line-height: 50px; font-size: 20px; color: #ff6a00; width: 400px; display: block; text-align: center; } .divHead span { font-size: 32px; color: #0094ff; font-weight: bold; } .divContent { width: 400px; position: initial; border: 1px solid #808080; margin: 0; } .divContent .divItem { float: left; display: inline-block; width: 98px; border: 1px solid #ff6a00; background-color: #ffd800; height: 98px; } </style> <script type="text/javascript"> var level = 2; //第一关,2X2 var levelShow = 2; //显示关卡字段 var cavWidth = 400; //定义容器总宽度高度不变,都为400 var itemWidth = 0; //色块宽高 var maxLevel = 8; //最大关卡 var colors = [ ["#FF6B6B", "#F16565"], ["#FF9869", "#E88A5F"], ["#FFB269", "#E8A15F"], ["#FFC369", "#E1AC5C"], ["#F0E663", "#E1D95C"], ["#DAF063", "#D5E960"], ["#FFFF93", "#C1E95B"], ["#8CD74E", "#93DC57"], ["#7FEBC7", "#90FBD7"] ]; //颜色数组 $(function () { onInit(); }); function onInit() { $("#level").html(levelShow - 1); $(".divContent").empty(); //加载数据 itemWidth = cavWidth / level; var otherIndex = GetRandomNum(level * level - 1); //不一样的那个 console.log(otherIndex); //lblLevel.Content = string.Format("第 {0} 关", level - 1); var strs = colors[GetRandomNum(colors.length - 1)]; var colorBtnBg = strs[0]; for (var i = 0; i < level; i++) { for (var j = 0; j < level; j++) { //向容器中添加一个色块(按钮) var item = $(‘<div></div>‘); //创建一个子DIV item.addClass("divItem"); item.css({ ‘width‘: (itemWidth - 2) + ‘px‘, //2为边框宽度 ‘height‘: (itemWidth - 2) + ‘px‘, ‘background-color‘: colorBtnBg }); item.appendTo($(".divContent")); //随机生成的色块编号,颜色换成相近颜色,当点击该色块表示找出差异,进入游戏下一关 if (otherIndex == i * level + j) { //strs[1] var other = $(".divContent").find("div")[otherIndex]; //other.attr("background-color", strs[1]); other.style.backgroundColor = strs[1]; $(other).bind({ click: function () { //达到最大关卡时数量不在增多,否则每次多一排一列色块 if (level <= maxLevel) { level = level + 1; } levelShow = levelShow + 1; onInit(); console.log(level); } }); } //cavContent.Children.Add(btn); } } } //产生随机数 function GetRandomNum(Max) { var Min = 0; var Range = Max - Min; var Rand = Math.random(); return (Min + Math.round(Rand * Range)); } </script> </head> <body> <div class="divHead"> 第<span id="level"></span>关 </div> <div class="divContent"> </div> </body> </html>
标签:
原文地址:http://www.cnblogs.com/chmc/p/5142381.html