In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

flash on 2011-10-22

[SWF(backgroundColor=0, width=465, height=465)]
text1.border = true;
stage.showDefaultContextMenu=false;
元に戻す               
フルスクリーンモード        
e.stopPropagation();//イベントの伝播を止める            
------------------------------------------------------------

リドゥ回数
background.graphics.lineStyle(0,0x000000);
background.graphics.beginBitmapFill(bitmapData);
background.graphics.drawRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
btn_recoverAll.graphics.drawRect(0,0,30, 30);

drawing canvas
@author naoto koshikawa

_____________________________________________________ Listener

MouseEvent.MOUSE_DOWN
@param    event

Event.ENTER_FRAME
@param    event

MouseEvent.MOUSE_UP
@param    event

drawing event
@author naoto koshikawa

jp.ppworks.drawing.simple
パッケージで使用できるツールのインターフェースです

@author naoto koshikawa

Pen Tool
@author naoto koshikawa

_____________________________________________________ Method
----------------------------------------------------------------------------
ホイール回転量
拡大率
フィールド
ozmap状態フラグ
テスト表示
Get Adobe Flash player
by tepe 15 Nov 2011
    Embed
/**
 * Copyright tepe ( http://wonderfl.net/user/tepe )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/ameh
 */

// forked from tepe's flash on 2011-3-19
package {
    import flash.events.*;
    import flash.display.*;
    import flash.text.*;
    //[SWF(backgroundColor=0, width=465, height=465)]
    public class FlashTest extends Sprite {
        private var node1:node = new node();
        private var text1:TextField = new TextField();
        private var sd:SimpleDrawing = new SimpleDrawing();
        private var iv:IsometricView = new IsometricView();
        
        public function FlashTest() {
            
            
            
            sd.y = 1000;
            sd.x = 10000;

            node1.map.addChild(sd);
            node1.map.addChild(iv);

         
            addChild(node1);
            text1.selectable = false;
            text1.height = 20;
            text1.width = 20;
            text1.textColor = 0xff00ff;
            //text1.border = true;
            addChild(text1);
            //stage.showDefaultContextMenu=false;
            stage.addEventListener(KeyboardEvent.KEY_DOWN,screenMode);
            addEventListener(Event.ENTER_FRAME,function():void{
                
                text1.text = String(node1.scaleSize);
            });


                
        }
        
        private function screenMode(e:KeyboardEvent):void{      
            
            if(e.keyCode == 13){
                if(node1.IsBrowseMode == true)node1.browseOff();
                else node1.browseOn();
                
            }
            else if(e.keyCode == 66){
                node1.returnHome();
            }
            else if(e.keyCode == 73){
                if(stage.displayState == StageDisplayState.FULL_SCREEN){
                    stage.displayState = StageDisplayState.NORMAL;//元に戻す               
                }
                else{
                    stage.displayState = StageDisplayState.FULL_SCREEN;//フルスクリーンモード        
                }
            }


            //e.stopPropagation();//イベントの伝播を止める            
        }
    }
}



//------------------------------------------------------------



// forked from naoto5959's お絵描きツール

    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    
class SimpleDrawing extends Sprite{
        private static const CANVAS_WIDTH:Number = 435;
        private static const CANVAS_HEIGHT:Number = 465;
        private static const RECOVERBLE:Number = 10;//リドゥ回数
        
        public function SimpleDrawing()
        {
            var bitmapData:BitmapData = new BitmapData(2, 2, true, 0x33AB7C10);
            bitmapData.setPixel(0, 0, 0x33ffffff);
            var background:Sprite = new Sprite();
            //background.graphics.lineStyle(0,0x000000);
            background.graphics.beginFill(0xffffff);
            background.graphics.drawRect(0,0,CANVAS_WIDTH, CANVAS_HEIGHT);
            background.graphics.endFill();
            //background.graphics.beginBitmapFill(bitmapData);
            //background.graphics.drawRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
            
            var canvas:Canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT, background, RECOVERBLE);
            canvas.attach("pen", new PenTool());
            canvas.change("pen");
            canvas.options = {thickness:2, color:0x000000};
            canvas.activate();

            addChild(canvas);

            var btn_recover:Sprite = new Sprite();
            btn_recover.graphics.beginFill(0xff0000);
            btn_recover.graphics.drawRect(0,0,30, 30);
            btn_recover.x = canvas.width;
            btn_recover.y = 0;
            btn_recover.addEventListener(MouseEvent.CLICK,
            function(event:MouseEvent):void
            {
                    canvas.recover();
            }
            );
            var txt_recover:TextField = new TextField();
            txt_recover.x = txt_recover.y = 0;
            txt_recover.autoSize = TextFieldAutoSize.LEFT;
            txt_recover.text = "戻す";
            txt_recover.mouseEnabled = false;
            btn_recover.addChild(txt_recover);
            addChild(btn_recover);

            var btn_recoverAll:Sprite = new Sprite();
            btn_recoverAll.graphics.beginFill(0x00ff00);
            //btn_recoverAll.graphics.drawRect(0,0,30, 30);
            btn_recoverAll.graphics.drawRoundRect(0,0,30,30,10)
            btn_recoverAll.x = canvas.width;
            btn_recoverAll.y = btn_recover.height;
            btn_recoverAll.addEventListener(MouseEvent.CLICK,
            function(event:MouseEvent):void
            {
                    canvas.recoverAll();
            }
            );
            var txt_recoverAll:TextField = new TextField();
            txt_recoverAll.x = txt_recoverAll.y = 0;
            txt_recoverAll.autoSize = TextFieldAutoSize.LEFT;
            txt_recoverAll.text = "消す";
            txt_recoverAll.mouseEnabled = false;
            btn_recoverAll.addChild(txt_recoverAll);

            addChild(btn_recoverAll);
        }
}    







import flash.display.*;
import flash.events.*;
/**
 * drawing canvas
 * @author naoto koshikawa
 */
class Canvas extends Sprite{
    private var _cache:Sprite;
    private var _mask:Shape;
    private var _background:Bitmap;
    private var _original:BitmapData;
    private var _history:Array;
    private var _length:int;
    private var _recoverableCount:uint;
    private var _width:Number;
    private var _height:Number;
    
    private var _currentTool:ITool;
    public function get currentTool():ITool
    {
        return _currentTool;
    }
    
    private var _tools:Object;
    public function set options(options:Object):void
    {
        if (_currentTool) _currentTool.options = options;
    }
    
    public function get recoverable():Boolean
    {
        return (_length) ? true:false;
    }
    
    private var _recoverableAll:Boolean;
    public function get recoverableAll():Boolean
    {
        return _recoverableAll;
    }
    
    public function Canvas(w:Number, h:Number, background:IBitmapDrawable, recoverableCount:uint = 0) 
    {
        _tools = { };
        _history = [];
        _recoverableAll = false;
        _recoverableCount = recoverableCount;
        _width = w;
        _height = h;
        _cache = new Sprite();
        _cache.graphics.beginFill(0, 0);
        _cache.graphics.drawRect(0, 0, _width, _height);
        addChildAt(_cache, 0);
        
        _mask = new Shape();
        _mask.graphics.beginFill(0, 0);
        _mask.graphics.drawRect(0, 0, _width, _height);
        mask = _mask;
        addChildAt(_mask, 0);
        
        if (background) updateBackground(background);
    }
    
    public function activate():void
    {
        addEventListener(MouseEvent.MOUSE_DOWN, mouseDownListener);
    }
    
    public function inactivate():void
    {
        removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownListener);
        removeEventListener(MouseEvent.MOUSE_UP, mouseUpListener);
        removeEventListener(MouseEvent.MOUSE_OUT, mouseUpListener);
        removeEventListener(Event.ENTER_FRAME, enterFrameListener);
    }
    
    public function getDrawingData():BitmapData
    {
        return getBitmapData(this);
    }
    
    public function stack(displayObject:DisplayObject):void
    {
        _history.push(displayObject);
        _length = _history.length;
        if (_length <= _recoverableCount) return;
        
        var i:uint;
        for (i = 1; i < _length; i++)
        {
            _history[i]["visible"] = false;
        }
        updateBackground(this);
        _history.shift();
        _length--;
        _cache.removeChildAt(0);
        
        for (i = 0; i < _length; i++)
        {
            _history[i]["visible"] = true;
        }
    }
    
    public function attach(key:String, tool:ITool):String
    {
        if (!_tools[key]) _tools[key] = tool;
        return key;
    }
    
    public function change(key:String):void
    {
        if (_tools[key]) _currentTool = _tools[key];
    }
    
    public function recover():void
    {
        if (_length) 
        {
            trace(_length);
            _cache.removeChildAt(--_length);
            _history.pop();
        }
    }
    
    public function recoverAll():void
    {
        for (var i:uint = 0; i < _length; i++)
        {
            _cache.removeChildAt(0);
        }
        _history = [];
        _length = 0;
        
        if (_background && contains(_background)) removeChild(_background);
        _background = new Bitmap(_original);
        addChildAt(_background, 0);
        _recoverableAll = false;
    }
    
    private function updateBackground(background:IBitmapDrawable):void
    {
        var bitmapData:BitmapData = getBitmapData(background);
        if (!_original) _original = bitmapData;
        if (_background && contains(_background)) removeChildAt(0);
        _background = new Bitmap(bitmapData);
        addChildAt(_background, 0);
    }
    
    private function getBitmapData(background:IBitmapDrawable):BitmapData
    {
        var bitmapData:BitmapData = new BitmapData(_width, _height);
        bitmapData.draw(background);
        return bitmapData;
    }
    
    // _____________________________________________________ Listener
    /**
     * MouseEvent.MOUSE_DOWN
     * @param    event
     */
    private function mouseDownListener(event:MouseEvent):void
    {
        var e:DrawingEvent = new DrawingEvent(DrawingEvent.START_DRAWING, true, true, mouseX, mouseY);
        dispatchEvent(e);
        if (!e.isDefaultPrevented())
        {
            addEventListener(MouseEvent.MOUSE_UP, mouseUpListener);
            addEventListener(MouseEvent.MOUSE_OUT, mouseUpListener);
            addEventListener(Event.ENTER_FRAME, enterFrameListener);
            if (_currentTool) 
            {
                _currentTool.start(mouseX, mouseY);
                _cache.addChildAt(_currentTool.displayObject, _length);
                _recoverableAll = true;
            }
        }
    }
    
    /**
     * Event.ENTER_FRAME
     * @param    event
     */
    private function enterFrameListener(event:Event):void
    {
        var e:DrawingEvent = new DrawingEvent(DrawingEvent.MOVE_DRAWING, true, true, mouseX, mouseY);
        dispatchEvent(e);
        if (!e.isDefaultPrevented())
        {
            if (_currentTool) _currentTool.move(mouseX, mouseY);
        }
    }
    
    /**
     * MouseEvent.MOUSE_UP
     * @param    event
     */
    private function mouseUpListener(event:MouseEvent):void
    {
        var e:DrawingEvent = new DrawingEvent(DrawingEvent.STOP_DRAWING, true, true, mouseX, mouseY);
        dispatchEvent(e);
        if (!e.isDefaultPrevented())
        {
            inactivate();
            activate();
            if (_currentTool)
            {
                stack(_currentTool.displayObject);
                _currentTool.stop(mouseX, mouseY);
            }
        }
    }
}


import flash.events.Event;

/**
 * drawing event
 * @author naoto koshikawa
 */
class DrawingEvent extends Event 
{
    public static const START_DRAWING:String = "startDrawing";
    public static const MOVE_DRAWING:String = "moveDrawing";
    public static const STOP_DRAWING:String = "stopDrawing";
    
    private var _x:Number;
    public function get x():Number
    {
        return _x;
    }
    
    private var _y:Number;
    public function get y():Number
    {
        return _y;
    }
    
    public function DrawingEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, x:Number = 0, y:Number = 0) 
    { 
        super(type, bubbles, cancelable);
        _x = x;
        _y = y;
    } 
    
    public override function clone():Event 
    { 
        return new DrawingEvent(type, bubbles, cancelable, _x, _y);
    } 
    
    public override function toString():String 
    { 
        return formatToString("DrawingEvent", "type", "bubbles", "cancelable", "eventPhase", "x", "y"); 
    }
    
}

import flash.display.DisplayObject;

/**
 * jp.ppworks.drawing.simple
 * パッケージで使用できるツールのインターフェースです
 * 
 * @author naoto koshikawa
 */
interface ITool 
{
    function get displayObject():DisplayObject;
    function set options(options:Object):void;
    function get options():Object;
    function start(x:Number, y:Number):void;
    function move(x:Number, y:Number):void;
    function stop(x:Number, y:Number):void;
}

import flash.display.DisplayObject;
import flash.display.Shape;

/**
 * Pen Tool
 * @author naoto koshikawa
 */
class PenTool implements ITool
{
    private var _displayObject:Shape;
    public function get displayObject():DisplayObject
    {
        return _displayObject;
    }
    
    private var _options:Object;
    public function get options():Object
    {
        return _options;
    }
    public function set options(options:Object):void
    {
        if (options && options.thickness) _options.thickness = options.thickness;
        if (options && options.color) _options.color = options.color;
    }
    
    // _____________________________________________________ Method
    public function PenTool() 
    {
        _options = {
            thickness:3,
            color:0x000000
        };
    }
    
    public function start(x:Number, y:Number):void
    {
        _displayObject = new Shape();
        _displayObject.graphics.lineStyle(
            _options.thickness,
            _options.color
        );
        _displayObject.graphics.moveTo(x, y);
    }
    
    public function move(x:Number, y:Number):void
    {
        if (!_displayObject) return;
        _displayObject.graphics.lineTo(x, y);
    }
    
    public function stop(x:Number, y:Number):void
    {
        if (!_displayObject) return;
        if (_displayObject.width == _options.thickness
            && _displayObject.height == _options.thickness)
        {
            _displayObject.graphics.clear();
            _displayObject.graphics.beginFill(_options.color);
            _displayObject.graphics.drawCircle(x, y, _options.thickness/2);
        }
        else
        {
            move(x, y);
        }
    }
}

//----------------------------------------------------------------------------



import flash.geom.*;
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.system.*;

class node extends Sprite{
        
        private var scale:Number = 1;
        
        public var wheel:int;//ホイール回転量
        private var zoom:Number = 1.0;//拡大率
        
        private var mapBase:Sprite;
        public var map:Sprite;//フィールド
        
        private var scrFocusX:Number=0; 
        private var scrFocusY:Number=0;
        private var mapWidth:int = Capabilities.screenResolutionX;
        private var mapHeight:int = Capabilities.screenResolutionY;

        private var mapscale:int=0;
        
        private var dragPanel:Sprite = new Sprite();
                
        //ozmap状態フラグ
        private const testMode:Boolean = false;//テスト表示
        private var mapBrowseMode:Boolean;//マップ移動操作
        private var mapDragMode:Boolean;//マップドラッグ中はtrue
        private var mapRotationMode:Boolean;//マップ回転操作
        
        
        //コンストラクタ 
        public function node():void{
            
            mapBase = new Sprite();//ズーム中心
            
            if(testMode == true){ 
                with( mapBase.graphics ){
                    lineStyle(1,0x00ff00,0.3);
                    moveTo(-100,0);
                    lineTo(100,0);
                    moveTo(0,-100);
                    lineTo(0,100);
                }
            }
            addChild(mapBase);
 
            
            //マップ上への配置
            map = new Sprite();
            
            if(testMode == true){
                var t3:TextField = new TextField();
                with(t3){
                    textColor = 0x0000ff;
                    selectable = false;
                    y = -20;
                    text = "map 0,0";
                }
                map.addChild(t3);
                with( map.graphics ){
                    lineStyle(1,0x0000ff,0.3);
                    moveTo(-100,0);
                    lineTo(100,0);
                    moveTo(0,-100);
                    lineTo(0,100);
                }
            } 
            
            browseOn();
 
            mapBase.addChildAt(map,0); 
            map.addChild(dragPanel);
            dragPanel.doubleClickEnabled = true;

            update();
    
        }
        
        public function get scaleSize():int{
            return mapscale;
        }
        
        //マップ移動操作状態
        public function get IsBrowseMode():Boolean{
            return mapBrowseMode;
        }
        //マップドラッグスクロール状態
        public function get IsDragMode():Boolean{
            return mapDragMode;
        }        
        //マップ回転操作状態
        public function get IsRotationMode():Boolean{
            return mapRotationMode;
        }

        //
        public function returnHome():void{
            map.x = 0;
            map.y = 0;
            map.scaleX = map.scaleY = 1.0;
            mapscale = 0;
            update();
            
        }

        
        
        //画面移動操作の受付 ON・OFF切り替え
        public function browseOn():void{
            
            mapBrowseMode = true;
            map.addEventListener(MouseEvent.MOUSE_DOWN,down);
            map.addEventListener(MouseEvent.MOUSE_UP,up);
            dragPanel.addEventListener(MouseEvent.DOUBLE_CLICK,onDouble);
            this.addEventListener(MouseEvent.MOUSE_WHEEL,on_wheel,true);//ホイール操作 
            map.addChild(dragPanel);
        }
        public function browseOff():void{
            wheel = 0;
            mapBrowseMode = false;
            map.removeEventListener(MouseEvent.MOUSE_DOWN,down);
            map.removeEventListener(MouseEvent.MOUSE_UP,up);
            dragPanel.removeEventListener(MouseEvent.DOUBLE_CLICK,onDouble);
            this.removeEventListener(MouseEvent.MOUSE_WHEEL,on_wheel,true);//ホイール操作 
            map.removeChild(dragPanel);
        }
        
        //ダブルクリックでマップブラウズモード解除 ⇒ オブジェクト操作モードに移行
        private function onDouble(e:MouseEvent):void{
            browseOff();
            //ホイール操作でブラウズモードに移行
            stage.addEventListener(MouseEvent.MOUSE_WHEEL,function():void{
                browseOn();
            });
        }


  
        //マップドラッグ開始
        private function down(e:MouseEvent):void{
            wheel=0;//ズーム操作ストップ

           e.currentTarget.startDrag();
           addEventListener(MouseEvent.MOUSE_MOVE,onMove);
           stage.removeEventListener(Event.ENTER_FRAME,onFrame);
           e.stopPropagation();//イベントの伝播を止める
           
        }
        
        private function up(e:MouseEvent):void{
            e.currentTarget.stopDrag();
            removeEventListener(MouseEvent.MOUSE_MOVE,onMove);
            e.stopPropagation();//イベントの伝播を止める
        }
        
        //マップドラッグ中
        private function onMove(e:MouseEvent):void{
            update();
        }

        //ホイール操作
        private function on_wheel(e:MouseEvent):void{  
            
            wheel += e.delta;
            
            if(wheel != 0)addEventListener(Event.ENTER_FRAME,onFrame);
            //else removeEventListener(Event.ENTER_FRAME,onFrame);
        }
  
        private function onFrame(e:Event):void {
            if(wheel==0){
                removeEventListener(Event.ENTER_FRAME,onFrame);
            }

            on_zoom(1+(0.005*wheel));
        }
        
        
        //マップ表示位置を更新
        private function update(z:Number=1, x:Number=0, y:Number=0, a:Number=0):void{
            var mX:int,mY:int;
            
            if(1<=z){//ズームイン
                mX = mouseX;
                mY = mouseY;//カーソル位置 
            }
            else{//ズームアウト
                mX = this.root.loaderInfo.width/2;
                mY = this.root.loaderInfo.height/2;//カーソル位置
            }
            
            //ズーム中心
            mapBase.x = mX;
            mapBase.y = mY; 
            //マップ位置
            map.x -= (mX-scrFocusX)/zoom;
            map.y -= (mY-scrFocusY)/zoom;
            //フォーカス位置
            scrFocusX = mX;
            scrFocusY = mY;
            

            //フィールドドラッグ用
            with(dragPanel.graphics){
                clear();
                beginFill(0xffffff,0.2);
                drawCircle( -map.x/map.scaleX, -map.y/map.scaleY, 1200/(zoom*map.scaleX) );
                
                endFill();
            }
            if(true){
                var i:int;
                var c:uint = 0x00aa00;
                const j:int = 32;
                with(dragPanel.graphics){
                    for(i= -20-(map.y/j);i<20-(map.y/j);i++){
                        if(Math.abs(i)%2 == 1)lineStyle(0,c,(zoom*0.5)-0.5);
                        else lineStyle(0,c,0.5);
                        moveTo((-600-map.x)/map.scaleX , i*j/map.scaleX);
                        lineTo((1600-map.x)/map.scaleX , i*j/map.scaleX);
                    }
                    for(i=-20-(map.x/j);i<40-(map.x/j);i++){
                        if(Math.abs(i)%2 == 1)lineStyle(0,c,(zoom*0.5)-0.5);
                        else lineStyle(0,c,0.5);
                        moveTo(i*j/map.scaleX, (-600-map.y)/map.scaleX);
                        lineTo(i*j/map.scaleX, (1600-map.y)/map.scaleX);
                    }
                }
            }
      
        }

        //ズーム処理
        private function on_zoom(z:Number=0):void{
            if(z==0)return;
            zoom *= z;    
                
            if(2 < zoom){
                with(map){
                    x+=x; y+=y;
                    scaleX = scaleY *= 2;
                }
                zoom /= 2;      
                mapscale--;
                
            }
            else if(zoom < 1.0){
                with(map){
                    x-=x/2; y-=y/2;
                    scaleX = scaleY /= 2;
                }        
                zoom *= 2;    
                mapscale++;
                    
            }
            
            with(mapBase){
                scaleX = scaleY = zoom;
            }
            update(z);//基準点更新      
          
        }
        
    }
    
//------------------------------------------------------------------------------------------

//    package{
    import flash.display.*;
    import flash.events.*;
    
    //public 
    class IsometricView extends Sprite {
  
        private var _blockContainer:MapChipContainer;
        
        /**
         * ブロックがいくつ積み重なっているかを記録するための 2 次元 Vector です.
         */
        private var _blockTop:Vector.<Vector.<int>> = new Vector.<Vector.<int>>();
 
        public function IsometricView() {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(event:Event = null):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);

            initStage();
            initEventListeners();
            
            _blockContainer = new MapChipContainer();
            addChild(_blockContainer);
            
            initBlocks(14, 14);
            
            onResize();
        }
        
        private function initStage():void {
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;
            stage.quality = StageQuality.HIGH;
        }

        private function initEventListeners():void {
            stage.addEventListener(Event.RESIZE, onResize);
        }
        
        private function initBlocks(w:int = 5, h:int = 5):void {
            for (var i:int = 0; i < w; i++ ){
                _blockTop[i] = new Vector.<int>();
                for (var k:int = 0; k < h; k++ ){
                    createBlock(i, k);
                    _blockTop[i][k] = 0;
                }
            }
        }
        
        private function createBlock(x:int, y:int, z:int = 0, tween:Boolean = false):void {
            var block:Block = new Block(x, y, z);
            block.addEventListener(MouseEvent.MOUSE_DOWN, onBlockMouseDown);
            block.buttonMode = true;
            _blockContainer.addMapChip(block, tween);
        }

        private function onResize(event:Event = null):void {
            _blockContainer.x = stage.stageWidth / 2 - _blockContainer.width / 2;
            _blockContainer.y = stage.stageHeight - 150;
        }
        
        private function onBlockMouseDown(event:MouseEvent):void {
            var target:Block = event.target as Block;
            var xpos:int = target.localX;
            var ypos:int = target.localY;
            //target.removeEventListener(MouseEvent.MOUSE_DOWN, arguments.callee);
            //target.buttonMode = false;
            _blockTop[xpos][ypos] = _blockTop[xpos][ypos] + 1;
            createBlock(xpos, ypos, _blockTop[xpos][ypos], true);
        }
    }
    
//}

//--------------------------------------------------------------------------

import flash.display.*;
import flash.events.*;
import flash.utils.Dictionary;
import org.libspark.betweenas3.BetweenAS3;
import org.libspark.betweenas3.easing.Expo;
import org.libspark.betweenas3.easing.Quart;
import org.libspark.betweenas3.easing.Quint;
import org.libspark.betweenas3.events.TweenEvent;
import org.libspark.betweenas3.tweens.IObjectTween;
import org.libspark.betweenas3.tweens.ITween;
import org.libspark.betweenas3.tweens.ITweenGroup;

/**
 * MapChipContainer クラス
 */
class MapChipContainer extends Sprite
{
    //--------------------------------------------------------------------------
    //
    // プロパティ
    //
    //--------------------------------------------------------------------------
    
    private var _chips:Vector.<Block> = new Vector.<Block>();
    private var _tween:Dictionary = new Dictionary(true);
    
    //--------------------------------------------------------------------------
    //
    // メソッド
    //
    //--------------------------------------------------------------------------
    
    /**
     * 新しい MapChipContainer クラスのインスタンスを作成します.
     */
    public function MapChipContainer() 
    {
        super();
    }
    
    /**
     * 指定したマップチップを追加します.
     * 
     * @param    chip
     * @param    tween 値が真の場合はトゥイーンして表示します.
     */
    public function addMapChip(chip:Block, tween:Boolean = false):void
    {
        _chips.push(chip);
        addChild(chip);
        
        setChildIndex(chip, numChildren - 1);
        if (tween)
        {
            var t:IObjectTween = BetweenAS3.tween(chip, { y: chip.y + Block.TWEEN_DISTANCE }, null, 0.4, Quint.easeIn);
            _tween[chip] = t;
            trace(_tween[chip])
            t.onComplete = sort;
            t.play();
        }
        else
        {
            chip.y += Block.TWEEN_DISTANCE;
            sort();
        }
    }
    
    /**
     * マップチップを正しい表示順にソートします.
     */
    public function sort():void
    {
        _chips.sort(function(a:Block, b:Block):int {
            if (_tween[a] && _tween[a].isPlaying) return 1;
            if (a.localZ > b.localZ) return 1;
            if (a.localZ < b.localZ) return -1;
            if (a.y == b.y) return 0;
            if (a.y > b.y) return 1;
            return -1;
        })
        var n:int = numChildren;
        for (var i:int; i < n; i++ )
        {
            setChildIndex(_chips[i], i);
        }
    }
    
}

//--------------------------------------------------------------------------

/**
 * Block クラス
 */
class Block extends Sprite
{
    //--------------------------------------------------------------------------
    //
    // プロパティ
    //
    //--------------------------------------------------------------------------
    
    // 色を格納する Array
    public static const COLORS:Array = [0xB5CC7A, 0x728D6C, 0xEDC06B, 0xF48D3E, 0xFF614E, 0xBC554E, 0x47ACBC, 0x4773A4];
    
    // Tween の距離 値を大きくするほど上の方から落ちてきます。
    public static const TWEEN_DISTANCE:Number = 200;
    
    // 幅の初期値
    public static const DEFAULT_WIDTH:Number = 60;
    
    // 奥行きの初期値
    public static const DEFAULT_DEPTH:Number = 40;
    
    // 高さの初期値
    public static const DEFAULT_HEIGHT:Number = 13;
    
    // 幅
    private var _width:Number = DEFAULT_WIDTH;
    
    // 奥行き
    private var _depth:Number = DEFAULT_DEPTH;
    
    // 高さ
    private var _height:Number = DEFAULT_HEIGHT;
    
    // 面
    private var _faces:Vector.<Shape> = new Vector.<Shape>();
    
    // ローカル座標 X
    private var _localX:int;
    
    // ローカル座標 Y
    private var _localY:int;
    
    // ローカル座標 Z
    private var _localZ:int;
    
    //--------------------------------------------------------------------------
    //
    // メソッド
    //
    //--------------------------------------------------------------------------
    
    /**
     * 新しい Block インスタンスを作成します.
     */
    public function Block(x:int, y:int, z:int)
    {
        super();
        
        _localX = x;
        _localY = y;
        _localZ = z;
        move(_localX, _localY, _localZ);
        
        this.y -= TWEEN_DISTANCE;
        
        createFaces();
        drawFaces();
    }
    
    /**
     * オブジェクトを移動します.
     */
    public function move(x:int, y:int, z:int):void
    {
        var xpos:int = x * Block.DEFAULT_WIDTH / 2 + y * Block.DEFAULT_WIDTH / 2;
        var ypos:int = y * Block.DEFAULT_DEPTH / 2 + -x * Block.DEFAULT_DEPTH / 2 - z * Block.DEFAULT_HEIGHT;
        
        this.x = xpos;
        this.y = ypos;
    }
    
    /**
     * 各面を作成します.
     */
    private function createFaces():void
    {        
        // top
        var top:Shape = new Shape();
        addChild(top);
        _faces.push(top);
        
        // left
        var left:Shape = new Shape();
        addChild(left);
        _faces.push(left);
        
        // right
        var right:Shape = new Shape();
        addChild(right);
        _faces.push(right);
    }
    
    /**
     * 各面を描画します.
     */
    private function drawFaces():void 
    {
        var g:Graphics;
        var commands:Vector.<int>;
        var path:Vector.<Number>;
        
        // 色
        var rand:int = (Math.random() * (COLORS.length/2) >> 0) * 2;
        var color:uint = COLORS[rand];
        var darkColor:uint = COLORS[rand+1];
        
        // コマンド
        commands = Vector.<int>([GraphicsPathCommand.MOVE_TO,
                                 GraphicsPathCommand.LINE_TO,
                                 GraphicsPathCommand.LINE_TO,
                                 GraphicsPathCommand.LINE_TO,
                                 GraphicsPathCommand.LINE_TO]);
        
        //{{ top
        
        // パス
        path = Vector.<Number>([_width / 2, 0, // top
                                0, _depth / 2, // left
                                _width / 2, _depth, // bottom
                                _width, _depth / 2, // right
                                _width / 2, 0]); // top
        
        g = _faces[0].graphics;
        g.clear();
        g.beginFill(color);
        g.drawPath(commands, path);
        g.endFill();
        
        //}} end of top
        
        //{{ left
        
        // パス
        path = Vector.<Number>([0, _depth / 2,
                                0, _height + _depth / 2,
                                _width / 2, _height + _depth, // center
                                _width / 2, _depth,
                                0, _depth / 2]);
        
        g = _faces[1].graphics;
        g.clear();
        g.beginFill(darkColor);
        g.drawPath(commands, path);
        g.endFill();
        
        //}} end of left
        
        //{{ right
        
        // パス
        path = Vector.<Number>([_width, _depth / 2,
                                _width, _height + _depth / 2,
                                _width / 2, _height + _depth,
                                _width / 2, _depth,
                                _width, _depth / 2]);
        
        g = _faces[2].graphics;
        g.clear();
        g.beginFill(darkColor);
        g.drawPath(commands, path);
        g.endFill();
        
        //}} end of right
    }
    
    //--------------------------------------------------------------------------
    // 
    // Getter / Setter
    //
    //--------------------------------------------------------------------------
    
    // width
    
    override public function get width():Number 
    {
        return _width;
    }
    
    override public function set width(value:Number):void 
    {
        _width = value;
        dispatchEvent(new Event(Event.RESIZE));
    }
    
    // height
    
    override public function get height():Number 
    {
        return _height;
    }
    
    override public function set height(value:Number):void 
    {
        _height = value;
        dispatchEvent(new Event(Event.RESIZE));
    }
    
    // faces
    
    public function get faces():Vector.<Shape> 
    {
        return _faces;
    }
    
    // localX
    
    public function get localX():int 
    {
        return _localX;
    }
    
    public function set localX(value:int):void 
    {
        _localX = value;
        move(_localX, _localY, _localZ);
    }
    
    // localY
    
    public function get localY():int 
    {
        return _localY;
    }
    
    public function set localY(value:int):void 
    {
        _localY = value;
        move(_localX, _localY, _localZ);
    }
    
    // localY
    
    public function get localZ():int 
    {
        return _localZ;
    }
    
    public function set localZ(value:int):void 
    {
        _localZ = value;
        move(_localX, _localY, _localZ);
    }
}

//--------------------------------------------------------------------------