One day, I had nothing to do on a winter evening and I decided to translate a useful, as it seemed to me, post about 15 snippets for Action Script 3. You
can see the original
-there-if-click-on-this-long-phrase-through -defs , and the translation of the article can be seen here, and nowhere (except for habrakat) click and do not need.
Many additional code samples that were not in the original article are provided by the user
Flashist .
1. Random sorting
for ( var i: uint = 0; i < myArray.length; i++)
{
var rand: uint = int (Math.random() * myArray.length);
myArray.push( myArray.splice( rand, 1 )[0] );
}
* This source code was highlighted with Source Code Highlighter .
The authors of the article propose to imagine an array, as a deck of cards, from which, at each step of the cycle, a random card is “drawn”, after which it is added to the end of this deck. Personally, I don’t understand why they didn’t use the standard function of sorting arrays (and vectors) with which one could do something like the following:
/**
*
*
* @param obj1 1- .
* @param obj2 2- .
*
* @return , (-1, 0 1).
*/
public function randomizeSortFunction(obj1:Boolean, obj2:Object): int
{
var randNum: int = -1 + Math.floor((Math.random() * 3));
return randNum;
}
//
var array:Array = [0, 1, 2, 3, 4];
array.sort(ArrayTools.randomizeSortFunction);
trace(array);
* This source code was highlighted with Source Code Highlighter .
The second method seems to me more understandable. Moreover, it is a built-in AS3.
')
2. Positioning objects on the grid
The authors offer such a simple and short way to position objects. The operator of the remainder of the division (
% ) allows you to correctly position objects along the X axis, and the division with rounding down (
Math.floor ) helps to deal with the alignment of Y.
for ( var i: uint = 0; i < 20; i++)
{
var displayObject:MyDisplayObject = new MyDisplayObject();
displayObject.x = displayObject.width * ( i % 5 );
displayObject.y = displayObject.height * Math.floor( i / 5 );
addChild(displayObject);
}
* This source code was highlighted with Source Code Highlighter .
The example creates 20 objects of a certain fictional class
MyDisplayObject , which are located inside a grid with 5 columns. As you might have guessed, the number 5 in the code means the number of grid columns, i.e. if there were 7 columns, we would put 7 instead of 5.
3. Delete all “children” from DisplayObjectContainer
The base class for all containers with visual content (I'm talking now about the
DisplayObjectContainer , yes yes), does not have its own method for deleting all the child objects at once. No problem! =) Let's make such a method ourselves, thankfully, it is not difficult at all:
/**
* - .
*
* @param parentClip , .
*/
static public function removeAllChildren(parentClip:DisplayObjectContainer): void
{
// 1 ,
while (parentClip.numChildren > 0)
{
parentClip.removeChildAt(0);
}
}
* This source code was highlighted with Source Code Highlighter .
In addition, the present to you from the user Flashist, who shares a couple of functions for working with the DisplayObjectContainer and their "children":
/**
* - .
*
* @param parentClip , .
*/
static public function hideAllChildren(parentClip:DisplayObjectContainer): void
{
var childrenCount: int = parentClip.numChildren;
for ( var childrenIndex: int = 0; childrenIndex < childrenCount; childrenIndex++)
{
parentClip.getChildAt(childrenIndex).visible = false ;
}
}
/**
* - .
*
* @param parentClip , .
*/
static public function showAllChildren(parentClip:DisplayObjectContainer): void
{
var childrenCount: int = parentClip.numChildren;
for ( var childrenIndex: int = 0; childrenIndex < childrenCount; childrenIndex++)
{
parentClip.getChildAt(childrenIndex).visible = true ;
}
}
/**
* .
*
* @param child .
*/
static public function childRemoveItselfFromParent(child:DisplayObject): void
{
// ,
if (child == null || child.parent == null )
{
return ;
}
child.parent.removeChild(child);
}
parentClip.removeChildAt(0);
}
}
* This source code was highlighted with Source Code Highlighter .
4. Getting the URL of the page in which SWF is embedded
To get the URL of the page in which the flash drive is embedded, you need to use the
ExternalInterface class. In order not to go into unnecessary details, I’ll just say that in the example we use
ExternalInterface to access the DOM (Document Object Model) HTML page in which our flash drive is embedded.
The disadvantage of this approach is that the flash drive must be embedded in the HTML page, with the parameter
allowscriptaccess set to
sameDomain or
always . If you control the embedding of the flash drive in the HTML page, then for you this may not be a problem, however, if the flash drive is embedded by other people, this method may not work. To use this code, do not forget to import the flash.external.ExternalInterface class to your document:
function get currentURL():String
{
var url:String;
if (ExternalInterface.available)
{
return ExternalInterface.call( "window.location.href" );
}
return url;
}
* This source code was highlighted with Source Code Highlighter .
Alternatively, you can use the
url property of the
loaderInfo object, this property must be accessed through the root object of the flash drive (or via
stage (author's note)). Using this method, you will not know the URL of the HTML page where the flash drive is located, but you can find out where the flash drive itself is located. This method will allow you to find out on which domains your flash drive is available.
root.loaderInfo.url;
* This source code was highlighted with Source Code Highlighter .
I'd add from myself that in order to know where your flash drive is laid out, as well as to collect other very useful statistical information, you can use the cool-super-duper service
MochiBot , I do, yeah)
5. Rounding the coordinates of the DisplayObjectContainer objects and their "children"
This snippet pleased me a little, since, despite its obviousness and simplicity, I had not thought about it before. The point is that by passing the
DisplayObjectContainer function to the function, we launch a recursive call to this function, which rounds the coordinates of the container itself and all its child objects. Well, if one of the child objects is itself a member of the
DisplayObjectContainer class, then it is passed to the function, and so on until the last, until all the nested containers have been enumerated.
function roundPositions(displayObjectContainer:DisplayObjectContainer): void
{
if (!(displayObjectContainer is Stage))
{
displayObjectContainer.x = Math.round(displayObjectContainer.x);
displayObjectContainer.y = Math.round(displayObjectContainer.y);
}
for ( var i: uint = 0; i < displayObjectContainer.numChildren; i++)
{
var child:DisplayObject = displayObjectContainer.getChildAt(i);
if (child is DisplayObjectContainer)
{
roundPositions(child as DisplayObjectContainer);
} else
{
child.x = Math.round(child.x);
child.y = Math.round(child.y);
}
}
}
* This source code was highlighted with Source Code Highlighter .
Oh yes, the
Stage check is worth it in order not to accidentally try to refer to the
x and
y properties of the
Stage object that does not support them (an exception will be displayed).
6. A random number between 2 numbers
Well, everything is quite simple here, I don’t even want to explain anything) Just take it and use it.
function random(min:Number, max:Number):Number
{
return min + Math.random() * (max - min);
}
* This source code was highlighted with Source Code Highlighter .
And another extra gift from
Flashist . In this analogue of the function "built-in" attention, the ability to:
a) Automatically round off to a smaller integer.
b) Automatically round to the nearest integer.
c) Automatically round off to a larger integer.
Wow, that's really cool:
/**
* .
*
* @param minNum .
* @param maxNum .
* @param isNeedFloor .
* @param isNeedRound .
* @param isNeedCeil .
*
* @return .
*/
static public function getRandomNum(minNum:Number, maxNum:Number, isNeedFloor:Boolean = false , isNeedRound:Boolean = false , isNeedCeil:Boolean = false ):Number
{
var randNum:Number = minNum + Math.random() * (maxNum - minNum);
if (isNeedFloor)
{
randNum = Math.floor(randNum);
}
if (isNeedRound)
{
randNum = Math.round(randNum);
}
if (isNeedCeil)
{
randNum = Math.ceil(randNum);
}
return randNum;
}
* This source code was highlighted with Source Code Highlighter .
7. Random Boolean
Again, there is nothing particularly difficult about this, everyone should understand. Simple and often required function:
function get randomBoolean():Boolean
{
return Math.random() >= 0.5;
}
* This source code was highlighted with Source Code Highlighter .
8. Finding the angle between 2 points
And this is more interesting. Such functions are often required when developing games or applications where you need to respond to the movement / position of the mouse cursor:
function getAngle (x1:Number, y1:Number, x2:Number, y2:Number):Number
{
var dx:Number = x2 - x1;
var dy:Number = y2 - y1;
return Math.atan2(dy,dx);
}
* This source code was highlighted with Source Code Highlighter .
It is important to remember that the function returns the angle in radians, and not in degrees (as we all would be used to). But the following functions will help us with this little flaw.
9. Converting degrees to radians and back.
/**
* .
*/
/**
* .
*
* @param angle .
*
* @return .
*/
static public function convertAngleToRadians(angle:Number):Number
{
var radians:Number = angle / 180 * Math.PI;
return radians;
}
/**
* .
*
* @param radians .
*
* @return .
*/
static public function convertRadiansToAngle(radians:Number):Number
{
var angle:Number = radians * 180 / Math.PI;
return angle;
}
* This source code was highlighted with Source Code Highlighter .
10. Email validation
A useful snippet for creating websites and all sorts of registrations in games.
function isValidEmail(email:String):Boolean
{
var emailExpression:RegExp = /([a-z0-9._-]+?)@([a-z0-9.-]+)\.([az]{2,4})/i;
return emailExpression.test(email);
}
* This source code was highlighted with Source Code Highlighter .
It should be understood that this
RegExp does not provide a 100% guarantee (note by the author: unfortunately, I have not seen a single
RegExp yet, which would not be mistaken). In my three-minute experiments, he made a mistake in at least 3 cases. Try checking the addresses:
-mymail@mail.mail ,
.mymail @ mail.mail and
mymail@mail.mail .
11. Removing spaces
If you have ever had to remove some characters from a string, here is the solution to your problems =)
function stripSpaces( string :String):String
{
var s:String = string ;
return s.split( " " ).join( "" );
}
* This source code was highlighted with Source Code Highlighter .
The good-natured
Flashist shares with us the “advanced” version of this snippet, with which you can delete any substrings (not only spaces) and insert in their place the same way, any substrings (not just an empty string):
/**
* , .
*
* @param sourceString , .
* @param oldString , .
* @param newString , .
*
* @return , .
*/
static public function replaceText(sourceString:String, oldString:String, newString:String):String
{
// ,
var replacedString:String = sourceString.split(oldString).join(newString);
//
return replacedString;
}
* This source code was highlighted with Source Code Highlighter .
12. Slugify
Probably the term
Slug , the right thing to do in Russian will be to reverse it as CNC (human-understandable URLs), i.e. such a link that a person can easily read.
function slugify( string :String):String
{
const pattern1:RegExp = /[^\w- ]/g; // Matches anything except word characters, space and -
const pattern2:RegExp = / +/g; // Matches one or more space characters
var s:String = string ;
return s.replace(pattern1, "" ).replace(pattern2, "-" ).toLowerCase();
}
* This source code was highlighted with Source Code Highlighter .
This snippet takes the source string and cuts out from it all the characters incorrect for the formation of the URL, i.e. All characters except Latin, digits, hyphen and underscore. Spaces between “correct” words are replaced with hyphens. So, if you pass the line “Hello, this is an article about Flash! ^ @ # & *! @ ^ # * &, ActionScript, Adobe, snippets, and similar_drugs,” then it will return “-flash-actionscript-adobe -__- ".
13. Removal from http: // or https: // substrings and optional www removal from any string
Honestly, this functionality, for probably already 4 years of Flash development, I have never needed, but I do not exclude that it can be useful to someone, you never know what developers have some tasks.
function stripHttp( string :String, stripWWW:Boolean = false ):String
{
var s:String = string ;
var regexp:RegExp = new RegExp(!stripWWW ? "https*:\/\/" : "https*:\/\/(www\.)*" , "ig" );
return s.replace(regexp, "" );
}
* This source code was highlighted with Source Code Highlighter .
14. Removing HTML Markup
And this is more interesting, much more interesting. In general, a snippet allows you to clear text from HTML markup characters and leave only “clean” text. Enter "
Click here to find out more ", and you are left only "Click here to find out more.", Cool, what else to say.
function stripTags( string :String):String
{
var s:String = string ;
var regexp:RegExp = new RegExp( "<[^<]*<" , "gi" );
return s.replace(regexp, "" );
}
* This source code was highlighted with Source Code Highlighter .
15. Removing XML Namespaces
Again, I also never encountered the problem of name space conflicts in XML, but the original article says that such problems sometimes happen when XML is loaded from different sources.
function stripXMLNamespaces(xml:XML):XML
{
var s:String = xml.toString();
var pattern1:RegExp = /\s*xmlns[^\'\ "]*=[\'\"][^\'\"]*[\'\"]/gi;
s = s.replace(pattern1, " ");
var pattern2:RegExp = /<[\/]{0,1}(\w+:).*?>/i;
while(pattern2.test(s)) {
s = s.replace(pattern2.exec(s)[1], " ");
}
return XML(s);
}
* This source code was highlighted with Source Code Highlighter .
PS:
Well, that's probably all. I hope that these snippets will make life easier for someone and will be useful in everyday development. For myself, I noted a couple of interesting ones, which, I think, will still be useful to me.
Once again,
Flashist has kindly provided its code samples for the post, which was badly damaged by other users after a
desperate post , where he advised us all to think about how insignificant they are. Do not judge him strictly =) He himself already regretted a little about such a tag to the post and some bold comments. Actually, this post, probably, he would gladly publish himself, but only karma does not allow (I’m supposedly trying to knock him out a couple of advantages in karma.