Alternative

by Cheshir forked from Observer and simple Console (diff: 164)
Try to create an alternative to MovieClip
♥0 | Line 277 | Modified 2015-02-27 22:29:15 | MIT License
play

ActionScript3 source code

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

// forked from Cheshir's Observer and simple Console
package {
    import flash.system.ApplicationDomain;
    import flash.system.SecurityDomain;
    import flash.system.LoaderContext;
    import flash.events.IOErrorEvent;

    import flash.display.Loader;
    import flash.display.Bitmap;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.filters.GlowFilter;
    import flash.text.TextField;
    import flash.display.Sprite;

    public class FlashTest extends Sprite {
        public static var myConsole:Console;
        private var myObserver:Observer;
        private var galaxyHolder:Sprite;
        
        private var tileClipSheep:TileClip;
        
        public function FlashTest() {
            // write as3 code here..
            myConsole = new Console(stage);
            myObserver = new Observer(stage);
            galaxyHolder = new Sprite();
            
            this.graphics.beginFill(0x7c9b81);
            this.graphics.drawRect(0,0,600,600);
            addChild(galaxyHolder);
            myConsole.addComand('-cl',myObserver.removeAll, 'clear obserber');
            myConsole.help();
      //    Ooooo Yeaaa... it work... but was problem whis securityDomain
            var context:LoaderContext = new LoaderContext();
            context.checkPolicyFile = true;
            context.securityDomain = SecurityDomain.currentDomain;
            context.applicationDomain = ApplicationDomain.currentDomain;
            var url:URLRequest = new URLRequest('http://cheshir.zabix.net/footlocker/sheep_16_16.png');
            var img:Loader = new Loader();
            img.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
            img.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            img.load(url, context);
        }
        private function ioErrorHandler(e:IOErrorEvent):void{
            myConsole.log('error '+e.text);
        }

        private function loaded(e:Event):void
        {
            var bitmap:Bitmap = e.target.content;
            bitmap.y = 240;
            galaxyHolder.addChild(bitmap);    // show full set of graphics
            myConsole.log('this minimalist sheep');
            tileClipSheep = new TileClip(16,16,bitmap.bitmapData, 5);
            tileClipSheep.x = tileClipSheep.y = 120;
            tileClipSheep.demoMode = true;    // show all states one by one
            galaxyHolder.addChild(tileClipSheep);
            // Create new sheep - the adjusted animation
            var finalySheep:TileClip = new TileClip(16,16,bitmap.bitmapData, 9);
            finalySheep.x = 300;
            finalySheep.y = 340;
            finalySheep.delays = [5,5,25,15,15,15,25,15,5,15];    // maybe it should be ... random delay? I like random.
            // but if I make random delay I must to make them more
            finalySheep.scaleX = -9;
            finalySheep.randomDelay = true; // minimum delay -> maximum delay... I'm tired, but You can do it!
            galaxyHolder.addChild(finalySheep);           
            e.target.removeEventListener(Event.COMPLETE, loaded);
        }
    }
}
import flash.geom.Matrix;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.events.Event;
import flash.utils.Dictionary;
import flash.ui.Keyboard;
import flash.events.FocusEvent;
import flash.text.TextFieldType;
import flash.events.TextEvent;
import flash.events.KeyboardEvent;
import flash.display.Stage;
import flash.text.TextField;
import flash.display.Sprite;

Class{
    class TileClip extends Bitmap
    {
        public var demoMode:Boolean = false;
        public var randomDelay:Boolean = false;
        public var delays:Array = [];
        
        private var currentDelay:uint = 0;
        
        private var widthFrame:Number;
        private var heightFrame:Number;
        private var bitData:BitmapData;
        
        private var currFrame:uint = 0;
        private var totalFrame:uint = 0;
        private var currState:uint = 0;
        private var totalState:uint = 0;
        
        private var matrix:Matrix;
        
        // Create TileClip from bitmap Data
        public function TileClip(widthFrame:Number, heightFrame:Number, bitData:BitmapData, scale:Number = 1)
        {
            this.widthFrame = widthFrame;
            this.heightFrame = heightFrame;
            this.bitData = bitData;            // Safe data to draw
            matrix = new Matrix();        // Init Matrix transform
            totalFrame = uint(bitData.width / widthFrame);    // Calculate frames
            totalState = uint(bitData.height / heightFrame);    // Calculate states
            this.bitmapData = new BitmapData(widthFrame, heightFrame, true, 0);    // This is 'wiew window' of my clip
            super();
            currentFrame = 0;
            this.width = widthFrame * scale;
            this.height = heightFrame * scale;
            play();
        }
        public function set currentFrame(num:uint):void
        {
            if (num < totalFrame)    // Elementary update as looped video "currentFrame+=1"
            {
                this.currFrame = num;
            } else {
                this.currFrame = 0;
                if(demoMode){currentState++;}
            }
            setCurrentFrame();
        }
        public function get currentFrame():uint
        {
            return this.currFrame;
        }
        public function set currentState(num:uint):void
        {
            if (num < totalState)
            {
                this.currState = num;
            } else {
                this.currState = 0;
            }
            setCurrentFrame();
        }
        public function get currentState():uint
        {
            return this.currState;
        }
        public function play():void
        {
            this.addEventListener(Event.ENTER_FRAME, update);
        }
        public function stop():void
        {
            this.removeEventListener(Event.ENTER_FRAME, update);
        }
        public function update(e:Event):void
        {
            //currentFrame++;    // Maybe i must add delays to each frame?
            /* How can I add delays to frames... Delay can be a good idea becouse my sheep slightly twitch.
                I like a meditative thing ... */
            if(currentDelay <= 0){
               currentFrame++;
               currentDelay = (randomDelay) ? uint(delays[currentFrame]*Math.random()) : uint(delays[currentFrame]);
            //   I like random and it make my animation not so repetitive...
            //    FlashTest.myConsole.clear();
            //    FlashTest.myConsole.log('next frame delay '+currentDelay);
            } else {
                currentDelay--;
            }
        }
        
        private function setCurrentFrame():void    // DRY    (don't repeat yourself)
        {
            matrix.tx = -this.currFrame * widthFrame;    // positioning data
            matrix.ty = -this.currState * heightFrame;
            this.bitmapData.fillRect(this.bitmapData.rect, 0);    // clear 'wiew window'
            this.bitmapData.draw(bitData, matrix);
        }
    }
}


Class{
    class Observer {
        private var subscribers:Array = [];
        public function Observer(stage:Stage) {
            stage.addEventListener(Event.ENTER_FRAME, updateAll);
        }
        public function updateAll(e:Event):void {
            for each(var sub:ISubscr in subscribers){
                sub.update();
            }
        }
        public function addSubscr(sub:ISubscr):void{
            subscribers.push(sub);
        }
        public function removeSubscr(sub:ISubscr):void{
            for(var i:int=0; i<subscribers.length; i++){
                if(subscribers[i] == sub){
                    subscribers.slice(i, 1);
                }
            }
        }
        public function removeAll():void{
            for(var i:int=0; i<subscribers.length; i++){
                subscribers[i].destroy();
                subscribers[i] = null;
            }
            subscribers = [];
        }
        public function get numSubscr():Number {
            return subscribers.length;
        }
    }
}

Class {
    class Particle extends Sprite implements ISubscr {
        private var dx:Number;
        private var dy:Number;
        private var rad:Number;
        private var center:Point;
        public function Particle(x:Number, y:Number, stage:Stage, parent:Sprite){
            this.x = x;
            this.y = y;
            center = new Point(stage.stageWidth/2, stage.stageHeight/2);
            this.graphics.beginFill(0xffffff);
            this.graphics.drawCircle(0,0,2*Math.random()*Math.random());
            parent.addChild(this);
        }
        public function update():void{
            dx = center.x - this.x;
            dy = center.y - this.y;
            rad = Math.atan2(dy,dx)+1.4835298642;    // Collapse to center 
            this.x += Math.cos(rad);
            this.y += Math.sin(rad);
        }
        public function destroy():void{
            parent.removeChild(this);
        }
    }
}


Class {
    interface ISubscr {
        function update():void;
        function destroy():void;
    }
}


Class
{
    class Console extends Sprite {
        private var consoleField:TextField = new TextField();
        
        private var descript:Array = ['help', 'clear console'];
        
        private var diction:Dictionary = new Dictionary();
        
        public function Console(stage:Stage) {
            consoleField.background = true;
            consoleField.type = TextFieldType.INPUT; 
            consoleField.backgroundColor = 0x333333;
            consoleField.alpha = .6;
            consoleField.textColor = 0xf2f9ff;
            consoleField.width = stage.stageWidth;
            consoleField.scaleX = consoleField.scaleY = 1.4;
            stage.addChild(consoleField);
            consoleField.addEventListener(FocusEvent.FOCUS_IN, clear);
            consoleField.addEventListener(KeyboardEvent.KEY_UP, upKey);
            diction['-h'] = {func: help, descript: 'help function trace'};
            diction['-c'] = {func: clear, descript: 'clear console zone'};
        }
        public function log(str:Object):void {
            if(!str is String){
                str.toString();
            }
            consoleField.appendText(str+'\n');
        }
        
        public function addComand(comand:String, toCall:Function, desc:String="no descript"):void{
            diction[comand] = {func: toCall, descript: desc};
        }

        private function upKey(e:KeyboardEvent):void{
            if(e.keyCode == Keyboard.ENTER){
                // parse
                var key:String = '';
                for(var i:int = 1; i<=4; i++){
                    key = consoleField.text.charAt(consoleField.text.length-i)+key;
                    if(diction[key] != null){
                        (diction[key].func as Function).call();
                        return;
                    }
                }
            }
        }
        
        public function clear(event:FocusEvent = null):void{
            consoleField.text = '';
        }
        
        public function help():void {
            log('This is help - default');
            for (var key:Object in diction) 
            { 
                log(key +"\t is "+ diction[key].descript); 
            } 

        }

    }

}

Forked