From the monthly archives:

March 2010

Konference pro iPhone vývojáře

by Robin on March 30, 2010

Objevil jsem celkem praktický seznam konferencí a workshopů pro iPhone/iPad vývojáře, třeba se na některé potkáme. V ČR je o podobné workshopy a konference nouze, zatím tu byl jen iPhoneDevCamp od LSA, který byl hodně obecný — ale ukázalo se, že zájem tu je. Kluci z iKnow Clubu také něco zkoušejí, uvidíme jak budou přednášky hodnotné, první byla také hodně obecná.

Otázka do diskuze: Kolik by jste byli ochotni investovat do kurzu v Praze (2dny), který by se zaobíral kompletním workflow (dev, design, marketing) do hloubky?

s.Oliver Rubik’s Cube

by josefchutka on March 29, 2010

The Rubik’s Cube is a 3-D mechanical puzzle invented in 1974 by Hungarian sculptor and professor of architecture Ernő Rubik. My latest project was to create a 3D engine (I have used papervision) based on this logic + integrate with facebook. Finally, the game is ready and you can play s.Oliver ’s Cube on Facebook.

Quine in ActionScript 3

by josefchutka on March 29, 2010

In computing, a quine is a computer program which produces a copy of its own source code as its only output. For amusement, programmers sometimes attempt to develop the shortest possible quine in any given programming language.

While playing with wonderfl I have found a nice ActionScript quine solution from yonatan, which I decided to shorten. It would be shorter code using trace() but than you won’t be able to log/see output on wonderfl, thats why TextField is used.

… and here is the result:

The source code is the same as output:

package{
    import flash.display.*;
    import flash.text.*;
    public class Quine extends Sprite{
        public function Quine(){
            var t:*=addChild(new TextField),q:*=<![CDATA[package{
    import flash.display.*;
    import flash.text.*;
    public class Quine extends Sprite{
        public function Quine(){
            var t:*=addChild(new TextField),q:*=<![CDATA[2]>+'';
            t.text=q.replace(1+1,q+']'),t.width=t.height=465}}}]]>+'';
            t.text=q.replace(1+1,q+']'),t.width=t.height=465}}}

Feel free to try to fork it to even shorten source.

Another ActionScript quine attempts:


Game of life

by josefchutka on March 19, 2010

The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton. The “game” is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input from humans. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.

While I like ActionScript the most, I decided to make a version in flash. It is also fine moment to introduce wonderfl project. Wonderfl is a service where you can build Flash(swf) online. Wonderfl is online, free and social. After registration you are able to write and build your own codes, follow people, favourtie theirs work or even fork other user’s code (improve, change).

My aim was to make the code shortest possible, so you may find it mess, hell yeah it is :) . Try to fork my code on wonderfl to achieve shortest possible. Use some tricks to make your code shorter.

// Conway's Game of Life http://en.wikipedia.org/wiki/Conway's_Game_of_Life
// field 38x38 px

package{
    import flash.display.Sprite;

    public class GameOfLife extends Sprite{
        public function GameOfLife(){
            with(x)
            for each(i in w=h=38,a=new Array(w*h),b=[63,99,101,127,128,135,136,
                149,150,164,168,173,174,187,188,191,192,201,207,211,212,229,230,
                239,243,245,246,251,253,277,283,291,316,320,355,356])
                a[i]=1;
            addEventListener("enterFrame",function():void{
                with(graphics){
                for(clear(),c=[i=0];i<w*h;i++)
                    X=i%w,Y=int(i/w),j=X-1,k=X+1,l=Y-1,m=Y+1,
                    n=int(j>-1&&l>-1?a[i-37]:0)
                    +int(l>-1?a[i-w]:0)
                    +int(k<w&&l>-1?a[i-39]:0)
                    +int(j>-1?a[i-1]:0)
                    +int(k<w?a[i+1]:0)
                    +int(j>-1&&m<h?a[i+37]:0)
                    +int(m<h?a[i+w]:0)
                    +int(k<w&&m<h?a[i+39]:0),
                    c[i]=a[i]?(n==2||n==3)?1:0:int(n==3),
                    a[i]?drawRect(X*10,Y*10,10,10):beginFill(0);
                    a=c;
                }
            });
        }
    }
}

Where to go next

Common Tricks in ActionScript Code Shortening

by josefchutka on March 17, 2010

Code shortening can make your code more readable as well as more unreadable :-) . While it is recommend to use coding conventions and standards, in some cases you can spare a lot of lines using some shortening. In fact there must not be a conflict between using convetion vs. using shortening, and soon after you get used to some “shortcuts”, your code may be reduced in reasonable amount of lines. Some reading about code optimization can be found here, this article extends optimizations.

with() statement

Establishes a default object to be used for the execution of a statement or statements, potentially reducing the amount of code that needs to be written. You can use multiple with() statemens:

with(new Date)
with(Math)
    trace(hours, sin(0));

List style dynamic switch

Sometimes when you need to “switch” simple input value into output value, all you need is to choose item from list.

var m:uint = 3;
trace(['','I','II','III','IV'][m]);
trace({a:'AA',b:'BB'}['b']);

New instantion / addChild combo

While DisplayObjectContainer.addChild(child) returns inserted child as DisplayObject, you can cast it.

var s:Sprite = Sprite(addChild(new Sprite()))

Anonymous functions

ActionScript lets you put function definition directly where you normally put reference.

addEventListener(Event.ENTER_FRAME, function(event:Event):void
{
    trace("anonymous enter frame")
});

In order to get a reference to the currently executing function use arguments.callee. If you need to removeEventListener, use reference not direct definition.

Omitting curly braces

It is possible to omit curly braces with some block statements (for, for each, if, while) on single statement

for(var i:uint=0;i<100;i++)
    trace(i)

Joining multiple statements into single-like

In order to create single statement from multiple statement (to omit curly braces) join statements with “,”.

var i:uint;
while(i<10)
    i++,trace(i);

Ternar / conditional operator

Pretty common, but worth mentioning

for(var i:uint = 0; i < 3; i++)
    trace(i == 1 ? "BOMB" : i);

Operators (pre-increment, post-increment…)

Also pretty common

var i:uint = 0;
trace(i++, ++i, i--, --i);
i += 1, i *= 2, i /= 2, i -= 1, i %= 2;

Modulo operator (%) and alternation

The Modulus operator(%) computes the remainder of division between 2 integers. Can be use for alternation (color etc.)

for(var i:uint = 0; i < 10; i++)
    trace(i%3 ? i : "BOMB");

Action assignment

Result of assignment is value itself.

var i:uint, j:uint = 0;
trace(i = j = 2);

for statement

for statement definition says:

for ([init]; [condition]; [next])

… it means you can use it very creative way

var i:uint = 0;
with(graphics)
for(clear(),lineStyle(1,0);i<10;x=y=100,i++)
    lineTo(x*i, y*i*i);

logical OR operator (||) and first valid

Result of statement using logical OR is the first valid element. It can substitute ternar operator in some cases

trace(null || 0 || "" || "BOMB" || "never");
trace(defined ? defined : "default") // equals to trace(defined || "default")

Class Instantiating without “new”

Most common used is string delimiter (“), but there are also ones for XML and RegExp

var x:XML = <data></data>;
var r:RegExp = /.*/i;

Other

onConference – Facebook Video Chat Screencast

by josefchutka on March 15, 2010

At last, I managed to work youtube videos on my blog using Embedded Video plugin. Watch this youtube screencast video about how to make facebook video calls with onConference application:

RattingButtonBar class

by josefchutka on March 12, 2010

RatingButtonBar class extends ButtonBar and is meant to be used for ratings. Just like common star ratings all over the internet. Based on ButtonBar it makes it easy skinable for developers. Use bindable selectedIndex to get index of selected rating (zero based).

RatingButtonBar class

package sk.yoz.controls
{
    import flash.events.MouseEvent;

    import mx.controls.Button;
    import mx.controls.ButtonBar;

    public class RatingButtonBar extends ButtonBar
    {
        private var indexChanged:Boolean = false;
        private var suggestedIndex:int = -2;
        private var rollOverPhase:Object;
        private var rollOutPhase:Object;

        public function RatingButtonBar()
        {
            super();
        }

        override protected function createChildren():void
        {
            super.createChildren();
            selectValue(suggestedIndex != -2 ? suggestedIndex : selectedIndex);
            var children:Array = getChildren();
            for each(var button:Button in children)
            {
                button.addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
                button.addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
            }
        }

        override public function set selectedIndex(value:int):void
        {
            super.selectedIndex = value;
            suggestedIndex = value;
            selectValue(value);
        }

        protected function selectValue(value:int):void
        {
            if(value != selectedIndex)
            {
                selectedIndex = value;
                return;
            }
            var children:Array = getChildren();
            var index:uint = 0;
            var selected:Boolean = value != -1;
            var out:String = MouseEvent.ROLL_OUT;
            for each(var button:Button in children)
            {
                button.selected = selected;
                if(selected)
                    button.dispatchEvent(new MouseEvent(out, false, true));
                if(index++ == value)
                    selected = false;
            }
        }

        protected function overValue(value:int):void
        {
            var children:Array = getChildren();
            var index:uint = 0;
            var out:String = MouseEvent.ROLL_OUT;
            var over:String = MouseEvent.ROLL_OVER;
            for each(var button:Button in children)
            {
                if(index != value && !button.selected)
                    button.dispatchEvent(new MouseEvent(out, false, true));
                if(index++ < value && !button.selected)
                    button.dispatchEvent(new MouseEvent(over, false, true));
            }
        }

        override protected function clickHandler(event:MouseEvent):void
        {
            super.clickHandler(event);
            var children:Array = getChildren();
            selectValue(children.indexOf(event.target));
        }

        protected function rollOverHandler(event:MouseEvent):void
        {
            var children:Array = getChildren();
            var flag:Object = {};
            if(!rollOverPhase)
                rollOverPhase = flag;
            if(rollOverPhase != flag)
                return;
            overValue(children.indexOf(event.target));
            rollOverPhase = null;
        }

        protected function rollOutHandler(event:MouseEvent):void
        {
            if(rollOverPhase)
                return;

            var flag:Object = {};
            if(!rollOutPhase)
                rollOutPhase = flag;
            if(rollOutPhase != flag)
                return;
            overValue(-1);
            rollOutPhase = null;
        }
    }
}

Application

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal"
    xmlns:controls="sk.yoz.controls.*" backgroundColor="#ffffff">
<mx:Style>
ButtonBar {
    buttonStyleName: ratingButton;
    color: #999999;
}

.ratingButton {
    skin: Embed(source="../assets/star.png");
    overSkin: Embed(source="../assets/starOver.png");
    selectedUpSkin: Embed(source="../assets/starSelected.png");
    selectedOverSkin: Embed(source="../assets/starSelected.png");
    selectedDownSkin: Embed(source="../assets/starSelected.png");
}

</mx:Style>
<controls:RatingButtonBar id="rating" selectedIndex="1">
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
    <mx:Object label="" />
</controls:RatingButtonBar>
<mx:Text text="{rating.selectedIndex}" />
</mx:Application>

Result:


What fontName to use with embedding?

by josefchutka on March 10, 2010

This article extends “Embedding fonts bold vs. black” post. Sometimes it may be tricky to guess correct fontName with your font. Compilator works with different fontNames than what Flash IDE shows you. Lets say you want to embed fonts from .swf (library) file into .css file. In Flash IDE, properties panel for TextInput, character Family and Style stand for something totaly different that what you gonna need with correct fontName value later in .css file. In fact solution is very easy.

For example, for Helvetica font family, Flash IDE offers one Family called “Helvetica Neue LT Pro” with different styles “65 Medium”, “55 Roman”:

Here comes the tricky part. When it comes to .css you may want to use:

@font-face
{
    src: url("assets/fonts.swf");
    fontFamily: "Helvetica Neue LT Pro";
    fontStyle: "65 Medium";
}

… but compiler would stop you saying:

font 'Helvetica Neue LT Pro' with normal weight and regular style not found
Unable to transcode assets/fonts.swf

… or something similar.

So how to find out what is the correct fontFamily for compilator? Thankfully, there is an easy help. Locate your .ttf (.otf) file and open it. In my case I have used default system font viewer (Windows XP), but I am sure you can use any solid font viewer application:

…and there you find your familyName. Now you can embed fonts:

@font-face
{
    src: url("assets/fonts.swf");
    fontFamily: "HelveticaNeueLT Pro 65 Md";
}

@font-face
{
    src: url("assets/fonts.swf");
    fontFamily: "HelveticaNeueLT Pro 55 Roman";
    fontWeight: bold;
}

Notice there is different fontFamily and fontWeight (normal vs. bold) used for each font. If you try to use something else (change fontWeight) with these font-face specifications, compiler would stop you again. The fontFamily thing seems to be clear, but for now the thing with fontWeight remains mystery for me (viewer is not saying a thing about it). Flash IDE font family and style are also suggested somehow mysteriously.