拼圖
by San-Kai Liao
HTML
<table id="pluzze" border="0"></table>
CSS
#pluzze td {
padding: 10px;
}
JavaScript
/**
* 建立拼圖
*/
function buildPluzze(xSize, ySize) {
// 置放拼塊的容器
var pluzze = [];
for (var x = 0; x < ySize; x++) {
pluzze[x] = [];
for (var y = 0; y < xSize; y++) {
console.log('x:', x, 'y:', y);
// 取得當前拼塊的「上格」和「左格」拼塊
var topPiece = (x === 0) ? null : pluzze[x - 1][y];
var leftPiece = (y === 0) ? null : pluzze[x][y - 1];
console.log('TP:', topPiece, 'LP:', leftPiece);
// 用上格和左格拼塊來判斷當前格的「上邊」和「左邊」對應的邊線樣式
// 值表示:-1=凹, 0=平, 1=凸
var topBorder = (topPiece) ? topPiece.bottom * -1 : 0;
var leftBorder = (leftPiece) ? leftPiece.right * -1 : 0;
console.log('T:', topBorder, 'L:', leftBorder);
// 當前拼塊若不在邊界,「右邊」和「下邊」為隨機決定(1或-1)
var rightBorder = (y + 1 === xSize) ? 0 : (Math.floor((Math.random() * 10) % 2)) ? 1 : -1;
var bottomBorder = (x + 1 === ySize) ? 0 : (Math.floor((Math.random() * 10) % 2)) ? 1 : -1;
console.log('R:', rightBorder, 'B:', bottomBorder);
// 設定拼圖四邊線樣式
pluzze[x][y] = {
id: x+'-'+y,
top: topBorder,
right: rightBorder,
bottom: bottomBorder,
left: leftBorder
}
console.log('----');
}
console.log('####');
}
return pluzze;
}
$(document).ready(function () {
var p = buildPluzze(3, 3);
var table = '';
for (var i in p) {
var tr = p[i];
table += '<tr>';
for (var j in tr) {
var td = tr[j];
var borderStyle = {
"-1": "dotted",
"0": "double",
"1": "solid"
}
var style = 'border-width:5px;';
style += 'border-top-style:' + borderStyle[td.top] + ';';
style += 'border-right-style:' + borderStyle[td.right] + ';';
style += 'border-bottom-style:' +...