Langton's Ants old school fun with BitmapData milchreis forked:1favorite:2lines:92license : MIT License modified : 2012-08-17 06:10:08 Embed Tweet package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.events.Event; [SWF( height = "600", width = "600", framerate = "50", backgroundColor = "0x000000" )] /** * ... * @author milchreis */ public class Main extends Sprite { private static const ANT_COUNT:uint = 7; //number of ants in one row private static const SIZE:uint = 200; //initial size of bitmap, will be scaled up (2x) private var _bm:Bitmap; private var _bmd:BitmapData; private var _hive:Array; public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); _hive = []; _bmd = new BitmapData(SIZE, SIZE, false, 0x000000); _bm = new Bitmap(_bmd); _bm.scaleX = _bm.scaleY = Math.min(stage.stageHeight, stage.stageWidth)/SIZE; addChild(_bm); for (var j:uint = 0; j < ANT_COUNT; j++) for (var i:uint = 0; i < ANT_COUNT; i++) { _hive.push(new Ant(_bmd, SIZE /2 /ANT_COUNT + SIZE /ANT_COUNT * j, SIZE /2 /ANT_COUNT + SIZE /ANT_COUNT * i, 0xffffff * Math.random())); } addEventListener(Event.ENTER_FRAME, loop); } private function loop(e:Event):void { _bmd.lock() for each (var ant:Ant in _hive) ant.update(); _bmd.unlock(); } } } import flash.display.BitmapData; internal class Ant { private var _hole:BitmapData; private var _direction:uint, _x:uint, _y:uint, _color:uint; public function Ant(bitmapdata:BitmapData, x:uint = 0, y:uint = 0, color:uint = 0xffff00) { _x = x; _y = y; _color = color; _hole = bitmapdata; _direction = Math.ceil(Math.random()*4); } public function update():void { // this is how the langton algorithm works, setting/unsetting pixels and changing direction. if (_hole.getPixel(_x, _y) == 0) { _hole.setPixel(_x, _y, _color); _direction += 1; } else { _hole.setPixel(_x, _y, 0); _direction -= 1; } //making sure that we only have 4 directions and cycle through them if (_direction > 4) { _direction = 1; } else if (_direction < 1) { _direction = 4; } //this moves the ant and projects the bitmapData on a torus, this way, no ant can be lost. =) switch(_direction) { case 1: _y = (_y == 0) ? _hole.height-1 : (_y - 1); break; case 2: _x = (_x == _hole.width-1) ? 0 : (_x + 1); break; case 3: _y = (_y == _hole.height-1) ? 0 : (_y + 1); break; case 4: _x = (_x == 0) ? _hole.width-1 : (_x - 1); break; } } } Code Fullscreen Preview Fullscreen _ueueueueue hacker_w7d9y.. : как идея Ant Bitmap BitmapData Langton Pixel height setPixel Event.ADDED_TO_STAGE width Math.ceil unlock lock BitmapData getPixel Event Math.min Event.ENTER_FRAME push Math.random Array uint sort new page view favorite forked pv141 forked from: Langton's Ants karabengles1 forked:0 favorite:0lines:88 (diff:2)