「消滅星星」這類消除遊戲規則簡單、上手快,很適合當成 JavaScript 與 DOM 動畫的練習題。動畫部分靠 jQuery 的 animate() 完成,核心邏輯則是格子相連的遞迴搜尋。

雙擊相鄰且顏色相同的星星群組,該群組就會一起消失;上方星星向下補位,整列清空後左側的列會往左收攏。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" content="target-densitydpi=320,width=640,user-scalable=no" />
<noscript><meta http-equiv="refresh" content="0"></noscript>
<title></title>
<meta name="description" id="seo_description" content="消滅星星">
<meta name="viewport" content="initial-scale=1, width=device-width, maximum-scale=1, user-scalable=no">
<meta name="viewport" content="initial-scale=1.0,user-scalable=no,maximum-scale=1" media="(device-height: 568px)">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name='apple-touch-fullscreen' content='yes'>
<meta name="full-screen" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="format-detection" content="address=no">
<link rel="icon" href="" type="image/x-icon">
<script id="jquery_183" type="text/javascript" class="library" src="https://runjs.cn/js/sandbox/jquery/jquery-1.8.3.min.js"></script>
<style>
* { margin:0; padding:0; }
body { background:#000; width:100%; height:100%; }
#box { position:absolute; margin-top:50px; }
#star_box { position:relative; }
#star_box .star { width:40px; height:40px; position:absolute; cursor:pointer; }
#star_box .star img { border-radius:5px; }
#star_box .link img { border:2px solid #fff; border-radius:5px; }
</style>
<script>
$(function(){ app.run(); });
var app = {};
app.linkStars = []; // 本次連通的所有星星
app.searchStars = []; // 搜尋佇列
app.stars = []; // 當前棋盤資料
app.newStars = []; // 移動後的新棋盤
app.colsNoneNum = 0;
app.star = {
width: 30, // 星星寬度
height: 30, // 星星高度
margin: 5, // 每顆星星的間距
rowNum: 10, // 行數
colsNum: 10, // 列數
colorNum: 5 // 顏色種類(最多 5 種,因為只有 5 張圖)
};
app.timer = null;
app.run = function() {
this.box = $('#box');
this.starBox = this.box.find('#star_box');
this.initCanvas();
this.initStars();
this.draw();
this.initBox();
};
app.initCanvas = function() {
var height = $(window).height();
$('body').css('height', height + 'px');
};
// 依視窗寬度置中棋盤
app.initBox = function() {
var boxWidth = this.star.width * this.star.colsNum + this.star.margin * this.star.colsNum;
var boxHeight = this.star.height * this.star.rowNum + this.star.margin * this.star.rowNum;
var left = ($(window).width() - boxWidth) / 2;
this.box.css('left', left + 'px');
this.box.css('width', boxWidth + 'px');
this.box.css('height', boxHeight + 'px');
};
// 隨機初始化星星矩陣
app.initStars = function() {
for (var i = 0; i < this.star.rowNum; i++) {
this.stars[i] = [];
for (var k = 0; k < this.star.colsNum; k++) {
var color_index = Math.floor(Math.random() * this.star.colorNum);
this.stars[i][k] = color_index;
}
}
this.newStars = left2Array(this.stars);
this.noLeftChangeStars = left2Array(this.stars);
};
app.initColsLink = function() {
this.colsLink = [];
for (var i = 0; i < this.star.colsNum; i++) {
this.colsLink[i] = {
x: [], num: 0, max: Number(-1), count: this.initRowArray(1)
};
}
};
// 單擊:先找出相連星星並高亮
app.click = function(x, y) {
x = parseInt(x); y = parseInt(y);
var searchStars = [];
searchStars[0] = { x: x, y: y };
this.count = 0;
this.linkStars = [];
this.searchStars = [];
this.bigSearch(searchStars);
this.clickAnimate();
};
app.mouseup = function() {
clearTimeout(app.timer);
app.timer = setTimeout(function() {
app.starBox.find('.star').removeClass('link');
}, 500);
};
// 雙擊:消除並重排
app.touch = function(x, y) {
x = parseInt(x); y = parseInt(y);
var searchStars = [];
searchStars[0] = { x: x, y: y };
this.count = 0;
this.linkStars = [];
this.searchStars = [];
this.bigSearch(searchStars);
this.initColsLink();
this.colsNoneLenth = this.initColsArray(0);
this.leftData = {
min: Number(this.star.colsNum), y: [], num: 0, count: this.initColsArray(1)
};
this.makeStars();
this.animate();
};
// 消除+下落+左移的動畫總入口
app.animate = function() {
if (this.linkStars.length < 2) return;
for (var i in this.linkStars) {
this.delAnimate(parseInt(this.linkStars[i].x), parseInt(this.linkStars[i].y));
}
for (var i in this.colsLink) {
var x = parseInt(this.colsLink[i].max);
var y = parseInt(i);
if (this.colsLink[i].x.length > 1) {
var mOffset = 0;
for (var j = this.colsLink[i].x.length - 1; j >= 0; j--) {
mOffset += this.colsLink[i].count[j];
var r = this.colsLink[i].x[j - 1];
if (j - 1 < 0) r = -1;
for (var t_x = this.colsLink[i].x[j] - 1; t_x > r; t_x--) {
this.downAnimate(t_x, y, mOffset);
}
}
} else {
for (var t_x = x - 1; t_x >= 0; t_x--) {
this.downAnimate(t_x, y, this.colsLink[y].num);
}
}
}
if (this.leftData.min > -1) {
if (this.leftData.y.length > 1) {
var mOffset = 0;
for (var j = 0; j <= this.leftData.y.length - 1; j++) {
mOffset += this.leftData.count[j];
var r = this.leftData.y[j + 1];
if (j + 1 > this.leftData.y.length - 1) r = this.star.colsNum;
for (var n_x = 0; n_x <= this.star.rowNum - 1; n_x++) {
for (var n_y = this.leftData.y[j] + 1; n_y < r; n_y++) {
this.leftAnimate(n_x, n_y, mOffset);
}
}
}
} else {
var y = parseInt(this.leftData.min);
for (var n_x = 0; n_x <= this.star.rowNum - 1; n_x++) {
for (var n_y = y + 1; n_y < this.star.colsNum; n_y++) {
this.leftAnimate(n_x, n_y, this.leftData.num);
}
}
}
}
};
/* 星星消失動畫 */
app.delAnimate = function(x, y) {
var index = x * this.star.colsNum + y; // 由座標算出 DOM 的 id
var starDiv = this.starBox.find('.id_' + index);
var left = parseInt(starDiv.css('left')) + this.star.width / 2;
var top = parseInt(starDiv.css('top')) + this.star.height / 2;
starDiv.find('img').animate({ width: '0', height: '0' }, 500);
starDiv.animate({ left: left + 'px', top: top + 'px', opacity: 0 }, 500, function () {
$(this).hide();
});
starDiv.removeClass('id_' + index);
};
/* 星星下落動畫 */
app.downAnimate = function(x, y, move_num) {
if (this.checkRepeat(x, y)) { return; }
var index = x * this.star.colsNum + y;
var starDiv = this.starBox.find('.id_' + index);
var dTop = parseInt(starDiv.css('top'));
var top = dTop + (this.star.height + this.star.margin) * move_num;
starDiv.animate({ top: top + 'px' }, 300);
var n_x_ = x + move_num;
starDiv.attr('ondblclick', 'app.touch(' + n_x_ + ',' + y + ')');
starDiv.attr('onmousedown', 'app.click(' + n_x_ + ',' + y + ')');
starDiv.removeClass('id_' + index);
starDiv.addClass('id_' + (parseInt(n_x_ * this.star.colsNum) + parseInt(y)));
};
/* 星星左移動畫 */
app.leftAnimate = function(x, y, move_num) {
var index = x * this.star.colsNum + y;
var starDiv = this.starBox.find('.id_' + index);
var dLeft = parseInt(starDiv.css('left'));
var left = dLeft - (this.star.width + this.star.margin) * move_num;
starDiv.animate({ left: left + 'px' }, 300);
var n_y_ = y - move_num;
starDiv.attr('ondblclick', 'app.touch(' + x + ',' + n_y_ + ')');
starDiv.attr('onmousedown', 'app.click(' + x + ',' + n_y_ + ')');
starDiv.removeClass('id_' + index);
starDiv.addClass('id_' + (parseInt(x * this.star.colsNum) + parseInt(n_y_)));
};
// 單擊時高亮相連星星
app.clickAnimate = function() {
if (this.linkStars.length < 2) return;
this.starBox.find('.star').removeClass('link');
for (var i in this.linkStars) {
var index = parseInt(this.linkStars[i].x) * this.star.colsNum + parseInt(this.linkStars[i].y);
this.starBox.find('.id_' + index).addClass('link');
}
};
/* 遞迴搜尋相連的星星 */
app.bigSearch = function(searchStars) {
if (searchStars.length == 0) return;
this.newSearchStars = [];
this.s_count = 0;
for (var i in searchStars) {
var star = searchStars[i];
var x = parseInt(star.x);
var y = parseInt(star.y);
if (!this.checkRepeat(x, y)) {
this.linkStars[this.count] = { x: x, y: y };
}
this.count++;
this.search(x, y, 'top');
this.search(x, y, 'right');
this.search(x, y, 'down');
this.search(x, y, 'left');
}
this.bigSearch(this.newSearchStars);
};
/* 上下左右四向查找同色相鄰格 */
app.search = function(x, y, position) {
if (position == 'top') {
var top = x - 1;
if (top < 0) return;
if (this.stars[x][y] == this.stars[top][y] && !this.checkRepeat(top, y)) {
this.newSearchStars[this.s_count] = { x: top, y: y };
}
} else if (position == 'right') {
var right = y + 1;
if (right > this.star.colsNum - 1) return;
if (this.stars[x][y] == this.stars[x][right] && !this.checkRepeat(x, right)) {
this.newSearchStars[this.s_count] = { x: x, y: right };
}
} else if (position == 'down') {
var down = x + 1;
if (down > this.star.rowNum - 1) return;
if (this.stars[x][y] == this.stars[down][y] && !this.checkRepeat(down, y)) {
this.newSearchStars[this.s_count] = { x: down, y: y };
}
} else if (position == 'left') {
var left = y - 1;
if (left < 0) return;
if (this.stars[x][y] == this.stars[x][left] && !this.checkRepeat(x, left)) {
this.newSearchStars[this.s_count] = { x: x, y: left };
}
}
this.s_count++;
};
// 檢查座標是否已在 linkStars 中
app.checkRepeat = function(x, y) {
if (this.linkStars.length == 0) return false;
for (var i in this.linkStars) {
if (parseInt(this.linkStars[i].x) == parseInt(x)
&& parseInt(this.linkStars[i].y) == parseInt(y)) return true;
}
return false;
};
// 重建棋盤:下落 + 左移
app.makeStars = function() {
if (this.stars.length == 0 || this.newStars.length == 0
|| this.linkStars.length < 2) return false;
// step-1 逐列處理下落,把 -1 補到最上方
var clx_count = this.initColsArray(0);
for (var x in this.stars) {
x = parseInt(x);
for (var y in this.stars[x]) {
y = parseInt(y);
if (this.stars[x][y] != -1 && this.checkRepeat(x, y)) {
for (var n_x = x - 1; n_x >= 0; n_x--) {
this.newStars[n_x + 1][y] = this.newStars[n_x][y];
}
this.newStars[0][y] = -1;
this.colsLink[y].num += 1;
if (this.colsLink[y].max < x) {
this.colsLink[y].max = x;
if ((x + 1 <= this.stars.length - 1 && !this.checkRepeat(x + 1, y))
|| (x == this.stars.length - 1 && this.checkRepeat(x, y))) {
this.colsLink[y].x[clx_count[y]] = x;
clx_count[y]++;
} else if (x + 1 <= this.stars.length - 1 && this.checkRepeat(x + 1, y)) {
this.colsLink[y].count[clx_count[y]] += 1;
}
}
this.colsNoneLenth[y] += 1;
}
}
}
// step-2 統計需要左移的整空列
this.noLeftChangeStars = left2Array(this.newStars);
var ld_count = 0;
for (var y = 0; y <= this.star.colsNum - 1; y++) {
y = parseInt(y);
if (this.checkColsNone(y)) {
if (this.leftData.min > y) { this.leftData.min = y; }
if ((y + 1 <= this.star.colsNum - 1 && !this.checkColsNone(y + 1))
|| (y == this.star.colsNum - 1)) {
this.leftData.y[ld_count] = y;
ld_count++;
} else if (y + 1 <= this.star.colsNum - 1 && this.checkColsNone(y + 1)) {
this.leftData.count[ld_count] += 1;
}
this.leftData.num += 1;
}
}
// step-3 執行左移並產生新棋盤
if (this.leftData.min > -1) {
var check = this.leftData.min;
for (var y = 0; y < this.star.colsNum; y++) {
if (this.checkNewColsNone(check)) {
for (var n_x = 0; n_x <= this.star.rowNum - 1; n_x++) {
for (var n_y = check + 1; n_y < this.star.colsNum; n_y++) {
this.newStars[n_x][n_y - 1] = this.newStars[n_x][n_y];
}
this.newStars[n_x][this.star.colsNum - 1] = -1;
}
} else {
check += 1;
}
}
}
this.stars = left2Array(this.newStars);
};
// 判斷「尚未左移」的棋盤中該列是否已清空
app.checkColsNone = function(y) {
var count = 0;
for (var x = 0; x < this.star.rowNum; x++) {
if (this.noLeftChangeStars[x][y] == Number(-1)) count++;
}
return count == this.star.rowNum;
};
// 判斷每次下移/左移後的新棋盤中該列是否已清空
app.checkNewColsNone = function(y) {
var count = 0;
for (var x = 0; x < this.star.rowNum; x++) {
if (this.newStars[x][y] == Number(-1)) count++;
}
return count == this.star.rowNum;
};
app.draw = function() {
var starsDiv = '';
for (var x in this.stars) {
x = parseInt(x);
for (var y in this.stars[x]) {
y = parseInt(y);
var star = this.stars[x][y];
if (star == -1) { continue; }
var left = y * this.star.width + y * 5;
var top = x * this.star.height + x * 5;
var index = x * this.star.colsNum + y;
starsDiv += '<div class="star id_' + index + '" style="left:' + left + 'px; top:' + top
+ 'px; width:' + this.star.width + 'px;height:' + this.star.height + 'px;"'
+ ' ondblclick="app.touch(' + x + ',' + y + ');"'
+ ' onmousedown="app.click(' + x + ',' + y + ');"'
+ ' onmouseup="app.mouseup();">'
+ '<img src="https://sandbox.runjs.cn/uploads/rs/437/doeiphrq/star_' + star + '.png"'
+ ' width="' + this.star.width + '" height="' + this.star.height + '"/></div>';
}
}
$('#star_box').html(starsDiv);
};
app.initColsArray = function(val) {
var array = [];
if (val == 'undefined') val = 0;
for (var i = 0; i < this.star.colsNum; i++) { array[i] = val; }
return array;
};
app.initRowArray = function(val) {
var array = [];
if (val == 'undefined') val = 0;
for (var i = 0; i < this.star.rowNum; i++) { array[i] = val; }
return array;
};
// 除錯用:把棋盤矩陣印到頁面上
app.write = function() {
var html = '';
for (var i in this.stars) {
for (var j in this.stars[i]) {
var star = this.stars[i][j];
var color = (star == -1) ? 'blue' : 'red';
html += '<font color="' + color + '">' + star + '</font>'
+ '<font color="#999">(' + i + ',' + j + ')</font> ';
}
html += '<br/><br/>';
}
$('#show').append(html);
};
// 深拷貝二維陣列,避免修改時互相影響
function left2Array(array) {
if (array.length < 0) return array;
var newArray = [];
for (var i in array) {
newArray[i] = [];
for (var j in array[i]) { newArray[i][j] = array[i][j]; }
}
return newArray;
}
</script>
</head>
<body>
<div id="box">
<div id="star_box"></div>
</div>
<div id="show" style="padding-top:600px;"></div>
</body>
</html>
整個專案的骨架其實只有三塊:資料層用二維陣列記錄每格的顏色編號,-1 代表空格;邏輯層靠 bigSearch() 以四向遞迴找出相連同色群組,再依序執行下落與左移;表現層則用 jQuery animate() 把資料變化演繹成動畫,並在動畫結束後更新 DOM 的 id 與事件綁定。
原作者的程式裡還保留著積分系統的 TODO,如果想延伸練習,計分、剩餘步數、結束判定與重新開始都是不錯的下一題。