flash on 2011-6-20
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.system.LoaderContext;
public class Main extends Sprite
{
private const WIDTH:int = 10;
private const HEIGHT:int = 10;
private const SIZE:int = 8;
private const SCALE:Number = 4.0;
private var map:Array = [];
private var tile:BitmapData;
private var canvas:BitmapData;
public function Main()
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
loader.load(new URLRequest("http://assets.wonderfl.net/images/related_images/5/52/5250/525077ca6886504891442f9af2ea2f0e3589dde6"), new LoaderContext(true));
}
private function initHandler(event:Event):void
{
graphics.beginFill(0xACBCD7);
graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
graphics.endFill();
canvas = new BitmapData(WIDTH * SIZE, HEIGHT * SIZE, true, 0x0);
var bitmap:Bitmap = new Bitmap(canvas);
bitmap.scaleX = bitmap.scaleY = SCALE;
addChild(bitmap);
var loader:Loader = event.currentTarget.loader as Loader;
tile = new BitmapData(loader.width, loader.height, true, 0x0);
tile.draw(loader);
for (var y:int = 0; y < HEIGHT; y++)
{
map[y] = [];
for (var x:int = 0; x < WIDTH; x++)
{
map[y][x] = (Math.random() < 0.7) ? 1 : 0;
}
}
update();
stage.addEventListener(MouseEvent.CLICK, onMouseClick);
}
private function onMouseClick(event:MouseEvent):void
{
var ty:int = mouseY / SIZE / SCALE;
var tx:int = mouseX / SIZE / SCALE;
if (ty < 0 || HEIGHT <= ty ||
tx < 0 || WIDTH <= tx) return;
if (event.shiftKey) map[ty][tx] = 0;
else map[ty][tx] = 1;
update();
}
private function update():void
{
canvas.fillRect(canvas.rect, 0x0);
for (var y:int = 0; y < HEIGHT; y++)
{
for (var x:int = 0; x < WIDTH; x++)
{
if (map[y][x] == 1)
{
var index:int = 0;
if (0 <= y - 1 && map[y - 1][x] == 1) index += 1;
if (x + 1 < WIDTH && map[y][x + 1] == 1) index += 2;
if (y + 1 < HEIGHT && map[y + 1][x] == 1) index += 4;
if (0 <= x - 1 && map[y][x - 1] == 1) index += 8;
canvas.copyPixels(tile, new Rectangle(index * SIZE, 0, SIZE, SIZE), new Point(x * SIZE, y * SIZE));
}
}
}
}
}
}