ライフゲーム

by wantora
♥0 | Line 65 | Modified 2009-07-16 19:05:16 | MIT License
play

ActionScript3 source code

/**
 * Copyright wantora ( http://wonderfl.net/user/wantora )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/pP5x
 */

package {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	[SWF(frameRate=30, backgroundColor = 0x000000)]
	
	public class Main extends Sprite {
		private const STAGE_WIDTH:int = 400;
		private const STAGE_HEIGHT:int = 400;
		
		private var bitmapData:BitmapData;
		private var bitmap:Bitmap;
		private var bm_tmp:BitmapData;
		private var bm_rect:Rectangle;
		private var bm_point:Point;
		
		public function Main():void {
			bitmapData = new BitmapData(STAGE_WIDTH, STAGE_HEIGHT, false, 0x000000);
			bm_tmp = bitmapData.clone();
			bm_rect = bitmapData.rect;
			bm_point = new Point(0, 0);
			
			bitmap = new Bitmap(bitmapData);
			bitmap.x = 32;
			bitmap.y = 32;
			//bitmap.width = STAGE_WIDTH * 2;
			//bitmap.height = STAGE_HEIGHT * 2;
			
			for (var i:int = 0; i < (STAGE_WIDTH * STAGE_HEIGHT / 2); i++) {
				bitmapData.setPixel(Math.random() * STAGE_WIDTH, Math.random() * STAGE_HEIGHT, 0x00ff00);
			}
			
			addChild(bitmap);
			addEventListener(Event.ENTER_FRAME, mainloop);
		}
		
		private function mainloop(e:Event):void {
			bm_tmp.copyPixels(bitmapData, bm_rect, bm_point);
			
			var a1:Boolean, a2:Boolean, a3:Boolean,
				b1:Boolean, b2:Boolean, b3:Boolean,
				c1:Boolean, c2:Boolean, c3:Boolean,
				xa:Boolean, xb:Boolean, xc:Boolean;
			xa = xb = false; xc = bm_tmp.getPixel(0, 0) != 0x000000;
			
			for (var x:int = 0; x < STAGE_WIDTH; x++) {
				xa = xb; xb = xc; xc = bm_tmp.getPixel(x + 1, 0) != 0x000000;
				
				a1 = a2 = b1 = b2 = c1 = c2 = false;
				a3 = xa; b3 = xb; c3 = xc;
				
				for (var y:int = 0; y < STAGE_HEIGHT; y++) {
					a1 = a2; a2 = a3; a3 = bm_tmp.getPixel(x - 1, y + 1) != 0x000000;
					b1 = b2; b2 = b3; b3 = bm_tmp.getPixel(x, y + 1) != 0x000000;
					c1 = c2; c2 = c3; c3 = bm_tmp.getPixel(x + 1, y + 1) != 0x000000;
					
					var count:int = 0;
					if (a1) count ++;
					if (a2) count ++;
					if (a3) count ++;
					if (b1) count ++;
					if (b3) count ++;
					if (c1) count ++;
					if (c2) count ++;
					if (c3) count ++;
					
					var live:Boolean = b2;
					if (!live && count == 3) {
						bitmapData.setPixel(x, y, 0x00ff00);
					} else if (live && !(count == 2 || count == 3)) {
						bitmapData.setPixel(x, y, 0x000000);
					}
				}
			}
		}
	}
}

Forked