十六宫格拼图游戏
发布时间:2024-08-27
发布时间:2024-08-27
十六宫格拼图游戏
游戏要求:先打乱方块次序,再移动方块(只能移到空位),使15个方块按顺序排列。 以前的示例,经过随机排列后,会出现无解的情况。代码修改后解决了这个问题。
1、制作一个背景。
1、制作方块影片剪辑,动态文本变量名为PieceNumber。
3、将背景元件和方块元件拖入主场景,将方块影片命名为P。
4、在主场景第一帧写上如下代码:
dfd=new Array()
for(k=0;k<4;k++){
dfd[k]=new Array(0,0,0,0)
}
if (!initialized) {
Initialize();
initialized = true;
}
function PieceX(col)
{
return 72.8 + col * xSpace;
}
function PieceY(row)
{
return 63.5 + row * ySpace;
}
function Initialize()
Congratulations.stop();
numRows = 4;
numCols = 4;
numCells = numRows*numCols;
xBase = p0._x;
yBase = p0._y;
xSpace = p._width * 1.07;
ySpace = p._height * 1.07;
for (var i=0; i<4; i++) {
for(var j=0; j<5; j++) {
if((i*4+j)<15){
var name = "p" + (i*4+j);
p.duplicateMovieClip(name, i*4+j);
var newPiece = eval(name);
newPiece._x = PieceX(i);
newPiece._y = PieceY(j);
newPiece.PieceNumber =i*4+j+1;
}
}}
posArray = [];
for (i=0; i<numCells-1; i++) {
posArray[i] = i;
}
empty = numCells-1;
}
function isWinner()
{
for (var i = 0; i<numCells-1; i++) {
if (posArray[i] != i) {
return false;
}
}
return true;
}
function Click(clicked)
{
clicked--;
if (isWinner()) {
shuffle();
Congratulations.gotoAndStop(1);
// Congratulations过关后出现的影片剪辑
} else {
pos = posArray[clicked];
emptyRow = Math.floor(empty/numCols);
emptyCol = empty-emptyRow*numCols;
clickedRow = Math.floor(pos/numCols);
clickedCol = pos-clickedRow*numCols;
rowDiff = Math.abs(clickedRow-emptyRow);
colDiff = Math.abs(clickedCol-emptyCol);
adjacent = (rowDiff+colDiff) == 1;
if (adjacent) {
var piece = eval("/p" + clicked);
piece._x = PieceX(emptyCol);
piece._y = PieceY(emptyRow);
posArray[clicked] = empty;
empty = pos;
if (isWinner()) {
Congratulations.play();
}
}
}
}
function Shuffle()
{
var cf = function (x, y) {
if (x[1] < y[1]) {
return -1;
} else if (x[1] > y[1]) {
return 1;
} else {
return 0;
}
}
var i;
var cell = [];
for (i=0; i<numCells; i++) {
cell.push([i, Math.random()]);
}
cell.sort(cf);
var r = 0, c = 0;
nie=0
daf=[]
for (i=0; i<numCells; i++) {
var piece = cell[i][0];
daf.push([piece])
for(j=i+1;j<numCells;
{if(cell[i][0]<15){ if(cell[i][0]>cell[j][0]){
nie=nie+1
//
}}}
if (piece == numCells-1) {
empty = i;
} else {
posArray[piece] = i;
var p = eval("/p" + piece);
p._x = PieceX(c);
p._y = PieceY(r);
}
if (++c >= numCols) {
c = 0;
r++;
}
}
for(k=0;k<4;k++){for(kk=0;kk<4;kk++){dfd[k][kk]=daf[k*4+kk] }}
} j++)