首页 > 代码库 > 消方块小游戏

消方块小游戏

体验地址:

http://www.renyugang.cn/html/h5/

http://www.renyugang.cn/html/h5/oop/

效果图:

 

代码:

<!DOCTYPE html>
<html>
<head>
<title>H5 Game</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="Cache-control" content="no-cache"/>
    <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,user-scalable=no"/>
    <meta name="oupengmobile" content="game,fullscreen,lockrotation,portrait"/>
    <meta name="tencent-x5-page-direction" content="portrait">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="white">
    <meta name="HandheldFriendly" content="true"/>
    <META HTTP-EQUIV="pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
    <META HTTP-EQUIV="expires" CONTENT="0">
<link href=http://www.mamicode.com/"css/main.css" rel="stylesheet" type="text/css" />>

html, body
{
	margin:0px;
	padding:5px;
	line-height:10px;
}

@-webkit-keyframes myfirst
{
from{top:20px,left:23px}
to {top:420px,left:23px}
}

.animation
{
-webkit-animation:myfirst 5s linear;
}

#gamezone 
{ 
	padding-top:10px;
	padding-left:23px;
	padding-right:23px;
	width:425px;
	height:420px;
	margin:0 auto;
	background-color:white;
	background-image:url("../images/bg.png");
	background-repeat:no-repeat;
	text-align:left;
}

#gamezone div,.div_-2
{
	background-color:#ffffff;
	width:25px;
	height:25px;
	padding:0px;
	display:inline-block;
	letter-spacing:1px;
	
	/* only for ie*/
	*display:inline;
	zoom:1;
	
	border:0px solid #ffffff;
	border-radius:5px;
	-moz-border-radius:5px; /* Old Firefox */
}
#title
{
	width:425px;
	height:150px;
	padding:0px;
	display:block;
}
.color_-1
{
/*background-color:rgb(210,210,210);*/
opacity:0;
}
.color_0
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(204,204,104)))
}
.color_1
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(0,100,255)))
}
.color_2
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(110,206,206)))
}
.color_3
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(204,101,204)))
}
.color_4
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(204,101,0)))
}
.color_5
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(187,187,187)))
}
.color_6
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(0,202,0)))
}
.color_7
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(255,101,101)))
}
.color_8
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(255,135,255)))
}
.color_9
{
background: -webkit-gradient(linear, 0% 0%, 10% 50%, from(#fff), to(rgb(255,152,0)))
}

/**
 * base.js 全局数据定义
 */
var gameMode = {
    level:2,
    time:120,
    score:5,
    seriesScore:1.5
}
var gameChunkColor = [];
var gameMapArr = [];
var gameScore = 0;
var gameOver = false;
var timeRemain = gameMode.time;
//base
var Base = {}
//timer
var timer = setInterval("interval()", 1000);
function interval()
{
	timeRemain--;
	$$("timeRemain").innerHTML = ("剩余时间:" + timeRemain + "s");
	if(timeRemain <= 0)
	{
		clearInterval(timer);
		timeRemain = gameMode.time;
		gameOver = true;
		alert(‘游戏结束,得分:‘ + gameScore);
	}
}
function hasClass(obj, cls)
 {
	return !!(obj.className.match(new RegExp(‘(\\s|^)‘ + cls + ‘(\\s|$)‘)));
 }

function removeClass(obj, cls)
{
	if (hasClass(obj, cls)) {
		var reg = new RegExp(‘(\\s|^)‘ + cls + ‘(\\s|$)‘);
		obj.className = obj.className.replace(reg, ‘‘);
	}
}

function addClass(obj, cls)
{
	if (!hasClass(obj, cls)) 
	{
		obj.className += (" " + cls);
	}
}

function $query(selector, e)
{
	e = e || document;
	return e.querySelector(selector);
}

function $$(id)
{
	return document.getElementById(id);
}
/**
 * game.js 游戏类
 */
(function() {

	var Game = {}
	
	Game.init = function()
	{
		var myGameMap = new Base.GameMap();
		myGameMap._initData();
		myGameMap._create(Game.clickCallBack);
		this.myGameMap = myGameMap;
	}
	
	Game.searchBlock =function(i, j)
	{
		var left = -1; 
		var right = -1; 
		var top = -1; 
		var bottom = -1;
		var leftColor, rightColor, topColor, bottomColor;
		
		for(var k = j-1; k >= 0; k--)// search left
		{
			var color = gameMapArr[i][k]
			if(color != "-1")
			{
				left = k;
				leftColor = color;
				break;
			}
		}
		
		for(var k = j+1; k < this.myGameMap._c; k++)// search right
		{
			var color = gameMapArr[i][k]
			if(color != "-1")
			{
				right = k;
				rightColor = color;
				break;
			}
		}
		
		for(var k = i-1; k >= 0; k--)// search top
		{
			var color = gameMapArr[k][j]
			if(color != "-1")
			{
				top = k;
				topColor = color;
				break;
			}
		}
		
		for(var k = i+1; k < this.myGameMap._r; k++)// search bottom
		{
			var color = gameMapArr[k][j]
			if(color != "-1")
			{
				bottom = k;
				bottomColor = color;
				break;
			}
		}
		
		var leftBlock = $$("block_" + i + "_" + left);
		var rightBlock = $$("block_" + i + "_" + right);
		var topBlock = $$("block_" + top + "_" + j);
		var bottomBlock = $$("block_" + bottom + "_" + j);

		var colors = new Array();
		colors.push(leftColor);
		colors.push(rightColor);
		colors.push(topColor);
		colors.push(bottomColor);
		
		var blocks = new Array();
		blocks.push(leftBlock);
		blocks.push(rightBlock);
		blocks.push(topBlock);
		blocks.push(bottomBlock);
		//remove
		Base.Utils.removeBlocks(blocks, colors);
	}
	
	Game.clickCallBack = function(target)
	{
		if(hasClass(target, "color_-1") == false || gameOver)
		return;
		var id = target.id;
		var array = id.split("_"); 
		var i = array[1];
		var j = array[2];
		Game.searchBlock(Number(i) , Number(j));
	}
	
    /**
     * destory
     */
    Game.destory = function() 
	{
    }
	
	Base.Game = Game;
	
})();
/**
 * map.js
 */
(function(){
/**
 *定义map
 */
var GameMap = function(){}

	/**
	 * 创建一个map 需要根据游戏的配置
	 * @private
	 */
	GameMap.prototype._create = function(callback)
	{
		if(!this._r || !this._c || !this._d)
		{
			this._initData();
		}
		var gamezone = $$("gamezone");
		for(var i = 0; i < this._r; i++)
		{
			//初始化列
			gameMapArr[i] = [];
			for(var j = 0; j < this._c; j++)
			{
				var _div=document.createElement("div");  // 以 DOM 创建新元素
				var num = Math.floor((Math.random() * 16));
				_div.id = "block_" + i + "_" + j;			
				if(num >= 10)
				{	
					num = -1;
				}
				_div.className = "color_" + num;
				document.getElementById(‘gamezone‘).appendChild(_div);
				gameMapArr[i][j] = "" + num;
				// _div.onclick = callback;
				_div.addEventListener(‘click‘,function(e)
				{
					callback(e.currentTarget);
				});
			}
		}
		
		
	}

	/**
	 * 更新map
	 * @private
	 */
	GameMap.prototype._update = function()
	{

	}

	/**
	 * 删除和销毁已有的map
	 * @private
	 */
	GameMap.prototype._destroy = function()
	{

	}

	GameMap.prototype._initData = http://www.mamicode.com/function()>
/**
 * utils.js 实用类
 */
(function() {
	var Utils = {}
	
	Utils._findDuplicateCount = function(colors, color)
	{
		var count = 0;
		color = color || "-1";
		if(color == "-1")//click region
			return count;
		for(var k = 0; k < colors.length; k++)
		{
			if(color == colors[k])
				count++;
		}
		return count;
	}

	Utils._doAnimation = function(block, blockColor, direction)
	{
		var div=document.createElement("div");
		div.className = "div_-2 color_" + blockColor;
		var oRect = block.getBoundingClientRect();   
		var x=oRect.left   
		var y=oRect.top  
		div.cssText = "display:block;position:absolute;left:" 
		+ x + "px;top:" + y + "px;width:300px;background-color:black";
		
		$query("body").appendChild(div); 

		addClass(div, "animation");
		/*
		if(direction == "left")
		{
			$div.animate(
			{top:"420px",left:"23px"}, "normal", "swing", 
			function(){$div.css("display", "none");$div.remove();}
			);
			
		}
		else
		{
			$div.animate(
			{top:"420px",left:"420px"}, "normal", "swing", 
			function(){$div.css("display", "none");$div.remove();}
			);		
		}*/
	}
	
	Utils.removeBlocks = function(blocks, colors)
	{
		var count = 0;
		var colorArr = new Array();
		var size = colors.length;
		console.log("colors[0]=" + colors[0]);
		console.log("colors[1]=" + colors[1]);
		console.log("colors[2]=" + colors[2]);
		console.log("colors[3]=" + colors[3]);
		for(var i=0; i< size; i++)
		{
			count = this._findDuplicateCount(colors, colors[i]);
			if(count >= 2)
			{
				var block = blocks[i];
				var duplicateColor = colors[i];
				block.style.opacity = 0;
				removeClass(block, "color_" + duplicateColor);
				addClass(block, "color_-1");
				
				var id = block.id;
				var array = id.split("_"); 
				//重置array中的颜色记录
				gameMapArr[array[1]][array[2]] = "-1";
				this._doAnimation(block, duplicateColor, i%2==0 ? "right" : "left");
				gameScore++;
				$$("score").innerHTML = ("得分:" + gameScore);
			}
		}
		return colorArr;
	}
	
	Base.Utils = Utils;
	
})();