JavaScript实现消消乐的源代码

JavaScript实现消消乐的源码下载地址:点击下载源代码

index.html

<!doctype html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>LuckyStar</title>
		<link rel="stylesheet" href="./css/index.css?v=1.0.0" rel="external nofollow" >
	</head>
	<body>
		<div class="lucky-star" id="luckyStar">
			<div class="score-target">
				<p class="score-level">关卡 <span id="scoreLevel"></span></p>
				<p>目标:<span id="scoreTarget"></span></p>
			</div>
			<div class="score-current">得分<span id="scoreCurrent"></span></div>
			<div class="score-select" id="scoreSelect"></div>
			<ul class="star-list" id="starList"> </ul>
		</div>
	</body>
	<script src="./js/countUp.js"></script>
	<script src="./js/index.js"></script>
	<script src="./js/resize.js"></script>
	<script>
		new PopStar()
	</script>
</html>

JS文件

main.js

(function() {
	//全局配置
	var config = {
		tileWidth: .75, //小星星的宽高
		tileHeight: .75,
		tileSet: [], //存储小星星的二维数组
		tableRows: 10, //行数
		baseScore: 5, //每一个小星星的基础分数
		stepScore: 10, //每一个小星星的递增分数
		targetScore: 2000, //目标分数,初始为2000
		el: document.querySelector('#starList'),// 星星列表
		scoreTarget: document.querySelector('#scoreTarget'),//目标分数
		scoreCurrent: document.querySelector('#scoreCurrent'),//当前分数
		scoreSelect: document.querySelector('#scoreSelect'),//选中星星分数
		scoreLevel: document.querySelector('#scoreLevel'),//当前所在的关数
	};
	//全局计算属性
	var computed = {
		flag: true, //锁
		choose: [], //已选中的小星星集合
		timer: null,
		totalScore: 0, //总分数
		tempTile: null,
		level: 1, //当前所在的关数(每闯过一关+1,游戏失败回复为1)
		stepTargetScore: 1000, //闯关成功的递增分数(1000/关)
		score: 0 //当前的计算分数
	};

	//Block对象
	function Block(number, row, col) {
		var tile = document.createElement('li');
		tile.width = config.tileWidth;
		tile.height = config.tileHeight;
		tile.number = number;
		tile.row = row;
		tile.col = col;
		return tile;
	} 

	//入口函数
	function PopStar() {
		return new PopStar.prototype.init();
	}

	//PopStar原型
	PopStar.prototype = {
		/**
		 * PopStar的入口函数
		 */
		init: function() {
			this.initTable();
		},
		/**
		 * 初始化操作
		 */
		initTable: function() {
			this.initScore();
			this.initTileSet();
			this.initBlocks();
		},

		/**
		 * 初始化当前分数和目标
		 */
		initScore: function() {
			new CountUp(config.scoreTarget, config.targetScore, config.targetScore).start();
			config.scoreCurrent.innerHTML = computed.totalScore;
			config.scoreLevel.innerHTML = computed.level;
		},
		/**
		 * 点击事件操作
		 */
		mouseClick: function() {
			var tileSet = config.tileSet,
				choose = computed.choose,
				baseScore = config.baseScore,
				stepScore = config.stepScore,
				el = config.el,
				self = this,
				len = choose.length;
			if (!computed.flag || len <= 1) {
				return;
			}
			computed.flag = false;
			computed.tempTile = null;
			var score = 0;
			for (var i = 0; i < len; i++) {
				score += baseScore + i * stepScore;
			}

			new CountUp(config.scoreCurrent, computed.totalScore, computed.totalScore += score).start();
			for (var i = 0; i < len; i++) {
				setTimeout(function(i) {
					tileSet[choose[i].row][choose[i].col] = null;
					el.removeChild(choose[i]);
				}, i * 100, i);
			}
			setTimeout(function() {
				self.move();
				//判断结束
				setTimeout(function() {
					if (self.isFinish()) {
						self.clear();
						if (computed.totalScore >= config.targetScore) {
							new CountUp(config.scoreTarget, config.targetScore, config.targetScore += (computed.level - 1) * computed
									.stepTargetScore)
								.start();

							new CountUp(config.scoreLevel, computed.level, computed.level += 1).start();
							alert("恭喜获胜");
							console.log("恭喜获胜")
						} else {
							config.targetScore = config.scoreTarget = 2000;
							computed.level = computed.totalScore = 0;
							alert("游戏失败");
							console.log("游戏失败")
						}
						computed.flag = true;

					} else {
						choose = [];
						computed.flag = true; //在所有动作都执行完成之后释放锁
						self.mouseOver(computed.tempTile);
					}
				}, 300 + choose.length * 150);
			}, choose.length * 100);
		},
		/**
		 * 闯关成功或失败清除(清除二维数组和el的子节点)操作
		 */
		clear: function() {
			var tileSet = config.tileSet,
				rows = tileSet.length,
				el = config.el;
			var temp = [];
			for (var i = rows - 1; i >= 0; i--) {
				for (var j = tileSet[i].length - 1; j >= 0; j--) {
					if (tileSet[i][j] === null) {
						continue;
					}
					temp.push(tileSet[i][j])
					tileSet[i][j] = null;
				}
			}
			for (var k = 0; k < temp.length; k++) {
				setTimeout(function(k) {
					el.removeChild(temp[k]);
						if(k>=temp.length-1){
								setTimeout(function(k) {
										new PopStar();
								},1000)
						}
				}, k * 100, k);
			}
		},
		/**
		 * 是否游戏结束
		 * @returns {boolean}
		 */
		isFinish: function() {
			var tileSet = config.tileSet,
				rows = tileSet.length;
			for (var i = 0; i < rows; i++) {
				var row = tileSet[i].length;
				for (var j = 0; j < row; j++) {
					var temp = [];
					this.checkLink(tileSet[i][j], temp);
					if (temp.length > 1) {
						return false;
					}
				}
			}
			return true;
		},
		/**
		 * 消除星星后的移动操作
		 */
		move: function() {
			var rows = config.tableRows,
				tileSet = config.tileSet;
			//向下移动
			for (var i = 0; i < rows; i++) {
				var pointer = 0; //pointer指向小方块,当遇到null的时候停止,等待上面的小方块落到这里来
				for (var j = 0; j < rows; j++) {
					if (tileSet[j][i] != null) {
						if (j !== pointer) {
							tileSet[pointer][i] = tileSet[j][i];
							tileSet[j][i].row = pointer;
							tileSet[j][i] = null;
						}
						pointer++;
					}
				}
			}
			//横向移动(最下面一行其中有无空列)
			for (var i = 0; i < tileSet[0].length;) {
				if (tileSet[0][i] == null) {
					for (var j = 0; j < rows; j++) {
						tileSet[j].splice(i, 1);
					}
					continue;
				}
				i++;
			}
			this.refresh()
		},
		/**
		 * 鼠标移入时的闪烁操作
		 * @param obj
		 */
		mouseOver: function(obj) {
			if (!computed.flag) { //处于锁定状态不允许有操作
				computed.tempTile = obj;
				return;
			}
			this.clearFlicker();
			var choose = [];
			this.checkLink(obj, choose);
			computed.choose = choose;
			if (choose.length <= 1) {
				choose = [];
				return;
			}
			this.flicker(choose);
			this.computeScore(choose);
		},
		/**
		 * 计算已选中的星星分数
		 * @param arr
		 */
		computeScore: function(arr) {
			var score = 0,
				len = arr.length,
				baseScore = config.baseScore,
				stepScore = config.stepScore;
			for (var i = 0; i < len; i++) {
				score += baseScore + i * stepScore
			}
			if (score <= 0) {
				return;
			}
			computed.score = score;
			config.scoreSelect.style.opacity = '1';
			config.scoreSelect.innerHTML = arr.length + "连消 " + score + "分";
			setTimeout(function() {
				config.scoreSelect.style.opacity = '0';
			}, 1200)
		},
		/**
		 * 鼠标移出时的消除星星闪烁的操作
		 */
		clearFlicker: function() {
			var tileSet = config.tileSet;
			for (var i = 0; i < tileSet.length; i++) {
				for (var j = 0; j < tileSet[i].length; j++) {
					var div = tileSet[i][j];
					if (div === null) {
						continue;
					}
					div.classList.remove("scale");
				}
			}
		},
		/**
		 * 星星闪烁
		 * @param arr
		 */
		flicker: function(arr) {
			for (var i = 0; i < arr.length; i++) {
				var div = arr[i];
				div.classList.add("scale");
			}
		},
		/**
		 * 检查鼠标移入的这个星星是否有相连着的相同的星星,
		 * @param obj star
		 * @param arr choose
		 */
		checkLink: function(obj, arr) {
			if (obj === null) {
				return;
			}
			arr.push(obj);
			/**
			 * 检查左边方块是否可以加入到选入的可消除星星行列:
			 * 选中的星星不能是最左边的,
			 * 选中的星星左边要有星星,
			 * 选中的星星左边的星星的跟选中的星星一样,
			 * 选中的星星左边的星星没有被选中过
			 */
			var tileSet = config.tileSet,
				rows = config.tableRows;
			if (obj.col > 0 && tileSet[obj.row][obj.col - 1] && tileSet[obj.row][obj.col - 1].number === obj.number && arr.indexOf(
					tileSet[obj.row][obj.col - 1]) === -1) {
				this.checkLink(tileSet[obj.row][obj.col - 1], arr);
			}
			if (obj.col < rows - 1 && tileSet[obj.row][obj.col + 1] && tileSet[obj.row][obj.col + 1].number === obj.number &&
				arr.indexOf(tileSet[obj.row][obj.col + 1]) === -1) {
				this.checkLink(tileSet[obj.row][obj.col + 1], arr);
			}
			if (obj.row < rows - 1 && tileSet[obj.row + 1][obj.col] && tileSet[obj.row + 1][obj.col].number === obj.number &&
				arr.indexOf(tileSet[obj.row + 1][obj.col]) === -1) {
				this.checkLink(tileSet[obj.row + 1][obj.col], arr);
			}
			if (obj.row > 0 && tileSet[obj.row - 1][obj.col] && tileSet[obj.row - 1][obj.col].number === obj.number && arr.indexOf(
					tileSet[obj.row - 1][obj.col]) === -1) {
				this.checkLink(tileSet[obj.row - 1][obj.col], arr);
			}
		},
		/**
		 * 初始化二维数组
		 */
		initTileSet: function() {
			var rows = config.tableRows,
				arr = config.tileSet;
			for (var i = 0; i < rows; i++) {
				arr[i] = [];
				for (var j = 0; j < rows; j++) {
					arr[i][j] = [];
				}
			}
		},
		/**
		 * 初始化el的子节点
		 */
		initBlocks: function() {
			var tileSet = config.tileSet,
				self = this,
				el = config.el,
				cols = tileSet.length;
			for (var i = 0; i < cols; i++) {
				var rows = tileSet[i].length;
				for (var j = 0; j < rows; j++) {
					var tile = this.createBlock(Math.floor(Math.random() * 5), i, j);
					tile.onmouseover = function() {
						self.mouseOver(this)
					};
					tile.onclick = function() {
						self.mouseClick();
					};

					tileSet[i][j] = tile;
					el.appendChild(tile);
				}
			}
			this.refresh()
		},
		/**
		 * 渲染el的子节点
		 */
		refresh: function() {
			var tileSet = config.tileSet;
			for (var i = 0; i < tileSet.length; i++) {
				var row = tileSet[i].length;
				for (var j = 0; j < row; j++) {
					var tile = tileSet[i][j];
					if (tile == null) {
						continue;
					}
					tile.row = i;
					tile.col = j;
					tile.style.left = tileSet[i][j].col * config.tileWidth + "rem";
					tile.style.bottom = tileSet[i][j].row * config.tileHeight + "rem";
					tile.style.backgroundImage = "url('./images/" + tileSet[i][j].number + ".png')";

				}
			}
		},
		/**
		 * 创建星星子节点的函数
		 * @param number
		 * @param row
		 * @param col
		 * @returns {HTMLElement}
		 */
		createBlock: function(number, row, col) {
			return new Block(number, row, col);
		},

	};
	PopStar.prototype.init.prototype = PopStar.prototype;
	window.PopStar = PopStar;
})();

index.js

(function()
{function u(a,b,c)
{
var d=document.createElement("li");
d.width=e.tileWidth;d.height=e.tileHeight;
d.number=a;
d.row=b;d.col=c;return d}
function m()
{return new m.prototype.init
}
var e={tileWidth:.75,tileHeight:.75,tileSet: [],
tableRows:10,baseScore:5,
stepScore:10,
targetScore:2E3,
el:document.querySelector("#starList"),
scoreTarget:document.querySelector("#scoreTarget"),
scoreCurrent:document.querySelector("#scoreCurrent"),
scoreSelect:document.querySelector("#scoreSelect"),
scoreLevel:document.querySelector("#scoreLevel")
},
n=!0,t=[],p=0,r=null,q=1;
m.prototype={
init:function(){this.initTable()
}
,initTable:function(){
this.initScore();
this.initTileSet();
this.initBlocks()
}
,
initScore:function(){
(new CountUp(e.scoreTarget,e.targetScore,e.targetScore)).start();
e.scoreCurrent.innerHTML=p;e.scoreLevel.innerHTML=q
},
mouseClick:function(){
var a=e.tileSet,b=t,c=e.baseScore,d=e.stepScore,f=e.el,g=this,h=b.length;if(n&&!(1>=h)){
n=!1;r=null;
for(var l=0,k=0;
k<h;k++)l+=c+k*d;(new CountUp(e.scoreCurrent,p,p+=l)).start();
for(k=0;k<h;k++)
setTimeout(function(c){a[b[c].row][b[c].col]=
null;
f.removeChild(b[c])},100*k,k);
setTimeout(function(){g.move();
setTimeout(function()
{g.isFinish()?(g.clear(),p>=e.targetScore?((new CountUp(e.scoreTarget,e.targetScore,e.targetScore+=1E3*(q-1))).start(),(new CountUp(e.scoreLevel,q,q+=1)).start(),alert("\u606d\u559c\u83b7\u80dc"),console.log("\u606d\u559c\u83b7\u80dc")):(e.targetScore=e.scoreTarget=2E3,q=p=0,alert("\u6e38\u620f\u5931\u8d25"),console.log("\u6e38\u620f\u5931\u8d25")),n=!0):(b=[],n=!0,g.mouseOver(r))},300+150*b.length)},100*b.length)}},
clear:function()
{for(var a=e.tileSet,b=e.el,c=[],
d=a.length-1;0<=d;d--)
for(var f=a[d].length-1;0<=f;f--)
null!==a[d][f]&&(c.push(a[d][f]),a[d][f]=null);

for(a=0;a<c.length;a++)
setTimeout(function(a)
{b.removeChild(c[a]);
a>=c.length-1&&setTimeout(function(a){new m},1E3)},100*a,a)},isFinish:function()
{for(var a=e.tileSet,b=a.length,c=0;c<b;c++)
for(var d=a[c].length,f=0;f<d;f++)
{var g=[];this.checkLink(a[c][f],g);
if(1<g.length)
return!1}return!0},
move:function()
{for(var a=e.tableRows,b=e.tileSet,c=0;
c<a;c++)for(var d=
0,f=0;f<a;f++)null!=b[f][c]&&(f!==d&&(b[d][c]=b[f][c],b[f][c].row=d,b[f][c]=null),d++);
for(c=0;c<b[0].length;
)if(null==b[0][c])
for(f=0;f<a;f++)b[f].splice(c,1);else c++;this.refresh()},
mouseOver:function(a){if(n)
{this.clearFlicker();
var b=[];
this.checkLink(a,b);
t=b;1>=b.length||(this.flicker(b),this.computeScore(b))}
else r=a
},
computeScore:function(a)
{for(var b=0,c=a.length,d=e.baseScore,f=e.stepScore,g=0;
g<c;g++)b+=d+g*f;
0>=b||(e.scoreSelect.style.opacity="1",e.scoreSelect.innerHTML=a.length+"\u8fde\u6d88 "+
b+"\u5206",setTimeout(function(){
e.scoreSelect.style.opacity="0"},1200))
},clearFlicker:function(){
for(var a=e.tileSet,b=0;b<a.length;b++)
for(var c=0;c<a[b].length;c++){var d=a[b][c];null!==d&&d.classList.remove("scale")}},flicker:function(a){for(var b=0;b<a.length;b++)a[b].classList.add("scale")
},
checkLink:function(a,b){
if(null!==a){
b.push(a);var c=e.tileSet,d=e.tableRows;0<a.col&&c[a.row][a.col-1]&&c[a.row][a.col-1].number===a.number&&-1===b.indexOf(c[a.row][a.col-1])&&this.checkLink(c[a.row][a.col-
1],b);a.col<d-1&&c[a.row][a.col+1]&&c[a.row]
[a.col+1].number===a.number&&-1===b.indexOf(c[a.row][a.col+1])&&this.checkLink(c[a.row][a.col+1],b);a.row<d-1&&c[a.row+1][a.col]&&c[a.row+1][a.col].number===a.number&&-1===b.indexOf(c[a.row+1][a.col])&&this.checkLink(c[a.row+1][a.col],b);0<a.row&&c[a.row-1][a.col]&&c[a.row-1][a.col].number===a.number&&-1===b.indexOf(c[a.row-1][a.col])&&this.checkLink(c[a.row-1][a.col],b)}},
initTileSet:function(){
for(var a=e.tableRows,b=e.tileSet,c=0;c<a;c++){b[c]=[];
for(var d= 0;d<a;d++)b[c][d]=[]}},
initBlocks:function()
{
for(var a=e.tileSet,b=this,c=e.el,d=a.length,f=0;f<d;f++)
for(var g=a[f].length,h=0;h<g;h++){
var l=this.createBlock(Math.floor(5*Math.random()),f,h);
l.onmouseover=function(){b.mouseOver(this)};
l.onclick=function(){b.mouseClick()};
a[f][h]=l;
c.appendChild(l)}
this.refresh()},
refresh:function()
{for(var a=e.tileSet,b=0;b<a.length;b++)
for(var c=a[b].length,d=0;d<c;d++)
{var f=a[b][d];
null!=f&&(f.row=b,f.col=d,f.style.left=a[b][d].col*e.tileWidth+"rem",f.style.bottom=
a[b][d].row*e.tileHeight+"rem",f.style.backgroundImage="url('./images/"+a[b][d].number+".png')")
}
}
,createBlock:function(a,b,c){return new u(a,b,c)
}
}
;m.prototype.init.prototype=m.prototype;window.PopStar=m
})();

resize.js

// JavaScript Document
(function px2rem(doc, win) {
  var docEl = doc.documentElement,
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
    recalc = function () {
      var clientWidth = docEl.clientWidth;
      if (!clientWidth) return;
      docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
      /*
       * 100 -> html,body { font-size:100px; }
       * 750 -> 此处以 iPhone6 两倍设计稿 宽度750px 布局页面
       * 根据具体情况改变这两个数值
       */
    };
  if (!doc.addEventListener) return;
  // 窗口大小发生变化,初始化
  win.addEventListener(resizeEvt, recalc, false);
  doc.addEventListener('DOMContentLoaded', recalc, false);
  //防止在html未加载完毕时执行,保证获取正确的页宽
  setTimeout(function(){
    px2rem(doc, win);
  }, 200);
})(document, window);

countUp.js

(function(root, factory) {
 if (typeof define === 'function' && define.amd) {
  define(factory);
 } else if (typeof exports === 'object') {
  module.exports = factory(require, exports, module);
 } else {
  root.CountUp = factory();
 }
}(this, function(require, exports, module) {

/*

	countUp.js
	by @inorganik

*/

// target = id of html element or var of previously selected html element where counting occurs
// startVal = the value you want to begin at
// endVal = the value you want to arrive at
// decimals = number of decimal places, default 0
// duration = duration of animation in seconds, default 2
// options = optional object of options (see below)

var CountUp = function(target, startVal, endVal, decimals, duration, options) {

	var self = this;
	self.version = function () { return '1.9.3'; };

	// default options
	self.options = {
		useEasing: true, // toggle easing
		useGrouping: true, // 1,000,000 vs 1000000
		separator: ',', // character to use as a separator
		decimal: '.', // character to use as a decimal
		easingFn: easeOutExpo, // optional custom easing function, default is Robert Penner's easeOutExpo
		formattingFn: formatNumber, // optional custom formatting function, default is formatNumber above
		prefix: '', // optional text before the result
		suffix: '', // optional text after the result
		numerals: [] // optionally pass an array of custom numerals for 0-9
	};

	// extend default options with passed options object
	if (options && typeof options === 'object') {
		for (var key in self.options) {
			if (options.hasOwnProperty(key) && options[key] !== null) {
				self.options[key] = options[key];
			}
		}
	}

	if (self.options.separator === '') {
		self.options.useGrouping = false;
	}
	else {
		// ensure the separator is a string (formatNumber assumes this)
		self.options.separator = '' + self.options.separator;
	}

	// make sure requestAnimationFrame and cancelAnimationFrame are defined
	// polyfill for browsers without native support
	// by Opera engineer Erik Möller
	var lastTime = 0;
	var vendors = ['webkit', 'moz', 'ms', 'o'];
	for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
		window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
		window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
	}
	if (!window.requestAnimationFrame) {
		window.requestAnimationFrame = function(callback, element) {
			var currTime = new Date().getTime();
			var timeToCall = Math.max(0, 16 - (currTime - lastTime));
			var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
			lastTime = currTime + timeToCall;
			return id;
		};
	}
	if (!window.cancelAnimationFrame) {
		window.cancelAnimationFrame = function(id) {
			clearTimeout(id);
		};
	}

	function formatNumber(num) {
		var neg = (num < 0),
    	x, x1, x2, x3, i, len;
		num = Math.abs(num).toFixed(self.decimals);
		num += '';
		x = num.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? self.options.decimal + x[1] : '';
		if (self.options.useGrouping) {
			x3 = '';
			for (i = 0, len = x1.length; i < len; ++i) {
				if (i !== 0 && ((i % 3) === 0)) {
					x3 = self.options.separator + x3;
				}
				x3 = x1[len - i - 1] + x3;
			}
			x1 = x3;
		}
		// optional numeral substitution
		if (self.options.numerals.length) {
			x1 = x1.replace(/[0-9]/g, function(w) {
				return self.options.numerals[+w];
			})
			x2 = x2.replace(/[0-9]/g, function(w) {
				return self.options.numerals[+w];
			})
		}
		return (neg ? '-' : '') + self.options.prefix + x1 + x2 + self.options.suffix;
	}
	// Robert Penner's easeOutExpo
	function easeOutExpo(t, b, c, d) {
		return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
	}
	function ensureNumber(n) {
		return (typeof n === 'number' && !isNaN(n));
	}

	self.initialize = function() {
		if (self.initialized) return true;

		self.error = '';
		self.d = (typeof target === 'string') ? document.getElementById(target) : target;
		if (!self.d) {
			self.error = '[CountUp] target is null or undefined'
			return false;
		}
		self.startVal = Number(startVal);
		self.endVal = Number(endVal);
		// error checks
		if (ensureNumber(self.startVal) && ensureNumber(self.endVal)) {
			self.decimals = Math.max(0, decimals || 0);
			self.dec = Math.pow(10, self.decimals);
			self.duration = Number(duration) * 1000 || 2000;
			self.countDown = (self.startVal > self.endVal);
			self.frameVal = self.startVal;
			self.initialized = true;
			return true;
		}
		else {
			self.error = '[CountUp] startVal ('+startVal+') or endVal ('+endVal+') is not a number';
			return false;
		}
	};

	// Print value to target
	self.printValue = function(value) {
		var result = self.options.formattingFn(value);

		if (self.d.tagName === 'INPUT') {
			this.d.value = result;
		}
		else if (self.d.tagName === 'text' || self.d.tagName === 'tspan') {
			this.d.textContent = result;
		}
		else {
			this.d.innerHTML = result;
		}
	};

	self.count = function(timestamp) {

		if (!self.startTime) { self.startTime = timestamp; }

		self.timestamp = timestamp;
		var progress = timestamp - self.startTime;
		self.remaining = self.duration - progress;

		// to ease or not to ease
		if (self.options.useEasing) {
			if (self.countDown) {
				self.frameVal = self.startVal - self.options.easingFn(progress, 0, self.startVal - self.endVal, self.duration);
			} else {
				self.frameVal = self.options.easingFn(progress, self.startVal, self.endVal - self.startVal, self.duration);
			}
		} else {
			if (self.countDown) {
				self.frameVal = self.startVal - ((self.startVal - self.endVal) * (progress / self.duration));
			} else {
				self.frameVal = self.startVal + (self.endVal - self.startVal) * (progress / self.duration);
			}
		}

		// don't go past endVal since progress can exceed duration in the last frame
		if (self.countDown) {
			self.frameVal = (self.frameVal < self.endVal) ? self.endVal : self.frameVal;
		} else {
			self.frameVal = (self.frameVal > self.endVal) ? self.endVal : self.frameVal;
		}

		// decimal
		self.frameVal = Math.round(self.frameVal*self.dec)/self.dec;

		// format and print value
		self.printValue(self.frameVal);

		// whether to continue
		if (progress < self.duration) {
			self.rAF = requestAnimationFrame(self.count);
		} else {
			if (self.callback) self.callback();
		}
	};
	// start your animation
	self.start = function(callback) {
		if (!self.initialize()) return;
		self.callback = callback;
		self.rAF = requestAnimationFrame(self.count);
	};
	// toggles pause/resume animation
	self.pauseResume = function() {
		if (!self.paused) {
			self.paused = true;
			cancelAnimationFrame(self.rAF);
		} else {
			self.paused = false;
			delete self.startTime;
			self.duration = self.remaining;
			self.startVal = self.frameVal;
			requestAnimationFrame(self.count);
		}
	};
	// reset to startVal so animation can be run again
	self.reset = function() {
		self.paused = false;
		delete self.startTime;
		self.initialized = false;
		if (self.initialize()) {
			cancelAnimationFrame(self.rAF);
			self.printValue(self.startVal);
		}
	};
	// pass a new endVal and start animation
	self.update = function (newEndVal) {
		if (!self.initialize()) return;
		newEndVal = Number(newEndVal);
		if (!ensureNumber(newEndVal)) {
			self.error = '[CountUp] update() - new endVal is not a number: '+newEndVal;
			return;
		}
		self.error = '';
		if (newEndVal === self.frameVal) return;
		cancelAnimationFrame(self.rAF);
		self.paused = false;
		delete self.startTime;
		self.startVal = self.frameVal;
		self.endVal = newEndVal;
		self.countDown = (self.startVal > self.endVal);
		self.rAF = requestAnimationFrame(self.count);
	};

	// format startVal on initialization
	if (self.initialize()) self.printValue(self.startVal);
};

return CountUp;

}));

index.css

a,body,button,dd,div,dl,dt,form,h1,h2,h3,h4,h5,h6,input,label,li,ol,p,span,table,td,textarea,th,tr,ul
{	-webkit-box-sizing:border-box;
	-moz-box-sizing:border-box;box-sizing:border-box;
	margin:0;padding:0;
	border:0;-webkit-tap-highlight-color:transparent
}
body,html{
	width:100%;min-height:100%;background-color:#fff;
	-webkit-user-select:none;
	-moz-user-select:none;
	-ms-user-select:none;
	user-select:none
}
body
{color:#333;
font-family:微软雅黑
}
h1,h2,h3,h4,h5,h6
{
font-weight:400;
font-size:100%
}
a{
color:#555
}
a,a:hover{
text-decoration:none
}
img{
border:none
}
li,ol,ul{
list-style:none
}
input,textarea{
outline:0;
-webkit-appearance:none
}
::-webkit-input-placeholder{
color:#b0b0b0
}
:-moz-placeholder,::-moz-placeholder{
color:#b0b0b0
}
:-ms-input-placeholder{
color:#b0b0b0
}
[v-cloak]{
display:none
}
.lucky-star{
position:fixed;
top:0;left:0;width:100%;
height:100%;
background-image:url(../images/cover.jpg);background-size:cover;background-repeat:no-repeat;font-size:0;
-moz-background-size:cover;
-o-background-size:cover
}
.score-target
{
padding:0 .3rem;height:1.5rem;
-webkit-box-pack:justify;
-webkit-justify-content:space-between;
-moz-box-pack:justify;
-ms-flex-pack:justify;
justify-content:space-between
}
.score-current,.score-target{
display:-webkit-box;display:-webkit-flex;display:-moz-box;display:-ms-flexbox;
display:flex;width:100%;
color:#fff;font-size:.24rem;
-webkit-box-align:center;
-webkit-align-items:center;
-moz-box-align:center;
-ms-flex-align:center;
align-items:center
}
.score-current{
position:absolute;top:.3rem;
-webkit-box-orient:vertical;
-webkit-box-direction:normal;
-webkit-flex-direction:column;
-moz-box-orient:vertical;
-moz-box-direction:normal;
-ms-flex-direction:column;
flex-direction:column;
-webkit-box-pack:center;
-webkit-justify-content:center;
-moz-box-pack:center;
-ms-flex-pack:center;
justify-content:center
}
.score-current span{
color:#fffc0f;
font-size:.48rem
}
.score-select{
width:100%;
color:#fff;
text-align:center;
font-size:.28rem;opacity:0;
-webkit-transition:opacity 1s;
-moz-transition:opacity 1s;
-o-transition:opacity 1s;
transition:opacity 1s
}

.star-list{
position:fixed;
bottom:0;left:0;
width:100%;
height:70%}
.star-list li{
position:absolute;
width:.75rem;
height:.75rem;
border:0;
-webkit-border-radius:.16rem;
-moz-border-radius:.16rem;
border-radius:.16rem;
background-size:cover;
-webkit-transition:left .3s,bottom .3s,-webkit-transform .3s;-moz-transition:transform .3s,left .3s,bottom .3s,-moz-transform .3s;-o-transition:left .3s,bottom .3s,-o-transform .3s;transition:left .3s,bottom .3s,-webkit-transform .3s;transition:transform .3s,left .3s,bottom .3s;transition:transform .3s,left .3s,bottom .3s,-webkit-transform .3s,-moz-transform .3s,-o-transform .3s;
-moz-background-size:cover;
-o-background-size:cover
}
.star-list li.scale{
border:2px solid #bfefff;
-webkit-animation:scale .3s linear infinite alternate;
-moz-animation:scale .3s linear infinite alternate;
-o-animation:scale .3s linear infinite alternate;animation:scale .3s linear infinite alternate}
.star-list li img{position:absolute;top:15%;left:15%;width:70%;height:70%
}@-webkit-keyframes scale{
0%{-webkit-transform:scale(1);transform:scale(1)
}
to{
-webkit-transform:scale(.95);
transform:scale(.95)
}
}
@-moz-keyframes scale{
0%{
-moz-transform:scale(1);
transform:scale(1)}
to{
-moz-transform:scale(.95);
transform:scale(.95)
}
}
@-o-keyframes scale{
0%{
-o-transform:scale(1);
transform:scale(1)
}
to{
-o-transform:scale(.95);transform:scale(.95)
}
}
@keyframes scale{
0%{
-webkit-transform:scale(1);
-moz-transform:scale(1);
-o-transform:scale(1);
transform:scale(1)
}
to
{
-webkit-transform:scale(.95);
-moz-transform:scale(.95);
-o-transform:scale(.95);transform:scale(.95)
}
}

.DS_Store

到此这篇关于JavaScript实现消消乐-源代码的文章就介绍到这了,更多相关js实现消消乐内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 通过javascript实现扫雷游戏代码实例

    这篇文章主要介绍了通过javascript实现扫雷游戏代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 html代码: <div id="mine"> <div class="level"> <button type="button">初级</button> <button type="button">中级&l

  • JS实现打砖块游戏

    本文实例为大家分享了JS实现打砖块游戏的具体代码,供大家参考,具体内容如下 面向对象思想 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #show{ width: 200px; height: 600px; position: absolute;

  • js实现坦克大战游戏

    本文实例为大家分享了js实现坦克大战游戏的具体代码,供大家参考,具体内容如下 <!DOCTYPE html> <html> <head> <title>tank</title> <style type="text/css"> body { margin: 0px; padding: 0px; border: 0px; } .map { position: absolute; top: 30px; width: 39

  • JavaScript实现消消乐的源代码

    JavaScript实现消消乐的源码下载地址:点击下载源代码 index.html <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0,

  • Vue实现开心消消乐游戏算法

    之前做过一个算法题,算法要求就是写一个开心消消乐的逻辑算法,当时也是考虑了一段时间才做出来.后来想了想,既然核心算法都有了,能不能实现一个开心消消乐的小游戏呢,于是花了两天时间做了一个小游戏出来. 效果展示# 先在这里放一个最终实现的效果,还是一个比较初级的版本,大家有什么想法欢迎评论哦 游戏规则: 初始时会给玩家十分的初始分,每拖动一次就减一分,每消除一个方块就加一分,直到最后分数为0游戏结束 任意两个方块都可以拖动 界面设计# 页面的布局比较简单,格子的数据是一个二维数组的形式,说到这里大家

  • C++语言实现开心消消乐

    本文实例为大家分享了C++实现开心消消乐的具体代码,供大家参考,具体内容如下 用C++实现的开心消消乐主要分成一个一个模块去实现的,较少代码的耦合性,在这里用了一个xiaoxiaogame类去实现,其中构造函数中对数组和变量的初始化 xiaoxiaogame(int row1, int col1); 用void display();这样一个函数实现显示,用bool isvalid(int x, int y);来判断一个坐标所在的位置能不能消除, 用bool isgameover();判断游戏有没

  • C语言实现消消乐小游戏

    本文实例为大家分享了C语言实现消消乐小游戏的具体代码,供大家参考,具体内容如下 代码: #include<iostream> #include<cstdlib> #include<bitset> #include<conio.h> #include<time.h> #include <windows.h> #include<queue> #include<algorithm> using namespace s

  • C语言实现消消乐游戏

    本文实例为大家分享了C语言实现消消乐游戏的具体代码,供大家参考,具体内容如下 问题描述 给定一个矩阵, 判断移动哪一个格子,可以实现消除.(定义连续三个即可消除) 据说是华为的笔试题. 分析 先写一个函数,判断包含(i, j)的格子是否可能实现消除. 然后就是向右向下交换,然后调用上面写好的函数判断 被交换的两个格子是否实现消除. 重点是: 1.只需要向右向下交换,因为遍历的时候,后面的交换会重复.前一个判断了向右交换是否消除,后一个遍历就不需要再判断向左交换是否重复了. 2.一定要对被交换的两

  • 利用PHP实现开心消消乐的算法示例

    前言 本文主要介绍了关于PHP如何实现我们大家都知道的开心消消乐的算法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 一.需求描述: 1.在一个8*8的矩阵方格中随机出现5种颜色的色块. 2.当有三个或以上色块在横向或纵向上相连,则消除这些色块. 3.色块消除后,上方色块往下平移,并掉下颜色随机的色块填充矩阵空缺. 4.重复2.3步骤. 5.消除3个相同色块加10分,4个加15分,5个加20分,6个加30分,7个加40分,8个加70分,9个加100分,10个加150分,再往后

  • Android仿开心消消乐大树星星无限循环效果

    啥都不说先上效果图,这个是我项目里的效果: 下面的是我抽取出来的 demo 适配啥的我基本上都做好了没做其他的 ok 下面 说一下思路把 首先 说一下原理 我是使用bitmap 创建两张图 一开始的时候 一张在下面记为1号 一张在上面 记为2号 当手指向下滑动时 判断 1号 的起点位置 是否完全超出屏幕 如果超出屏幕的话 那么将2号变为下面 1号变为上面 (移动1号的Y坐标) 大体思路 是这样. 里面还有许多判断 比如 是否能向下滑动 起点位置, 星星的判定 哎呀 好烦 说的东西太多啦 来张我的

  • Android开心消消乐代码实例详解

    突然想要在android上写一个消消乐的代码,在此之前没有系统地学过java的面向对象,也没有任何android相关知识,不过还是会一点C++.8月初开始搭建环境,在这上面花了相当多的时间,然后看了一些视频和电子书,对android有了一个大概的了解,感觉差不多了的时候就开始写了. 疯狂地查阅各种资料,反反复复了好几天后,也算是写出了个成品.原计划有很多地方还是可以继续写下去的,比如UI设计,比如动画特效,时间设计,关卡设计,以及与数据库的连接,如果可以的话还能写个联网功能,当然因为写到后期内心

  • C语言实现宾果消消乐

    本文实例为大家分享了C语言宾果消消乐的具体代码,供大家参考,具体内容如下 ```c #include<graphics.h> #include<stdio.h> #include<windows.h> #include <conio.h> #include<time.h> #include<mmsystem.h> #define MAPSIZE 10 int map[MAPSIZE][MAPSIZE]; int map2[MAPSIZ

  • C/C++百行代码实现热门游戏消消乐功能的示例代码

    游戏设计 首先我们需要使用第三方框架,这里我使用的是sfml,不会使用sfml在我的上几篇文章当中-扫雷(上)有详细的开发环境搭建介绍 首先准备图片资源 一张背景图片,一张宝石图片 窗口初始化加载图片 Texture t1; t1.loadFromFile("images/bg2.png"); 当鼠标第一次单击时,记录下位置,第二次单击又记录一下位置,如果两个小方块相邻就交换位置,如果不相邻如图c的位置则,不发生变化 判断行或列如果三张一样的图片相邻,清除一下图片,进行刷新 实列 #i

随机推荐