Matching Neighbours

I was thinking about this whilst playing Zoo Keeper in the arcade. Here’s what I came up with:

(Mouse-over the tiles to see their matching neighbours)

Stage.scaleMode = "noScale";

var base:Array = [];
var selectors:Array = [];

var output:String = "<i>Click to regenerate</i>";

function buildBase() {
	for (y=0; y<15; y++) {
		base[y] = [];
		for (x=0; x<15; x++) {
			tile = _root.attachMovie("tile", "tile_"+x+"_"+y, _root.getNextHighestDepth());
	
			tile.x = x;
			tile.y = y;
			tile._x = x*tile._width;
			tile._y = y*tile._height;
			tile.gotoAndStop(Math.ceil(Math.random()*tile._totalframes));
			
			tile.onRollOut = function() {
				output = "<i>Click to regenerate</i>";
			}
			
			tile.onRollOver = function() {
				clearSelectors();
				testAdjacents(this);
			}
			
			base[y][x] = tile;
		}
	}
}

function clearBase() {
	for (y in base) for (x in base[y]) base[y][x].removeMovieClip();
}

function clearSelectors() {
	for(i in selectors) selectors*.removeMovieClip();
}

function testAdjacents(start:MovieClip) {
	
	var l:Number = start.x;
	var r:Number = start.x;
	while (base[start.y][l-1]._currentframe == start._currentframe) l--;
	while (base[start.y][r+1]._currentframe == start._currentframe) r++;
	
	var t:Number = start.y;
	var b:Number = start.y;
	while (base[t-1][start.x]._currentframe == start._currentframe) t--;
	while (base[b+1][start.x]._currentframe == start._currentframe) b++;
	
	// EyeCandy
	output = "<i>Click to regenerate</i>
Width: <b>"+Number(r-l+1)+"</b>	From: <b>"+Number(l+1)+"</b>
Height: <b>"+Number(b-t+1)+"</b>	From: <b>"+Number(t+1)+"</b>";
	for (x=l; x<=r; x++) selectors.push(_root.attachMovie("selector", "selector"+x+"_"+start.y, _root.getNextHighestDepth(), {_x:x*20,_y:start.y*20}));
	for (y=t; y<=b; y++) selectors.push(_root.attachMovie("selector", "selector"+start.x+"_"+y, _root.getNextHighestDepth(), {_x:start.x*20,_y:y*20}));
		 
}

_root.onMouseDown = function() {
	clearBase();
	clearSelectors();
	buildBase();
	
	output = "<i>Click to regenerate</i>";
}

buildBase();