Monthly Archives: February 2009

String.localeCompare()

Actionscript:
  1. var letterA:String = "a";
  2. var letterZ:String = "z";
  3.  
  4. trace(letterA.localeCompare(letterZ));
  5. trace(letterZ.localeCompare(letterA));
  6. /*
  7. outputs
  8. -25
  9. 25
  10. */

String.localeCompare() calculates the sorting order between two Strings....

Posted in strings | Tagged , | Leave a comment

Random Sort

Actionscript:
  1. function randomize(a:*, b:*):int{
  2.        return Math.round(Math.random()*8) - 4;
  3. }
  4.  
  5. var i:int;
  6. var fruits:Array;
  7.  
  8. trace("Math.random()");
  9. for (i = 0; i<4; i++){
  10.   // reset fruits array:
  11.   fruits = ["apple", "grape","pear","cherry"];
  12.   fruits.sort(randomize);
  13.   trace(fruits);
  14. }
  15.  
  16.  
  17. // seeds
  18. var s1:Number= 0xFF00FF;
  19. var s2:Number = 0xCCCCCC;
  20. var s3:Number= 0xFF00F0;
  21.  
  22. function tRandomize(a:*, b:*):int{
  23.        return Math.round(rand()*8) - 4;
  24. }
  25.  
  26. trace("\nTausworthe rand()");
  27. for (i= 0; i<4; i++){
  28.   fruits = ["apple", "grape","pear","cherry"];
  29.   fruits.sort(tRandomize);
  30.   trace(fruits);
  31. }
  32. // from www.ams.org/mcom/1996-65-213/S0025-5718-96-00696-5/S0025-5718-96-00696-5.pdf
  33. function rand():Number {
  34.     s1=((s1&4294967294)<<12)^(((s1<<13)^s1)>>19);
  35.     s2=((s2&4294967288)<<4)^(((s2<<2)^s2)>>25);
  36.     s3=((s3&4294967280)<<17)^(((s3<<3)^s3)>>11);
  37.     var r:Number = (s1^s2^s3) * 2.3283064365e-10;
  38.     r = (r<0) ? r+=1 : r;
  39.     return r;
  40. }
  41.  
  42. /*
  43. outputs:
  44. Math.random()
  45. grape,apple,pear,cherry
  46. pear,cherry,apple,grape
  47. grape,apple,pear,cherry
  48. grape,apple,cherry,pear
  49.  
  50. Tausworthe rand()
  51. apple,grape,pear,cherry
  52. cherry,grape,pear,apple
  53. grape,apple,cherry,pear
  54. grape,pear,apple,cherry
  55. */

The above shows how to randomly sort or shuffle an array. This is useful in games. To achieve this I made use of the compareFunction argument of Array.sort(). Most sorting algorithms go through the array and compare values until the desired sort order is achieved. The compareFunction argument is a function that takes two values a and b and returns an integer that is negative positive or zero... see this info from the docs:
* A negative return value specifies that A appears before B in the sorted sequence.
* A return value of 0 specifies that A and B have the same sort order.
* A positive return value specifies that A appears after B in the sorted sequence.

So in the case of a randomizing an array you simply need to return a random int -1, 0 or 1. This is what I've done in the past (Math.round()*2) -1) ... but when I was writing this snippet it seemed like 0 caused less variation in the output of the array so I made the range from -4 to 4 instead. This could have just been my imagination, but it seems like having less chance of a zero caused the arrays to be a bit more shuffled.

The reason I also included a version that uses Tausworthe is because of the easy seeding. In some cases you may want to use seeded randomness to sort an array.

UPDATE:
Was digging around about this and found a much faster method for randomizing arrays... not a big deal if you have small arrays, but if you need to randomize 1000's of values this method is much faster than using Array.sort()

Posted in arrays, misc | Tagged , | Leave a comment

String.indexOf()

Actionscript:
  1. var words:String = "one two three four five";
  2.  
  3. trace("two: ", words.indexOf("two"));
  4.  
  5. var letters:String = "abcd";
  6.  
  7. trace("d: ",letters.indexOf("d"));
  8.  
  9. trace("z: ",letters.indexOf("z"));
  10.  
  11. /*
  12. outputs:
  13. two:  4
  14. d:  3
  15. z:  -1
  16. */

indexOf() searches a string for another string and returns an index... in line 3 above, I search the words string for the smaller string "two" and indexOf() gives me the index of the letter "t". If indexOf() doesn't find anything it will return -1 (as in the case of line 9).

I seem to recall using this in some unexpected places. I'll see if I can dig up an example over the next few days.

Posted in string manipulation, strings | Tagged , | Leave a comment

Zig Zag Binary ix2 & i/2

Actionscript:
  1. var txt:TextField = TextField(addChild(new TextField()));
  2. txt.text = "";
  3. txt.width = 190;
  4. txt.height = 400;
  5. txt.multiline = true;
  6.  
  7. var count:int = 1;
  8. function render():void{
  9.     var line = int(count).toString(2);
  10.     while(line.length <31){
  11.         line = "0" + line;
  12.     }
  13.     txt.appendText(line + "\n");
  14.     txt.scrollV= txt.maxScrollV;
  15. }
  16.  
  17. addEventListener(Event.ENTER_FRAME, onCountUp);
  18. function onCountUp(evt:Event):void {
  19.     count *= 2;
  20.     render();
  21.     if (count ==0x40000000){
  22.         removeEventListener(Event.ENTER_FRAME, onCountUp);
  23.         addEventListener(Event.ENTER_FRAME, onCountDown);
  24.     }
  25. }
  26. function onCountDown(evt:Event):void {
  27.     count /= 2;
  28.     render();
  29.     if (count ==1){
  30.         addEventListener(Event.ENTER_FRAME, onCountUp);
  31.         removeEventListener(Event.ENTER_FRAME, onCountDown);
  32.     }
  33. }

The above animates a zig zag pattern in a TextField.

Posted in Math, string manipulation, strings | Leave a comment

N to the power of N (with strings)

Actionscript:
  1. var input:String =  "a, b, c";
  2.  
  3. var words:Array = input.split(", ");
  4. var max:String = "";
  5. var maxD:String =  (words.length - 1).toString();
  6. for (var i:int = 0; i<words.length; i++){
  7.     max += maxD;
  8. }
  9. var maxInt:int = parseInt(max,words.length);
  10.  
  11. for(i = 0; i<=maxInt; i++){
  12.      var indices:String = i.toString(words.length);
  13.      var r:String = "";
  14.      var k:int=0;
  15.      for (var j:int = 0; j<indices.length; j++){
  16.          r += words[parseInt(indices.charAt(j))] +" ";
  17.          k++;
  18.      }
  19.      while(k <words.length) {
  20.         r = words[0] +" "+ r;
  21.         k++;
  22.      }
  23.     trace(r);
  24. }
  25. trace(i, " variations");

Like many things on this site, I coded this rather quickly and it can probably be cleaned up...

Setting the input variable of the above snippet to "a, b" will output:

a a
a b
b a
b b
4 variations

Setting the input to "a, b, c" will output:

a a a
a a b
a a c
a b a
a b b
a b c
a c a
a c b
a c c
b a a
b a b
b a c
b b a
b b b
b b c
b c a
b c b
b c c
c a a
c a b
c a c
c b a
c b b
c b c
c c a
c c b
c c c
27 variations

I created this to work with words... inputs like "bread, breath, blobs, backwards". Be careful because you can quickly get millions of outputs:

1 to the power of 1 is 1
2 to the power of 2 is 4
3 to the power of 3 is 27
4 to the power of 4 is 256
5 to the power of 5 is 3125
6 to the power of 6 is 46,656
7 to the power of 7 is 823,543
8 to the power of 8 is 16,777,216
etc...

Posted in Math, misc, string manipulation | Tagged , | Leave a comment

Tweetcoding

Actionscript:
  1. g=graphics;
  2. mt=g.moveTo;
  3. lt=g.lineTo;
  4. ls=g.lineStyle;
  5. m=Math;
  6. r=m.random;
  7. s=m.sin;
  8. i=0;
  9. o={};
  10. function f(e){
  11.     s=150,x=y=s,z=-s,c=(!i)?addChild(new Bitmap(new BitmapData(s,s))).bitmapData:c;while(i<22500)i++,c.setPixel(i%s,i/s,(i%s|i/s)*mouseX);i=1;
  12. }
  13. addEventListener("enterFrame",f);

Have to link to this very fun new contest:

http://tweetcoding.machine501.com/

http://gskinner.com/playpen/tweetcoding.html

I may just have to get a twitter account...

Posted in misc | Tagged , | Leave a comment

24hr Clock

Actionscript:
  1. var clock:Sprite = Sprite(addChild(new Sprite()));
  2. clock.x = clock.y = 150;
  3.  
  4. var bg:Shape = Shape(clock.addChild(new Shape()));
  5. with (bg.graphics) lineStyle(2, 0x666666), beginFill(0xEFEFEF), drawCircle(0,0,110);
  6.  
  7. var hHand:Shape = clockHand(6, 50);
  8. var mHand:Shape = clockHand(2, 80);
  9. var sHand:Shape = clockHand(1, 90);
  10.  
  11. var center:Shape = Shape(clock.addChild(new Shape()));
  12. with (center.graphics) beginFill(0x000000), drawCircle(0,0,5);
  13.  
  14. var hInc:Number = 360/24;
  15. var msInc:Number = 360/60 ;
  16. var nOff:Number = 6;
  17. var verdana:TextFormat = new TextFormat("Verdana", 8);
  18. // add numbers to clock
  19. for (var i:int = 0; i<24; i++){
  20.      var ang:Number = (i * hInc - 90) * Math.PI/180;
  21.      createNumber(70,ang, i.toString());
  22.      var ms:Number = i * 2.5;
  23.      if (ms % 5 == 0){
  24.         createNumber(95, ang, ms.toString());
  25.      }
  26. }
  27.  
  28. addEventListener(Event.ENTER_FRAME, onLoop);
  29. function onLoop(evt:Event):void {
  30.     var date:Date = new Date();
  31.     hHand.rotation =  hInc * date.getHours();
  32.     mHand.rotation =  msInc * date.getMinutes();
  33.     sHand.rotation =  msInc * date.getSeconds();
  34. }
  35.  
  36. function clockHand(thickness:Number, leng:Number):Shape{
  37.     var hand:Shape = Shape(clock.addChild(new Shape()));
  38.     with (hand.graphics) {
  39.         lineStyle(thickness, 0x000000, 1, true, LineScaleMode.NORMAL, CapsStyle.SQUARE);
  40.         lineTo(0,-leng);
  41.     }
  42.     return hand;
  43. }
  44.  
  45. function createNumber(radius:Number, theta:Number, str:String):void{
  46.     var t:TextField = TextField(clock.addChild(new TextField()));
  47.     with (t) defaultTextFormat = verdana, t.autoSize = "left";
  48.     t.text = str;
  49.     t.x = radius * Math.cos(theta) - nOff;
  50.     t.y = radius* Math.sin(theta) - nOff;
  51. }

I was watching a movie the other day and I saw a 24 hour clock in the background of one of the shots. After the movie I coded this snippet. It draws a very basic clock with an hour hand that takes 24 hours to go full circle...

Posted in misc | Tagged , | 4 Comments

Square Bracket Syntax & Typecasting

Actionscript:
  1. addChild(new TextField());
  2. getChildAt(0)["text"] = "Hello World";

Notice that square bracket syntax makes it so we don't need to typecast. Take a look at the other way:

Actionscript:
  1. addChild(new TextField());
  2. TextField(getChildAt(0)).text = "Hello World";

Typecasting is the way to go.... the square bracket technique is just an interesting trick.

I wrote this after somehow stumbling on this very entertaining page - it shows hello world written in approximately 200 different languages...

Posted in dynamic, misc | Tagged , | Leave a comment

Snap to Grid

Actionscript:
  1. [SWF(width = 600, height = 400)]
  2.  
  3. // draw the same grid as yesterday
  4. var tileSize:int = 40;
  5. var cols:int = stage.stageWidth / tileSize;
  6. var rows:int = stage.stageHeight / tileSize;
  7. var grid:Sprite = Sprite(addChild(new Sprite()));
  8. grid.graphics.lineStyle(0,0x000000);
  9. var i:int = 0;
  10. for (i = 1; i<cols; i++){
  11.     var posX:Number = i * tileSize
  12.     grid.graphics.moveTo(posX, 0);
  13.     grid.graphics.lineTo(posX, stage.stageHeight);
  14. }
  15. for (i = 1; i<rows; i++){
  16.     var posY:Number = i * tileSize
  17.     grid.graphics.moveTo(0, posY);
  18.     grid.graphics.lineTo(stage.stageWidth, posY);
  19. }
  20.  
  21. //
  22. // -- add a circle that snaps to the grid when dragged
  23. //
  24. var circle:Sprite = Sprite(addChild(new Sprite()));
  25. with (circle.graphics) beginFill(0xFF0000), drawCircle(0,0,10);
  26. circle.x = circle.y =  tileSize * 3;
  27. circle.buttonMode = true;
  28.  
  29. circle.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  30. function onDown(evt:MouseEvent):void {
  31.     addEventListener(Event.ENTER_FRAME, onRunSnapping);
  32. }
  33.  
  34. function onRunSnapping(evt:Event):void {
  35.     circle.x =  Math.round(mouseX / tileSize) * tileSize;
  36.     circle.y =  Math.round(mouseY / tileSize) * tileSize;
  37. }
  38.  
  39. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  40. function onUp(evt:MouseEvent):void {
  41.     removeEventListener(Event.ENTER_FRAME, onRunSnapping);
  42. }

This builds on yesterdays post by adding a draggable red circle that snaps to the grid. This is the real trick:

Actionscript:
  1. circle.x =  Math.round(mouseX / tileSize) * tileSize;
  2. circle.y =  Math.round(mouseY / tileSize) * tileSize;

Posted in Graphics, UI, motion | Tagged , | Leave a comment

Stage Grid

Actionscript:
  1. // try changing the size of  the stage
  2. [SWF(width = 600, height = 400)]
  3.  
  4. // try changing the tile size (make sure swf width and height are evenly divisible by this number)
  5. var tileSize:int = 20;
  6.  
  7.  
  8. var cols:int = stage.stageWidth / tileSize;
  9. var rows:int = stage.stageHeight / tileSize;
  10.  
  11. var grid:Sprite = Sprite(addChild(new Sprite()));
  12. grid.graphics.lineStyle(0,0x000000);
  13.  
  14. var i:int = 0;
  15.  
  16. for (i = 1; i<cols; i++){
  17.     var posX:Number = i * tileSize
  18.     grid.graphics.moveTo(posX, 0);
  19.     grid.graphics.lineTo(posX, stage.stageHeight);
  20. }
  21. for (i = 1; i<rows; i++){
  22.     var posY:Number = i * tileSize
  23.     grid.graphics.moveTo(0, posY);
  24.     grid.graphics.lineTo(stage.stageWidth, posY);
  25. }

This is a quick way to fill the stage with a grid. I like my grids to have square tiles with sizes like 5x5, 10x10 20x20 etc.... So as long as you make sure that you're swf width and height are evenly divisible by your tileSize, this snippet will work nicely.

Posted in Graphics | Tagged , | Leave a comment