Compare two xml
December 5, 2009
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var msg1:XML = <GREETING>
<TO>A</TO>
<FROM>Programmer</FROM>
<MESSAGE>Hello</MESSAGE>
</GREETING>;
var msg2:XML = <GREETING>
<TO>A</TO>
<FROM>Programmer</FROM>
<MESSAGE>Hello</MESSAGE>
</GREETING>;
trace(msg1.* == msg2.*); // Displays: true
}
}
}
Comparing Two Objects in Actionscript
December 5, 2009
Use this function to compare two objects that contains large number of properties.
public function compareObject(obj1:Object,obj2:Object):Boolean
{
var buffer1:ByteArray = new ByteArray();
buffer1.writeObject(obj1);
var buffer2:ByteArray = new ByteArray();
buffer2.writeObject(obj2);
// compare the lengths
var size:uint = buffer1.length;
if (buffer1.length == buffer2.length) {
buffer1.position = 0;
buffer2.position = 0;
// then the bits
while (buffer1.position < size) {
var v1:int = buffer1.readByte();
if (v1 != buffer2.readByte()) {
return false;
}
}
return true;
}
return false;
}
MP3 Player in AS3
September 17, 2008
This the code which you may use it to create a MP3 player using AS3. Copy these scripts in a class called Mp3Player and use this class in your flash cs3 as follows.
var player:Mp3Player = new Mp3Player();
player.play('blah.mp3');
or
var player:Mp3Player = new Mp3Player();
player.playlist = ['item1.mp3','item2.mp3'];
player.next();
package {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.net.URLRequest;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class Mp3Player extends EventDispatcher {
static public const EVENT_TIME_CHANGE:String = 'Mp3Player.TimeChange';
static public const EVENT_VOLUME_CHANGE:String = 'Mp3Player.VolumeChange';
static public const EVENT_PAN_CHANGE:String = 'Mp3Player.PanningChange';
static public const EVENT_PAUSE:String = 'Mp3Player.Pause';
static public const EVENT_UNPAUSE:String = 'Mp3Player.Unpause';
static public const EVENT_PLAY:String = 'Mp3Player.Play';
//
public var playing:Boolean;
public var playlist:Array;
public var currentUrl:String;
public var playlistIndex:int = -1;
//
protected var sound:Sound;
protected var soundChannel:SoundChannel;
protected var soundTrans:SoundTransform;
protected var progressInt:Number;
public function play( url:String ):void {
clearInterval(progressInt);
if ( sound ) {
soundChannel.stop();
}
currentUrl = url;
sound = new Sound();
sound.addEventListener(Event.COMPLETE, onLoadSong);
sound.addEventListener(Event.ID3, onId3Info);
sound.load(new URLRequest(currentUrl));
soundChannel = sound.play();
if ( soundTrans ) {
soundChannel.soundTransform = soundTrans;
} else {
soundTrans = soundChannel.soundTransform;
}
soundChannel.addEventListener(Event.COMPLETE, onSongEnd);
playing = true;
clearInterval(progressInt);
progressInt = setInterval(updateProgress, 30);
dispatchEvent(new Event(EVENT_PLAY));
}
public function pause():void {
if ( soundChannel ) {
soundChannel.stop();
dispatchEvent(new Event(EVENT_PAUSE));
playing = false;
}
}
public function unpause():void {
if ( playing ) return;
if ( soundChannel.position < sound.length ) {
soundChannel = sound.play(soundChannel.position);
soundChannel.soundTransform = soundTrans;
} else {
soundChannel = sound.play();
}
dispatchEvent(new Event(EVENT_UNPAUSE));
playing = true;
}
public function seek( percent:Number ):void {
soundChannel.stop();
soundChannel = sound.play(sound.length * percent);
}
public function prev():void {
playlistIndex--;
if ( playlistIndex < 0 ) playlistIndex = playlist.length - 1;
play(playlist[playlistIndex]);
}
public function next():void {
playlistIndex++;
if ( playlistIndex == playlist.length ) playlistIndex = 0;
play(playlist[playlistIndex]);
}
public function get volume():Number {
if (!soundTrans) return 0;
return soundTrans.volume;
}
public function set volume( n:Number ):void {
if ( !soundTrans ) return;
soundTrans.volume = n;
soundChannel.soundTransform = soundTrans;
dispatchEvent(new Event(EVENT_VOLUME_CHANGE));
}
public function get pan():Number {
if (!soundTrans) return 0;
return soundTrans.pan;
}
public function set pan( n:Number ):void {
if ( !soundTrans ) return;
soundTrans.pan = n;
soundChannel.soundTransform = soundTrans;
dispatchEvent(new Event(EVENT_PAN_CHANGE));
}
public function get length():Number {
return sound.length;
}
public function get time():Number {
return soundChannel.position;
}
public function get timePretty():String {
var secs:Number = soundChannel.position / 1000;
var mins:Number = Math.floor(secs / 60);
secs = Math.floor(secs % 60);
return mins + ":" + (secs < 10 ? "0" : "") + secs;
}
public function get timePercent():Number {
if ( !sound.length ) return 0;
return soundChannel.position / sound.length;
}
protected function onLoadSong( e:Event ):void {
}
protected function onSongEnd( e:Event ):void {
if ( playlist )
next();
}
protected function onId3Info( e:Event ):void {
dispatchEvent(new Event(Event.ID3, e.target.id3));
}
protected function updateProgress():void {
dispatchEvent(new Event(EVENT_TIME_CHANGE));
if ( timePercent >= .99 ) {
onSongEnd(new Event(Event.COMPLETE));
clearInterval(progressInt);
}
}
}
}
Current System Time using Timer()
September 11, 2008
This is about basically how to get your current system time using Timer() function using AS3.
For this you need to create four dynamic text boxes and name those as txtHrs, txtMins, txtSecs, and txtDate.
Put the following actions in your movie frame and create a class and use these.
var time:Timer = new Timer(10);
tm.addEventListener(TimerEvent.TIMER, update);
function update(tevt:TimerEvent):void {
var now:Date = new Date();
var hr:Number = now.hours;
var min:Number = now.minutes;
var sec:Number = now.seconds;
if (hr > 12) {
hr -= 12;
}
txtHrs.text = String(hr);
if (min < 10) {
txtMins.text = “0″;
}
else {
txtMins.text = “”;
}
txtMins.appendText(String(min));
if (sec < 10) {
txtSecs.text = “0″;
}
else {
txtSecs.text = “”;
}
txtSecs.appendText(String(sec));
txtDate.text = now.toDateString();
}
time.start();
Now test your movie and you can see your system time on your movie display.
Try this!.
Mac OSX Commands
August 21, 2008
Here are the commands that have been used in Mac OSX based Darwin open source kernel.
alias Create an alias
alloc List used and free memory
awk Find and Replace text within file(s)
basename Convert a full pathname to just a folder path
bash Bourne-Again SHell (Linux)
bless Set volume bootability and startup disk options.
break Exit from a loop
cal Display a calendar
case Conditionally perform a command
cat Display the contents of a file
cd Change Directory
chflags Change a file or folder's flags.
chgrp Change group ownership
chmod Change access permissions
chown Change file owner and group
chroot Run a command with a different root directory
cksum Print CRC checksum and byte counts
clear Clear terminal screen
cmp Compare two files
comm Compare two sorted files line by line
complete Edit a command completion [word/pattern/list]
continue Resume the next iteration of a loop
cp Copy one or more files to another location
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later date/time
cut Divide a file into several parts
date Display or change the date & time
dc Desk Calculator
dd Data Dump - Convert and copy a file
defaults The Mac OS X user defaults system.
df Display free disk space
diff Display the differences between two files
diff3 Show differences among three files
dig DNS lookup
dirname Convert a full pathname to just a path
dirs Display list of remembered directories
diskutil Disk utilities - Format, Verify, Repair
ditto Copy files and folders
dot_clean Remove dot-underscore files
dscacheutil Query or flush the Directory Service/DNS cache
dscl Directory Service command line utility
du Estimate file space usage
echo Display message on screen
ed A line-oriented text editor (edlin)
enable Stop or start printers and classes.
env Set environment and run a utility
eval Evaluate several commands/arguments
exec Execute a command
exit Exit the shell
expect Programmed dialogue with interactive programs
Also see AppleScriptexpand Convert tabs to spaces
expr Evaluate expressions
false Do nothing, unsuccessfully
fdisk Partition table manipulator for Darwin UFS/HFS/DOS
find Search for files that meet a desired criteria
fmt Reformat paragraph text
fold Wrap text to fit a specified width
for Expand words, and execute commands
foreach Loop, expand words, and execute commands
fsck Filesystem consistency check and repair
fsaclctl Filesystem enable/disable ACL support
fs_usage Filesystem usage (process/pathname)
ftp Internet file transfer program
GetFileInfo Get attributes of HFS+ files
getopt Parse positional parameters
goto Jump to label and continue execution
grep Search file(s) for lines that match a given pattern
groups Print group names a user is in
gzip Compress or decompress files
head Display the first lines of a file
hdiutil Manipulate iso disk images
history Command History
hostname Print or set system name
id Print user and group names/id's
if Conditionally perform a command
info Help info
install Copy files and set attributes
jobs List active jobs
join Join lines on a common field
kextfind List kernel extensions
kill Stop a process from running
l List files in long format (ls -l)
ll List files in long format, showing invisible files (ls -la)
less Display output one screen at a time
ln Make links between files (hard links, symbolic links)
locate Find files
logname Print current login name
login log into the computer
logout Exit a login shell (bye)
lpr Print files
lprm Remove jobs from the print queue
lpstat Printer status information
ls List information about file(s)
lsbom List a bill of materials file
lsof List open files
man Help manual
mkdir Create new folder(s)
mkfifo Make FIFOs (named pipes)
more Display output one screen at a time
mount Mount a file system
mv Move or rename files or directories
net Manage network resources
networksetup Network and System Preferences
nice Set the priority of a command
nohup Run a command immune to hangups
onintr Control the action of a shell interrupt
open Open a file/folder/URL/Application
osascript Execute AppleScript
passwd Modify a user password
paste Merge lines of files
pbcopy Copy data to the clipboard
pbpaste Paste data from the Clipboard
pico Simple text editor
ping Test a network connection
pkgutil List installed packages
pmset Power Management settings
popd Restore the previous value of the current directory
pr Convert text files for printing
printenv Print environment variables
printf Format and print data
ps Process status
pushd Save and then change the current directory
pwd Print Working Directory
quota Display disk usage and limits
rcp Copy files between machines.
repeat Execute a command multiple times
rm Remove files
rmdir Remove folder(s)
rpm Remote Package Manager
rsync Remote file copy - Sync file tree (also RsyncX)
say Convert text to audible speech
sched Schedule a command to run at a later time.
screen Multiplex terminal, run remote shells via ssh
screencapture Capture screen image to file or disk
sdiff Merge two files interactively
security Administer Keychains, keys, certificates and the Security framework
sed Stream Editor
set Set a shell variable = value
setenv Set an environment variable = value
setfile Set attributes of HFS+ files
shift Shift positional parameters
shutdown Shutdown or restart OS X
sleep Delay for a specified time
softwareupdate System software update tool
sort Sort text files
split Split a file into fixed-size pieces
stop Stop a job or process
su Substitute user identity
sudo Execute a command as another user
sum Print a checksum for a file
switch Conditionally perform a command
systemsetup Computer and display system settings
tail Output the last part of files
tar Tape ARchiver
tee Redirect output to multiple files
test Condition evaluation
textutil Manipulate text files in various formats
time Measure Program Resource Use
touch Change file timestamps
traceroute Trace Route to Host
tr Translate, squeeze, and/or delete characters
true Do nothing, successfully
tty Print filename of terminal on stdin
type Describe a command
umask Users file creation mask
umount a device
unalias Remove an alias
uname Print system information
unexpand Convert spaces to tabs
uniq Uniquify files
units Convert units from one scale to another
unset Remove variable or function names
unsetenv Remove environment variable
users Print login names of users currently logged in
uuencode Encode a binary file
uudecode Decode a file created by uuencode
vi Text Editor
wc Print byte, word, and line counts
where Report all known instances of a command
which Locate a program file in the user's path
while Execute commands
who Print all usernames currently logged on
whoami Print the current user id and name (`id -un')
xargs Execute utility - passing arguments
yes Print a string until interrupted
Hope you get known all the OSX commands
Beginning MAC Development
August 21, 2008
Why Develop On The Mac?
If you need answer to this, please take a look into MacZealots.
EFI
August 21, 2008
EFI
The Extensible Firmware Interface (EFI) is a specification that defines a software interface between an operating system and platform firmware. EFI is intended as a significantly improved replacement of the old legacy BIOS firmware interface historically used by all IBM PC-compatible personal computers. The EFI specification was originally developed by Intel, and is now managed by the Unified EFI Forum and is officially known as Unified EFI (UEFI).
Services
EFI defines boot services, which include text and graphical console support on various devices, bus, block and file services, and runtime services, such as date, time and NVRAM services.
Device drivers
In addition to standard architecture-specific device drivers, the EFI specification provides for a processor-independent device driver environment, called EFI Byte Code or EBC. System firmware is required by the UEFI specification to carry an interpreter for any EBC images that reside in or are loaded into the environment. In that sense, EBC is similar to Open Firmware, the hardware-independent firmware used in PowerPC-based Apple Macintosh and Sun Microsystems SPARC computers, amongst others.
Some architecture-specific (non-EBC) EFI device driver types can have interfaces for use from the operating system. This allows the OS to rely on EFI for basic graphics and network support until OS specific drivers are loaded.
Boot manager
An EFI boot manager is also used to select and load the operating system, removing the need for a dedicated boot loader mechanism (the OS boot loader is an EFI application).
Car race game in AS3
August 19, 2008
Here is the car race game that I have just started in AS3.
/*
* File : Main.as
* Author : Karthik
* Date : 12 Aug 2008
*
*
*/
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.display.Stage;
public class Main extends Sprite {
/*
* Declerations
*/
var mcRoad :MovieClip;
var mcCheckPoint :MovieClip;
var mcLastCheckPoint:MovieClip;
var mcRoadLine :MovieClip;
var mcLineContainer :MovieClip;
var mcCar :MovieClip;
var mcPlayButton :MovieClip;
var mcSpeedoMeter :MovieClip;
var mcGameOver :MovieClip;
var i :Number;
var trackLength :Number = 100;
var speedX :Number = 0;
var speedY :Number = 0;
var acceleration :Number = 0.75;
var friction :Number = 0.98;
/*
* Function : Main
* Param : NIL
* Return : NIL
* Description : Constructor method.
*/
public function Main() {
this.init();
}
/*
* Function : EnterFrame
* Param : NIL
* Return : NIL
* Description : Initialization method that adds all the required graphics,events to stage.
*/
public function init() {
// Add the road graphics to the center of the stage.
mcRoad = new Road();
mcRoad.x = stage.stageWidth * 0.5;
mcRoad.y = stage.stageHeight * 0.5;
addChild(mcRoad);
// Add the raod lines to the stage by duplicating it into multiple up to its track length
mcLineContainer = new MovieClip();
for(i=0;i<trackLength*0.5;i++) {
mcRoadLine = new Roadline();
mcRoadLine.x = stage.stageWidth * 0.5;
mcRoadLine.y = stage.stageHeight – i * 150;
mcLineContainer.addChild(mcRoadLine);
}
mcLastCheckPoint = new Checkpoint();
mcLastCheckPoint.x = stage.stageWidth * 0.5;
mcLastCheckPoint.y = stage.stageHeight – i * 150;
mcLineContainer.addChild(mcLastCheckPoint);
addChild(mcLineContainer);
// Add the checkpoint graphics to the center of the stage
mcCheckPoint = new Checkpoint();
mcCheckPoint.x = stage.stageWidth * 0.5;
mcCheckPoint.y = stage.stageHeight * 0.5;
addChild(mcCheckPoint);
// Add the car graphic to the center of the stage.
mcCar = new Car();
mcCar.x = stage.stageWidth * 0.5;
mcCar.y = stage.stageHeight * 0.5;
addChild(mcCar);
// Add the play button to the stage and make it to be clicked to start the game.
mcPlayButton = new Playbutton();
mcPlayButton.buttonMode = true;
mcPlayButton.x = stage.stageWidth * 0.80;
mcPlayButton.y = stage.stageHeight * 0.5;
mcPlayButton.addEventListener(MouseEvent.CLICK, PlaybuttonClicked);
addChild(mcPlayButton);
}
/*
* Function : EnterFrame
* Param : Any Event
* Return : NIL
* Description : This EnterFrame function is equalent to onEnterFrame function.
*/
private function EnterFrame(event:Event):void {
/*if (Key.isDown(Keyboard.UP)) {
mcLineContainer.y += 15;
mcCheckPoint.y += 15;
}*/
if (Key.isDown(Keyboard.LEFT)) {
//speedX = speedX-acceleration;
mcCar.x -= 4;
if(mcCar.x <= stage.stageWidth * 0.39) {
mcCar.x += 4;
}
}
if (Key.isDown(Keyboard.RIGHT)) {
//speedX = speedX+acceleration;
mcCar.x += 4;
if(mcCar.x >= stage.stageWidth * 0.61) {
mcCar.x -= 4;
}
}
if (Key.isDown(Keyboard.UP)) {
speedY = speedY-acceleration;
}
if (Key.isDown(Keyboard.DOWN)) {
speedY = speedY+acceleration;
}
speedX = speedX*friction;
speedY = speedY*friction;
mcLineContainer.y -= speedY;
mcCheckPoint.y -= speedY;
mcSpeedoMeter.speedHand.rotation -= speedY/60;
if(mcCar.hitTestObject(mcLastCheckPoint)) {
stage.removeEventListener(Event.ENTER_FRAME, EnterFrame);
mcGameOver = new Gameover();
mcGameOver.x = stage.stageWidth * 0.5;
mcGameOver.y = stage.stageHeight * 0.5;
addChild(mcGameOver);
}
}
/*
* Function : StartRace
* Param : NIL
* Return : NIL
* Description : Start race function will activate keyboard event to stage and invokes the EnterFrame function
* to the stage Enter_Frame event.
*/
private function StartRace():void {
stage.addEventListener(Event.ENTER_FRAME, EnterFrame);
Key.initialize(stage);
}
/*
* Function : PlaybuttonClicked
* Param : Mouse Event
* Return : NIL
* Description : Function will invoke the start race function up on Play button clicked
*/
private function PlaybuttonClicked(event:MouseEvent):void {
StartRace();
mcPlayButton.play();
mcSpeedoMeter = new Speedometer();
mcSpeedoMeter.x = stage.stageWidth * 0.15;
mcSpeedoMeter.y = stage.stageHeight * 0.9;
mcSpeedoMeter.speedHand.rotation = 0;
addChild(mcSpeedoMeter);
}
}
}
Get days between two given dates
August 8, 2008
public static function getDaysBetweenDates(date1:Date,date2:Date):int
{
var one_day:Number = 1000 * 60 * 60 * 24
var date1_ms:Number = date1.getTime();
var date2_ms:Number = date2.getTime();
var difference_ms:Number = Math.abs(date1_ms – date2_ms)
return Math.round(difference_ms/one_day);
}
Key.isDown in AS3
August 5, 2008
I have given the easy way to implement Key.isDown in AS3 here. This is the duplicated version from the original senocular’s post in KirupaForum (here)
Thanks to senocular
In ActionScript 2, you could use Key.isDown(keyCode) to determine whether or not a key was being pressed on the keyboard. This command is no longer available in ActionScript 3. In fact, there is no Key object in ActionScript 3. You can still access keyCodes by name, but through the Keyboard (flash.ui.Keyboard) class. For key recognition in ActionScript 3, you have to use keyboard events or, more specifically the KeyboardEvent.KEY_DOWN and KeyboardEvent.KEY_UP events. When a key is pressed on the keyboard, the KeyboardEvent.KEY_DOWN is dispatched and you can tell which key was pressed by checking KeyboardEvent.keyCode in the event handler. Same applies to keys being released in the KeyboardEvent.KEY_UP.
Using these events, you could recreate the functionality provided by the Key class in ActionScript 2. However, you should know that the KeyboardEvents only work when the Flash player has focus. This means a key could be pressed in Flash and released outside of Flash without Flash knowing that it was released (not having received the KEY_UP event). As a result, you should assume all keys released upon deactivation (loss of focus) of the Flash player. The following recreation of the Key class takes that into consideration.
// Key.as package { import flash.display.Stage; import flash.events.Event; import flash.events.KeyboardEvent; /** * The Key class recreates functionality of * Key.isDown of ActionScript 1 and 2. Before using * Key.isDown, you first need to initialize the * Key class with a reference to the stage using * its Key.initialize() method. For key * codes use the flash.ui.Keyboard class. * * Usage: * Key.initialize(stage); * if (Key.isDown(Keyboard.LEFT)) { * // Left key is being pressed * } */ public class Key { private static var initialized:Boolean = false; // marks whether or not the class has been initialized private static var keysDown:Object = new Object(); // stores key codes of all keys pressed /** * Initializes the key class creating assigning event * handlers to capture necessary key events from the stage */ public static function initialize(stage:Stage) { if (!initialized) { // assign listeners for key presses and deactivation of the player stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed); stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased); stage.addEventListener(Event.DEACTIVATE, clearKeys); // mark initialization as true so redundant // calls do not reassign the event handlers initialized = true; } } /** * Returns true or false if the key represented by the * keyCode passed is being pressed */ public static function isDown(keyCode:uint):Boolean { if (!initialized) { // throw an error if isDown is used // prior to Key class initialization throw new Error("Key class has yet been initialized."); } return Boolean(keyCode in keysDown); } /** * Event handler for capturing keys being pressed */ private static function keyPressed(event:KeyboardEvent):void { // create a property in keysDown with the name of the keyCode keysDown[event.keyCode] = true; } /** * Event handler for capturing keys being released */ private static function keyReleased(event:KeyboardEvent):void { if (event.keyCode in keysDown) { // delete the property in keysDown if it exists delete keysDown[event.keyCode]; } } /** * Event handler for Flash Player deactivation */ private static function clearKeys(event:Event):void { // clear all keys in keysDown since the player cannot // detect keys being pressed or released when not focused keysDown = new Object(); } } }