ActionScript 3 AS3下拉/弹出菜单
package {
// er, didn't verify if all these imports are *truly* needed
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Stage;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.events.Event;
import flash.events.MouseEvent;
import com.caurina.transitions.Tweener;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class flyout extends MovieClip {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var openmenuShare:Boolean=false;
var closedShareY:Number;// for remembering the close position of the email menu
var openedShareY:Number;// "" for open position
public function flyout():void {
initShare();
}
private function initShare():void {
makeButton(share_menu_mc.share_button_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_face_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_twit_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_mysp_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_deli_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_digg_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_stum_mc, overItem, outItem, clickItem);
makeButton(share_menu_mc.share_flyout_mc.share_redd_mc, overItem, outItem, clickItem);
with (share_menu_mc.share_flyout_mc) {
closedShareY=y;
openedShareY=closedShareY+height;
}
}
private function makeButton(which_mc:MovieClip, overFunction:Function, outFunction:Function, clickFunction:Function):void {
which_mc.buttonMode=true;
which_mc.useHandCursor=true;
which_mc.mouseChildren=false;
which_mc.addEventListener(MouseEvent.MOUSE_OVER, overFunction);
which_mc.addEventListener(MouseEvent.MOUSE_OUT, outFunction);
which_mc.addEventListener(MouseEvent.CLICK, clickFunction);
}
private function overItem(e:Event) {
Tweener.addTween(e.currentTarget, {scaleX:1.05, scaleY:1.05, time:0.2});
switch (e.currentTarget.name) {
case "share_button_mc" :
if (!openmenuShare) {
Tweener.addTween(share_menu_mc.share_flyout_mc, {y:openedShareY, time:.5});
stage.addEventListener(Event.ENTER_FRAME,checkOverSharer);
}
openmenuShare=true;
break;
}
}
private function outItem(e:Event) {
switch (e.currentTarget.name) {
default :
Tweener.addTween(e.currentTarget, {scaleX:1, scaleY:1, time:0.2});
break;
}
}
private function clickItem(e:Event) {
trace(e.currentTarget.name);
var url:String = "";
switch (e.currentTarget.name) {
case "share_face_mc" :
navigateTo("http://www.example.com/");
break;
case "share_twit_mc" :
navigateTo("http://www.example.com/");
break;
case "share_mysp_mc" :
navigateTo("http://www.example.com/");
break;
case "share_deli_mc" :
navigateTo("http://www.example.com/");
break;
case "share_digg_mc" :
navigateTo("http://www.example.com/");
break;
case "share_stum_mc" :
navigateTo("http://www.example.com/");
break;
case "share_redd_mc" :
navigateTo("http://www.example.com/");
break;
}
}
private function navigateTo(urlString:String):void {
var request:URLRequest = new URLRequest(urlString);
try {
navigateToURL(request, '_blank'); // second argument is target
} catch (e:Error) {
trace("Error occurred!");
}
}
function checkOverSharer(event:Event) {
var leeway:Number = 5;
var myX:Number = share_menu_mc.x - share_menu_mc.share_button_mc.width/2; // why I don't need leeway on this, I dunno
var myY:Number = share_menu_mc.y - share_menu_mc.share_button_mc.height/2 - leeway;
var myW:Number = share_menu_mc.width + leeway;
var myH:Number = share_menu_mc.share_flyout_mc.height + share_menu_mc.share_button_mc.height + leeway;
if (isColliding(myX, myY, myW, myH) == false) {
stage.removeEventListener(Event.ENTER_FRAME, checkOverSharer);
Tweener.addTween(share_menu_mc.share_flyout_mc, {y:closedShareY, time:.5});
openmenuShare = false;
}
}
private function isColliding(tX:Number, tY:Number, tW:Number, tH:Number):Boolean
{
var drawCollision:Boolean = false;
var obj1_x:Number = tX;
var obj1_y:Number = tY;
var obj2_x:Number = mouseX - 1;
var obj2_y:Number = mouseY - 1;
var obj1_x2:Number = tW + obj1_x;
var obj1_y2:Number = tH + obj1_y;
var obj2_x2:Number = 2 + mouseX;
var obj2_y2:Number = 2 + mouseY;
if (drawCollision == true)
{
drawRectangle(obj2_x, obj2_y, 2, 2);
drawRectangle(obj1_x, obj1_y, tW, tH);
}
if ((obj2_x > obj1_x) && (obj2_x2 < obj1_x2) && (obj2_y > obj1_y) && (obj2_y2 < obj1_y2)) {
return true;
} else {
return false;
}
}
private function drawRectangle(boxX, boxY, boxWidth:Number, boxHeight:Number):void {
var square:Sprite = new Sprite();
addChild(square);
square.graphics.lineStyle(1,0xff0000);
square.graphics.beginFill(0x0000FF, .4);
square.graphics.drawRect(0,0,boxWidth,boxHeight);
square.graphics.endFill();
square.x = boxX;
square.y = boxY;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
ActionScript 3 基本开关
switch (example_string)
{
case "a":
trace ("a was selected");
break;
case "b":
trace ("b was selected");
break;
default:
trace ("Neither a or b was selected")
}
ActionScript 3 Box2DFlash下降文本
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
import Box2D.Dynamics.*;
import Box2D.Collision.*;
import Box2D.Collision.Shapes.*;
import Box2D.Common.Math.*;
public class TextFalls extends Sprite {
public var the_world:b2World;
public var physScale:Number=30;
public var final_body:b2Body;
public var the_body:b2BodyDef;
public var the_box:b2PolygonDef;
public var the_circle:b2CircleDef;
public var environment:b2AABB = new b2AABB();
public var gravity:b2Vec2=new b2Vec2(0.0,1);
public var dropTextTime:Timer;
public var linkbtn:Timer;
public var blockTrackingArray:Array = new Array();
public var labelTxt:TextField = new TextField();
public var labelTrackingArray:Array = new Array();
public var wordsArray:Array = new Array();
public var slot=0;
public var Text:String="SPACES CONNECT PEOPLE "
public var spriteArray:Array = new Array();
public var holderSprite:Sprite = new Sprite();
public function TextFalls() {
environment.lowerBound.Set(-100.0, -100.0);
environment.upperBound.Set(100.0, 100.0);
the_world=new b2World(environment,gravity,true);
buildWalls();
addEventListener(Event.ENTER_FRAME, on_enter_frame);
dropTextTime=new Timer(2000, 30);
dropTextTime.addEventListener(TimerEvent.TIMER, newText);
dropTextTime.start();
linkbtn=new Timer(2000, 1);
linkbtn.addEventListener(TimerEvent.TIMER, newbtn);
linkbtn.start();
wordsArray=Text.split(" ");
}
public function buildWalls() {
//This Turns on The Ability to View Where the Physics Blockades are (best to get used to the spacing)
/*var debug_draw:b2DebugDraw = new b2DebugDraw();
var debug_sprite:Sprite = new Sprite();
addChild(debug_sprite);
debug_draw.m_sprite=debug_sprite;
debug_draw.m_drawScale=30;
debug_draw.m_fillAlpha=0.5;
debug_draw.m_lineThickness=1;
debug_draw.m_drawFlags=b2DebugDraw.e_shapeBit;
the_world.SetDebugDraw(debug_draw);*/
the_body = new b2BodyDef();
the_body.position.Set(1238 / 2 / physScale, 682 / physScale);//physScale is used to make calculating time based physics and not frame based.
the_box = new b2PolygonDef();
the_box.SetAsBox( 619 / physScale, 1 / physScale);
the_box.friction=0.3;
the_box.density=0;
final_body=the_world.CreateBody(the_body);
final_body.CreateShape(the_box);
final_body.SetMassFromShapes();
the_body = new b2BodyDef();
the_body.position.Set(200 / physScale, 300 / physScale);
the_circle = new b2CircleDef();
the_circle.radius=0.4;
the_circle.density=0;
final_body=the_world.CreateBody(the_body);
final_body.CreateShape(the_circle);
final_body.SetMassFromShapes();
/*the_body = new b2BodyDef();
the_body.position.Set(600 / physScale, 200 / physScale);
the_circle = new b2CircleDef();
the_circle.radius=1.3;
the_circle.density=0;
final_body=the_world.CreateBody(the_body);
final_body.CreateShape(the_circle);
final_body.SetMassFromShapes();*/
the_body = new b2BodyDef();
the_body.position.Set(1000 / physScale, 200 / physScale);
the_circle = new b2CircleDef();
the_circle.radius=0.4;
the_circle.density=0;
final_body=the_world.CreateBody(the_body);
final_body.CreateShape(the_circle);
final_body.SetMassFromShapes();
}
private function NewTextLabel():void {
labelTxt = new TextField();
labelTxt.autoSize=TextFieldAutoSize.LEFT;
labelTxt.cacheAsBitmap=true;
labelTxt.embedFonts=true;
labelTxt.x=-100;
var format:TextFormat = new TextFormat();
format.font="Aller Display";
format.color=0xcccccc;
if (wordsArray[slot].length==0){
++slot;
}
if (slot>=wordsArray.length-1){
slot=0;
}
labelTxt.text=wordsArray[slot];
format.size=55;
labelTxt.defaultTextFormat=format;
labelTxt.text=wordsArray[slot];
++slot;
}
public function newText(evt:TimerEvent):void{
NewTextLabel();
holderSprite = new Sprite();
addChild(holderSprite);
holderSprite.addChild(labelTxt);
labelTxt.x=holderSprite.x-labelTxt.width/2;
labelTxt.y=holderSprite.y-labelTxt.height/2;
holderSprite.x = -1000;
holderSprite.y = -1000;
spriteArray.push(holderSprite);
labelTrackingArray.push(labelTxt);
var final_body:b2Body;
var the_body:b2BodyDef;
var the_box:b2PolygonDef;
the_body = new b2BodyDef();
the_body.position.Set(Math.random()*35+2, -1);
the_box = new b2PolygonDef();
the_box.SetAsBox(labelTxt.width/physScale/2, labelTxt.height/physScale/3);
the_box.friction=.7;
the_box.density=1;
the_box.restitution=0.2;
final_body=the_world.CreateBody(the_body);
final_body.CreateShape(the_box);
final_body.SetMassFromShapes();
blockTrackingArray.push(final_body);
}
public function on_enter_frame(evt:Event) {
the_world.Step(1/30, 10);
var detroyAt:Array = new Array();
var totalBlocks=blockTrackingArray.length;
for (var b = 0; b < totalBlocks; ++b) {
if (blockTrackingArray[b].GetPosition().y>768/physScale) {//Kills Block if it fall past the screen.
spriteArray[b].removeChild(labelTrackingArray[b]);
removeChild(spriteArray[b]);
the_world.DestroyBody(blockTrackingArray[b]);
detroyAt.push(b);
}
var bodyRotation:Number=blockTrackingArray[b].GetAngle();
spriteArray[b].rotation = bodyRotation * (180/Math.PI) % 360;
spriteArray[b].x = (blockTrackingArray[b].GetPosition().x * physScale);
spriteArray[b].y = (blockTrackingArray[b].GetPosition().y * physScale);
}
for (var d = detroyAt.length-1; d >= 0; --d) {
blockTrackingArray.splice(detroyAt[d], 1);
labelTrackingArray.splice(detroyAt[d], 1);
spriteArray.splice(detroyAt[d], 1);
detroyAt.pop();
}
}
public function newbtn(myEvent:TimerEvent):void{
labelTxt.addEventListener(MouseEvent.MOUSE_OVER, btnHover);
function btnHover(myEvent, MouseEvent):void{
var format:TextFormat = new TextFormat();
format.color=0xcccccc;
}
}
}
}
ActionScript 3 在线还是离线?
var LOCAL:Boolean = stage ? true : false;
ActionScript 3 走在贝齐尔
// Initial variables
var numPoints = 5; // number of points
var maxSpeed = .02; // travel speed
var focalLength = 500; // environmental constant
var centerX = Stage.width/2; // Stage Center X
var centerY = Stage.height/2; // Stage Center Y
//Initiate Animation
this.initFollowPath = function(){
// create data object to store points coordinates
oData = new Object();
// create camera object
this.oCamera = new Object();
// Set camera Properties
this.oCamera.z = focalLength; // target camera z position
this.oCamera.dz = 0; // initial camera z position
this.oCamera.s = maxSpeed; // camera zoom speed
// associate button action
for(var i = 0; i<numPoints;i++){
var d = -(i+1);
// attach point
var anchor = attachMovie("anchor", "point_"+ i, d);
// attach associated control point
var control = attachMovie("control", "ctrl_"+ i,100*d);
// set random position
anchor._x = control._x = random(Stage.width);
anchor._y = control._y = random(Stage.height);
// set buttons
anchor.onPress = this.initDrag;
anchor.onRelease = point.onReleaseOutside= this.endDrag;
control.onPress = this.initDrag;
control.onRelease = control.onReleaseOutside= this.endDrag;
}
// create follower
var clip = this.attachMovie("follow_mc","follow_mc", 1);
// set properties
clip.t = 0; // start travel time
clip.num = 0; // start at this point
clip.speed = maxSpeed; // set speed
// render clip
clip.onEnterFrame = render;
// create a clip for the line
this.createEmptyMovieClip("line_mc",10);
// start rendering line
this.onEnterFrame = drawLine;
}
// render
this.render = function () {
//increment time
this.t += slider/1000; // value from scrolBar
// add num if it reaches 1 if it reaches last point set back to 0
this.num = ((this.num + (this.t >= 1)) * (this.num<numPoints));
// reset to to 0 if we reach 1
this.t%=1;
// set init//end and controler clip position for animation
// according to the value of num
for(var i = 0; i<=numPoints;i++){
if (this.num == i){
var initX = oData["cx"+i];
var initY = oData["cy"+i];
// keep looping by reseting to 0 if we reach last point
var bezX = (i==numPoints-1) ? oData.cx0 : oData["cx"+(i+1)];
var bezY = (i==numPoints-1) ? oData.cy0 : oData["cy"+(i+1)];
// keep looping by reseting to 0 if we reach last point
var endX = (i==numPoints-1) ? oData.x0: oData["x"+(i+1)];
var endY = (i==numPoints-1) ? oData.y0: oData["y"+(i+1)];
}
}
// keep old positions in memory
var dx = this._x;
var dy = this._y;
// set position to follow_mc
this._x = setBezierPos(initX,endX,bezX,this.t);
this._y = setBezierPos(initY,endY,bezY,this.t);
// difference in position
dx = this._x-dx;
dy = this._y-dy;
// roate clip
this._rotation = Math.atan2(dy, dx)*180/Math.PI;
}
// Set bezier curve to follow
this.setBezierPos = function(p1,p2,p3,t){
// Equation to calculat position in curve
return p1*(1-t)*(1-t)+2*p2*(1-t)*t+p3*t*t;
}
ActionScript 3 字符串函数
public static function striplast(string:String, delimiter:*):String
{
var pattern:RegExp = new RegExp("\\" + delimiter , "i");
var a:Array = string.split(pattern);
delete a[a.length-1];
return a.join(delimiter);
// turn -> path/to/folder/ into -> /path/to/
}
public static function stripfirst(string:String, delimiter:*):String
{
var pattern:RegExp = new RegExp("\\" + delimiter , "i");
var a:Array = string.split(pattern);
delete a[0];
return a.join(delimiter);
// turn -> path/to/folder/ into -> /to/folder
}
public static function listlast(string:String, delimiter:*):String
{
var pattern:RegExp = new RegExp("\\" + delimiter , "i");
var a:Array = string.split(pattern);
return a[a.length-1];
// turn -> path/to/folder/ into -> folder
}
public static function listfirst(string:String, delimiter:*):String
{
var pattern:RegExp = new RegExp("\\" + delimiter , "i");
var a:Array = string.split(pattern);
return a[0];
// turn -> path/to/folder/ into -> path
}
public static function listGetAt(string:String, delimiter:*,index:int = 0):String
{
var pattern:RegExp = new RegExp("\\" + delimiter , "i");
var a:Array = string.split(pattern);
if (index > a.length) index = a.length - 1;
return a[index] + delimiter
// index = 1 turn -> path/to/folder/ into -> to
}
// var fileExtension:String = StringUtils.listlast("mysoundfile.flac",".");
// output -> flac
ActionScript 3 AS3 | KCComponent |基本组件
package kc.core {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.MovieClip;
import flash.events.Event;
import kc.events.KCComponentEvent;
import kc.utils.ClassUtil;
import kc.utils.UID;
[Event( name="disabled", type="kc.events.KCComponentEvent" )]
[Event( name="enabled", type="kc.events.KCComponentEvent" )]
[Event( name="dataChange", type="kc.events.KCComponentEvent" )]
public class KCComponent extends MovieClip {
// @protected
protected var _data:XML;
protected var _autorelease:Boolean;
// @private
private var _uid:String;
private var _owner:DisplayObjectContainer;
// @constructor
public function KCComponent( data:XML = null, autorelease:Boolean = true ) {
super();
// FlashCore
this.stop();
this.focusRect = false;
this.tabEnabled = false;
this.tabChildren = false;
// KCCompoenent
this.data = data;
this.autorelease = autorelease;
this.addEventListener(
Event.ADDED_TO_STAGE,
$config
);
}
// @override
override public function get enabled():Boolean {
return super.enabled;
}
override public function set enabled( value:Boolean ):void {
super.enabled = value;
this.dispatchEvent(
new KCComponentEvent(
( ! value )
? KCComponentEvent.DISABLED
: KCComponentEvent.ENABLED
)
);
}
// @methods
public function get data():XML {
return this._data;
}
public function set data( value:XML ):void {
if( this._data === value ) return;
this._data = value;
this.dispatchEvent(
new KCComponentEvent (
KCComponentEvent.DATA_CHANGE
)
);
}
public function get autorelease():Boolean {
return this._autorelease;
}
public function set autorelease( value:Boolean ):void {
if( this._autorelease == value ) {
return;
}
this._autorelease = value;
if( ! this._autorelease ){
this.removeEventListener(
Event.REMOVED_FROM_STAGE,
purge
);
}else{
this.addEventListener(
Event.REMOVED_FROM_STAGE,
purge
);
}
}
public function get owner():DisplayObjectContainer {
return this._owner || this.parent;
}
public function set owner( value:DisplayObjectContainer ):void {
this._owner = value;
}
public function get uid():String {
if( this._uid == null ){
this._uid = UID.create();
} return this._uid;
}
public function owns( value:DisplayObject ):Boolean {
if ( this.contains( value ) ) return true;
try{
while( value && value != this ){
if( value is IKCComponent ){
value = IKCComponent( value ).owner;
}else{
value = value.parent;
}
}
}catch( e:SecurityError ){
return false;
} return value == this;
}
public function applyToAllChildren( action:String, ...rest ):void {
var child:IKCComponent;
for ( var a:int = 0; a < this.numChildren; a++ ) {
if ( this.getChildAt(a) is IKCComponent ) {
child = this.getChildAt(a) as IKCComponent;
if( ClassUtil.isMethod( child, action ) ) {
child[action].apply( child, rest );
}else if ( ClassUtil.isPropertyWritable( child, action ) ) {
child[action] = rest[0];
}
}
}
}
public function position( x:Number, y:Number = NaN ):void {
this.x = x;
this.y = y || x;
}
public function scale( x:Number, y:Number = NaN ):void {
this.scaleX = x;
this.scaleY = y || x;
}
public function size( w:Number, h:Number = NaN ):void {
this.width = w;
this.height = h || w;
}
// @purge
public function purge(...rest):void {
this._data = null;
this._uid = null;
this._owner = null;
this._autorelease = undefined;
if ( this.hasEventListener( Event.REMOVED_FROM_STAGE ) ) {
this.removeEventListener(
Event.REMOVED_FROM_STAGE,
purge
);
}
if ( this.hasEventListener( Event.ADDED_TO_STAGE ) ) {
this.removeEventListener(
Event.ADDED_TO_STAGE,
$config
);
}
}
// @handlers
protected function $config(e:Event):void {
this.removeEventListener(
Event.ADDED_TO_STAGE,
$config
);
}
}
}
package kc.events {
import flash.events.Event;
public class KCComponentEvent extends Event {
// @const
public static const ENABLED:String = "enabled";
public static const DISABLED:String = "disabled";
public static const DATA_CHANGE:String = "dataChange";
// @constructor
public function KCComponentEvent( type:String, bubbles:Boolean=false, cancelable:Boolean=false ) {
super( type, bubbles, cancelable );
}
// @override
override public function clone():Event {
return new KCComponentEvent( this.type, this.bubbles, this.cancelable );
}
override public function toString():String {
return this.formatToString( "KCComponentEvent", "type", "bubbles", "cancelable", "eventPhase" );
}
}
}
package kc.utils {
import kc.core.KCStatic;
public class UID extends KCStatic {
// @const
private static const CHARS:Array = new Array( 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70 );
private static const SEPARATOR:uint = 45;
// @constructor
public function UID() {
super();
}
// @methods
public static function create( value:Array = null ):String {
var uid:Array = new Array();
var template:Array = value || new Array( 8,4,4,4,12 );
var last:int = template.length - 1;
for ( var a:uint = 0; a < template.length; a++ ) {
for ( var b:uint = 0; b < template[a]; b++ ) {
uid.push( CHARS[ Math.floor( Math.random() * CHARS.length ) ] );
} if ( a < last ) {
uid.push( SEPARATOR );
}
}
var time:String = String(
"0000000" + new Date().getTime().toString(16).toUpperCase()
).substr(
Math.random() * template[last]
);
return String(
String.fromCharCode.apply(
null,
uid
)
).substr(
0,
-time.length
) + time;
}
}
}
ActionScript 3 简单的广场
var square:Sprite = new Sprite();
addChild(square);
square.graphics.lineStyle(3,0x00ff00);
square.graphics.beginFill(0x0000FF);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;
ActionScript 3 AS3 ArrayQueue ADT类
package
{
import flash.display.Sprite;
/***********************************************************************************************\
* ArrayQueue Class - Designed to give generic functionality to a queue collection type. *
* This collection is to be implemented in a FIFO principles. With adding, removing, searching, *
* trace output, and state functions of the collection. *
* @author : Richard Vacheresse /|\ http://www.rvacheresse.com /|\ *
* Licensed for free Commercial and Private use creative commons license agreement. *
* The provided code is in an "as-is" state. Richard Vacheresse makes no warranties *
* regarding the provided code, and disclaims liability for damages resulting from its use. *
* @version 1.0 *
\***********************************************************************************************/
public class ArrayQueue extends Sprite implements QueueADT
{
//- default capapcity of queue
private var DEFAULT_CAPACITY:int = 100;
//- indicates the value of the last
private var rear:int;
//- array object to hold the objects
private var queue:Array;
/**
* ArrayQueue() Constructor - Creates an empty queue using the default capacity.
* @variable - DEFAULT_CAPACITY - The default value for the queue's capacity.
* @variable - rear - Indicates the value of the last object + one as an Integer object.
* @variable - queue - The container object that will hold the objects of type array.
**/
public function ArrayQueue():void
{
//- set rear to 0 since the queue is empty
rear = 0;
// - instantiate a new array object at the default capacity of 100
queue = new Array(DEFAULT_CAPACITY);
//- output to console
trace("New ArrayQueue Created At Default Capacity");
}
/**
* ArrayQueueDefined(queueSize:int) function - Creates an empty queue using the passed in value.
**/
public function ArrayQueueDefined(queueSize:int):void
{
//- set rear to 0 since the queue is empty
rear = 0;
// - instantiate a new array object at the passed value size
queue = new Array(queueSize);
//- output to console
trace("New ArrayQueue Created At: " + queueSize);
}
/**
* dequeue() function - Removes the first item in the queue.
* - Then shifts the queue minus the removed object
* - Decrement rear to reflect minus one object.
* @return - Object
**/
public function dequeue():Object
{
//- if the collection is empty throw an error
if(isEmpty())
throw new Error("Queue contains no objects");
//- else remove the object at the first position
var result:Object = queue[0];
//- decrement the rear by one
rear--;
//- shift the elements forward one position
for(var scan:int = 0; scan < rear; scan++)
queue[scan] = queue[scan+1];
//- set the rear null again to null
queue[rear] = null;
//- output to console
trace("Item " + result + " dequeued.");
//- return the first objec in the array
return result;
}
/**
* enqueue(obj:Object) function - Takes the passed object and adds it to the
* rear indicated position.
* - Increment the rear value + one to reflect
* the additional object.
**/
public function enqueue(obj:Object):void
{
queue[rear] = obj;
rear++;
}
/**
* first() function - Returns the first object in the queue but does not remove it.
* @return - Object
**/
public function first():Object
{
var result:Object = "null";
if(isEmpty())
throw new Error("The queue is empty");
//- set result pointer equal to first item but do not remove
result = queue[0];
//- output to console
trace("Item " + queue[0] + " is next.");
return result;
}
/**
* size() function - Returns the number of objects in the queue.
* @return - Integer Object
**/
public function size():int
{
return rear;
}
/**
* getLength() accessor function - Returns an integer value of the length of the queue.
* @return - Integer Object
**/
public function getLength():int
{
return queue.length;
}
/**
* isEmpty() function - Returns True if the value of rear is equal to zero.
* @return - Boolean Object
**/
public function isEmpty():Boolean
{
return (rear == 0);
}
/**
* expandCapacity() function - Creates a new array of twice the size of the current
* array queue.
* - Then it repopulates the new larger Array with the
* original values.
**/
public function expandCapacity():void
{
var result:int = (queue.length*2);
var larger:Array = new Array(result);
for(var scan:int = 0; scan < queue.length; scan++)
larger[scan] = queue[scan];
queue = larger;
}
/**
* toString():String function - Returns a custom String object to represent the queue.
* - Overriden only because it is of type Sprite, (which has
* by default its' own toString() function), therefore we
* need more information about the queue.
* @return - String Object
**/
override public function toString():String
{
var result:String = ("------------------\n" +
"Queue toString()\n" +
"------------------\n" +
"Queue has " + size() + " items.\n");
for(var scan:int = 0; scan < rear; scan++)
{
result += ("Item: " + scan + " is a: " + queue[scan] + "\n");
}
return result;
}
}
}
ActionScript 3 AS3 QueueADT接口
package
{
/**
* QueueADT interface - Designed to give generic functionality to a queue collection type.
* This collection is to be implemented in a FIFO principles. With adding, removing, searching,
* trace output, and state functions of the collection.
* @author : Richard Vacheresse /|\ http://www.rvacheresse.com /|\
* Licensed for free Commercial and Private use creative commons license agreement.
* The provided code is in an "as-is" state. Richard Vacheresse makes no warranties
* regarding the provided code, and disclaims liability for damages resulting from its use.
* @version 1.0
**/
public interface QueueADT
{
/**
* REMOVE THE FIRST OBJECT FROM THE QUEUE
* @variable - Generic Object
**/
function dequeue():Object;
/**
* ADD AN OBJECT TO THE END OF THE QUEUE
* @variable - Generic Object
**/
function enqueue(obj:Object):void;
/**
* RETURNS WITHOUT REMOVING THE OBJECT AT THE FRONT OF THE QUEUE
* @return - Boolean Object
**/
function first():Object;
/**
* RETURN TRUE IF THE NUMBER VALUE OF THE SIZE OF THE QUEUE
* @return - Number Object
**/
function size():int;
/**
* RETURN TRUE IF THE QUEUE OBJECT HAS ZERO OBJECTS
* @return - Boolean Object
**/
function isEmpty():Boolean;
/**
* RETURN A STRING REPRESENTATION OF THE CURRENT QUEUE OBJECT
* @return - String Object
**/
function toString():String;
}
}