/**
* Copyright mutantleg ( http://wonderfl.net/user/mutantleg )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/Mjjc
*/
package {
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.geom.Matrix;
import flash.display.BitmapData;
import flash.events.Event;
import flash.display.Sprite;
public class FlashTest extends Sprite {
public function FlashTest() {
deb = new TextField();
deb.mouseEnabled = false;
deb.width=320;
deb.height=240;
deb.y=256;
addChild(deb);
myMap = new BitmapData(mw,mh,false, 0);
myMap.fillRect(myMap.rect, 0x808080);
myMap.fillRect(new Rectangle(12,12,8,8), 0);
var i:int;
var r:Rectangle;
r = new Rectangle();
for (i=0;i<32;i+=1)
{
r.x = Math.random()*mw;
r.y = Math.random()*mh;
r.width = Math.random()*8+2;
r.height = Math.random()*8+2;
myMap.fillRect(r, 0);
}//nexti
stage.addEventListener(Event.ENTER_FRAME, onEnter);
}//ctor
public var deb:TextField;
public var mw:int = 32;
public var mh:int = 32;
public var mapMat:Matrix = new Matrix(8,0,0,8);
public var myMap:BitmapData;
public function isWall(ax:int, ay:int):Boolean
{ if (ax<0||ax>=mw||ay<0||ay>=mh) { return true;}
return myMap.getPixel(ax,ay)==0x808080;
}//iswall
public function isFree(ax:int, ay:int):Boolean
{
if (isWall(ax,ay)) { return false; }
return myMap.getPixel(ax,ay) == 0;
}//isfree
public var cx:int = 16;
public var cy:int = 16;
public var vx:int = 0;
public var vy:int = 0;
public var wt:int = 0;
public function onEnter(e:Event):void
{
myMap.setPixel(cx,cy, 0xFF);
if (isFree(cx,cy-1)) {vy=-1; vx=0;}
else if (isFree(cx,cy+1)) {vy=1; vx=0; }
else if (isFree(cx-1,cy)) {vx=-1; vy=0;}
else if (isFree(cx+1,cy)) {vx=1; vy=0;}
deb.text = "vx "+vx+"\nvy "+vy;
var i:int; var k:int;
if (myMap.getPixel(cx,cy)==0xFF) { wt +=1; }
if (wt>=8) {
vx=0;vy=0;
kx=0;ky=0;
for (k=0;k<4;k+=1)
{
if (k ==0) {kx=1;ky=0;}
else if (k==1){kx=-1; ky=0;}
else if (k==2) {kx=0;ky=-1;}
else if (k==3) {kx=0;ky=1;}
for (i=0;i<8;i+=1) { if (isWall(cx+kx*i,cy+ky*i)) { break;}
else if (myMap.getPixel(cx+kx*i,cy+ky*i)==0) {vx=kx; vy=ky; break;} }
if (vx!=0 || vy !=0) { break;}
} //nextk
if (vx==0&&vy==0) {
vx=1;
wt = 0; k = Math.random()*8;
for (i=0;i<k;i+=1) { t = vx; vx=-vy; vy=t; }
}//endif
}//endif
var t:int;
var kx:int; var ky:int;
kx = cx+vx; ky= cy+vy;
if (isWall(kx,ky)==false) { cx=kx;cy=ky; }
else { t = vx; vx=-vy; vy=t; }
graphics.clear();
graphics.lineStyle(2, 0);
graphics.beginBitmapFill(myMap, mapMat);
graphics.drawRect(0,0, mw*8, mh*8);
graphics.endFill();
graphics.beginFill(0xFFffFF,1);
graphics.drawCircle(cx*8+4,cy*8+4, 4);
graphics.endFill();
}//onenter
}//classend
}