BitmapFilterでライフゲーム
/**
* Copyright seikai ( http://wonderfl.net/user/seikai )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/gc2Y
*/
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.filters.BlurFilter;
import flash.filters.ColorMatrixFilter;
import flash.filters.ConvolutionFilter;
import flash.geom.Point;
import flash.utils.Timer;
import net.hires.debug.Stats;
[SWF(width = 465, height = 465, frameRate = 30, backgroundColor=0)]
public class LifeGame extends Sprite
{
//描画用
private var _canvas:Bitmap;
//LifeMap
private var _life:BitmapData;
//計算用BitmapData
private var _bmd1:BitmapData;
private var _bmd2:BitmapData;
//計算パターン
private var _conv1:ConvolutionFilter;
private var _conv2:ConvolutionFilter;
private const BLOCK_SIZE:int = 2;
private const ZERO_P:Point = new Point(0, 0);
private const RATE:int = 30;
public function LifeGame()
{
if(stage){
_init();
}else {
addEventListener(Event.ADDED_TO_STAGE, _init);
}
}
public function _init(e:Event=null):void
{
//表示サイズ
var vw:int = stage.stageWidth - stage.stageWidth % BLOCK_SIZE;
var vh:int = stage.stageHeight - stage.stageHeight % BLOCK_SIZE;
//処理サイズ
var w:int = vw/BLOCK_SIZE, h:int = vh/BLOCK_SIZE;
//初期ライフの決定
var first:BitmapData = new BitmapData(w, h);
first.noise(int(Math.random() * 100), 0, 255, 7);
_life = new BitmapData(w, h, false, 0x000000);
_life.threshold(first, first.rect, ZERO_P, "<", 0x00666666, 0xFF010101, 0x000000FF, false);
first.dispose();
//表示周りの調整等
_canvas = new Bitmap(_life);
_canvas.width = vw;
_canvas.height = vh;
addChild(_canvas);
_canvas.filters = [new ColorMatrixFilter([
0, 0, 0, 0, 0,
0, 255, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 1, 0
]),
new BlurFilter(4, 4, 1)];
//計算データ初期化
_bmd1 = new BitmapData(w, h, false, 0x000000);
_bmd2 = new BitmapData(w, h, false, 0x000000);
//計算パターン1
_conv1 = new ConvolutionFilter(3, 3);
_conv1.matrix = [
1, 1, 1,
1, 1, 1,
1, 1, 1
];
//計算パターン2
_conv2 = new ConvolutionFilter(3, 3);
_conv2.matrix = [
1, 1, 1,
1, 0, 1,
1, 1, 1
];
//デバッグ
//addChild(new Stats());
var timer:Timer = new Timer(int(1000/RATE));
timer.addEventListener(TimerEvent.TIMER, is_life);
timer.start();
}
private function is_life(e:TimerEvent):void
{
//計算データコピー
_bmd1.copyPixels(_life, _life.rect, ZERO_P);
_bmd2.copyPixels(_life, _life.rect, ZERO_P);
//計算1
_bmd1.applyFilter(_bmd1, _life.rect, ZERO_P, _conv1);
//計算2
_bmd2.applyFilter(_bmd2, _life.rect, ZERO_P, _conv2);
//表示用処理
_life.fillRect(_life.rect, 0x000000);
_life.threshold(_bmd1, _life.rect, ZERO_P, "==", 0x03, 0xFF010101, 0x000000FF, false);
_life.threshold(_bmd2, _bmd2.rect, ZERO_P, "==", 0x03, 0xFF010101, 0x000000FF, false);
}
}
}