Pi Calculate
/**
* Copyright Qwaz ( http://wonderfl.net/user/Qwaz )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/xii2
*/
package {
import com.bit101.components.PushButton;
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.BitmapData;
import flash.events.Event;
import flash.geom.Point;
[SWF(width=465, height=465)]
public class Main extends Sprite {
private const CALC_PER_FRAME:int = 3000;
private const DARK_CONST:Number = 0.995;
private var middle:Point;
private var radius:int;
private var bmd:BitmapData;
private var bm:Bitmap;
private var pt:Point = new Point();
private var pi:PushButton;
private var allView:PushButton;
private var cntView:PushButton;
private var all:Number=0;
private var cnt:Number=0;
public function Main():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function init(e:Event=null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
middle = new Point(stage.stageWidth / 2, stage.stageHeight / 2);
radius = stage.stageWidth / 2;
bmd = new BitmapData(stage.stageWidth, stage.stageHeight, false);
bm = new Bitmap(bmd);
this.graphics.beginFill(0xFF7777);
this.graphics.drawCircle(stage.stageWidth / 2, stage.stageHeight / 2, stage.stageWidth / 2);
bmd.draw(this);
this.graphics.clear();
this.addChild(bm);
pi = new PushButton(this);
allView = new PushButton(this, 0, pi.y + pi.height);
cntView = new PushButton(this, 0, allView.y + allView.height);
}
private function enterFrameHandler(e:Event):void {
var i:int;
for (i = 0; i < CALC_PER_FRAME; i++) {
pt.x = Math.random() * stage.stageWidth;
pt.y = Math.random() * stage.stageHeight;
all++;
if (Point.distance(pt, middle) <= radius) cnt++;
bmd.setPixel(pt.x, pt.y, darken(bmd.getPixel(pt.x, pt.y)));
}
pi.label = String(((cnt / all) * 4).toFixed(10));
allView.label = String(all);
cntView.label = String(cnt);
}
private function darken(num:uint):uint {
var r:uint = num >> 16;
var g:uint = (num & 0xFFFF) >> 8;
var b:uint = (num & 0xFF);
r *= DARK_CONST;
g *= DARK_CONST;
b *= DARK_CONST;
return (r << 16) + (g << 8) + b;
}
}
}