I made a sliding tiles puzzle game (based on the example in Gary Rozenweig’s Actionscript for games book.
It has 15 tiles (54 pixel squares) and works realy well. But I have been asked to make a simpler version with only 8 tiles and I am struggling to adapt the code. I can’t get the pieces in the right place and they don’t behave properly any more!
I 'd be really grateful for any advice - I can only do simple AS so far, but am trying to get to grips with it. Many thanks for some help.
This is the code:
function initGame () {
// set the horizontal and vertical distance
// between tiles
tileDist = 54;
// set all tiles in exactly the correct spot
for (x=1;x<=4;x++) {
for (y=0;y<=3;y++) {
tile = x+y*4;
_root["tile"+tile]._x = x*tileDist;
_root["tile"+tile]._y = y*tileDist+tileDist;
}
}
// make 100 random but valid moves
for(tilenum=0;tilenum<100;tilenum++) {
do {
// pick a random tile
tile = "tile"+(random(15)+1);
// see whether there is an empty space near it
emptySpace = findEmpty(tile);
// keep looping until a tile is found that
// has an empty space near it
} while ( emptySpace == "none" );
// move this tile to the empty space
moveTile(tile,findEmpty(tile));
}
}
// given a tile, see if the empty space is near it
function findEmpty (tile) {
// get location of tile
tilex = _root[tile]._x;
tiley = _root[tile]._y;
// see whether there is a tile to the left
if (tilex > tileDist) {
if (!tileThere(tilex-tileDist, tiley)) {
return("left");
}
}
// see whether there is a tile to the right
if (tilex < tileDist*4) {
if (!tileThere(tilex+tileDist, tiley)) {
return("right");
}
}
// see whether there is a tile above
if (tiley > tileDist) {
if (!tileThere(tilex, tiley-tileDist)) {
return("above");
}
}
// see whether there is a tile below
if (tiley < tileDist*4) {
if (!tileThere(tilex, tiley+tileDist)) {
return("below");
}
}
// tiles are in all directions
return("none");
}
// check to see whether there is a tile at a certain location
function tileThere (thisx, thisy) {
// loop through tiles
for (i=1;i<=15;i++) {
// see if x matches
if (_root[“tile”+i]._x == thisx) {
// se if y matches
if (_root[“tile”+i]._y == thisy) {
return true;
}
}
}
// no tile there
return false;
}
// move a tile in a certain direction
function moveTile (tile, direction) {
if (direction == “above”) {
_root[tile]._y -= tileDist;
} else if (direction == “below”) {
_root[tile]._y += tileDist;
} else if (direction == “left”) {
_root[tile]._x -= tileDist;
} else if (direction == “right”) {
_root[tile]._x += tileDist;
}
}
// utility function to see on which tile the
// player clicked
function tileUnderMouse () {
for (i=1; i<=15; i++) {
if (_root[“Tile”+i].hitTest(_xmouse, _ymouse)) {
return (i);
}
}
}
initGame();
stop();