Sunday, August 29, 2010

Crazy Chickens video on youtube.

I have uploaded video of crazy chickens n900 game on youtube. Here youtube link for video, embedded video is below.

Tuesday, August 24, 2010

Crazy Chickens game for N900 (Maemo) using Qt

Recently I started to learn Qt' graphics view and I decided to put my learning in to some action and as output I created this game called crazy chickens. Its classic egg catcher game.

Goal of game is to catch eggs before they touch the ground. You get four chances if you let egg fall on ground. Speed of game increase as you catch more eggs. To make Motu(the fat boy) catch egg in to basket you need to touch hen which produced the egg. Game dose not take gravity into account so speed of egg remain constant till it fall to ground.

I already uploaded this game to maemo's extra-devel repository, so if you want to try the game enable extra-devel repository. I am also planning to promote this game to extra-testing repository soon so this game should be available in extra-testing repository as well.

Some snaps of this game from my N900.









Sunday, August 22, 2010

Nested function in c++

Recently while working on some code, I required to create nested function. Well in most case you can avoid use of nested function but in my case, in one function I required to use same code repeatedly and that piece of code was not going to be used else where so I wanted to keep that code inside original function only and I also wanted to remove redundant code. So I thought to create nested function.

By standard C++ dose not support use of nested function, some compiler allows it but that depends on compiler being used. So there is one work around by using you can achieve nested function in C++.

By using local class and overloading function operator we can simulate nested function. Following is my sample code to achieve nested function.
void foo() {
    class DoMyWork
    {
    public:
        int operator() (int args) {
            qDebug() << "Parameter passed:" << args;
            return args + 5;
        }
    } doMyWork;//creating instance of DoMyWork
//calling simulated nested function
    int retVal = doMyWork(5);
    qDebug() << "Returned value:" << retVal;
}
So that was all, hope this helps.

Friday, August 20, 2010

Debugging lzo(.lzo) file in maemo

If you are facing segmentation fault in Maemo device than there are some tools available to retrieve core dump files from the device. These tools are in the sp‐rich‐core package. sp‐rich‐core  will produce a core dump file and also additional information about process, most of /proc data, last lines from syslog, df, ifconfig output and much more.  All of such information is added to a
rich core dump package (.rcore) and then, it is compressed in .lzo file.

The core dumps by default are saved on directory /media/mmc1/core‐dumps on device.

To uncompressed core dump you need to use rich-core-extract tool. The package sp‐rich‐core‐postproc provides the rich‐core‐extract utility, which extracts the information from a rich core dump file that GDB can read.

To install this tool type following

apt-get install sp-rich-core sp-rich-core-postproc

Now to uncompress lzo file and to get core dump file use following command.

rich-core-extract core_file.lzo

For more information using gdb in maemo environment visit this post.

Also visit this link for more information on debugging on maemo platform.

Thursday, August 19, 2010

Excellent tutorial about OAuth

I found an excellent article about OAuth protocol thought to share it. It explain concept with example and vary good detail. Have look at it at following link.

http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/

Monday, August 16, 2010

Creating custom graphics item in Qt's graphics view

Now a days I started to learn Qt's Graphics view. Initially I was struggling with it but once I started programming with it I found that its quite easy and powerful. What I like most about it is, while creating custom item we can perform paint opration with items local coordinate and need not worry about scene coordinate.

While creating custom graphics item, Your class needs to be derived from QGraphicsItem or QGraphicsObject. If your object needs to use signal/slot than derive your class from QGraphicsObject else derive it from QGraphicsItem and override paint and boundingRect methods.

For test application I tried to create sprite with custom graphics item that shows rolling ball animation. Following is code for my custom graphics item.
#include <QGraphicsObject>
#include <QPixmap>

class BallGraphicsItem : public QGraphicsObject
{
    Q_OBJECT
public:

    BallGraphicsItem();
    ~BallGraphicsItem();

    void paint ( QPainter * painter, 
const QStyleOptionGraphicsItem * option, 
QWidget * widget = 0 );

    QRectF boundingRect() const;

public slots:
    void move();
    void nextFrame();
private:

    QPixmap mBallImage;    
    int mCurrentRow;
    int mCurrentColumn;    
};

#endif // BALLGRAPHICSITEM_H

#include "ballgraphicsitem.h"
#include <QPainter>
#include <math.h>
#include <QBitmap>


BallGraphicsItem::BallGraphicsItem()
    :QGraphicsObject( ),mBallImage(":sphere.bmp"),
mCurrentRow(0),mCurrentColumn(0)
{
    //masking image to make image transperent
    mBallImage.setMask( 
mBallImage.createMaskFromColor(QColor(255,0,255)));    
}

BallGraphicsItem::~BallGraphicsItem()
{}

QRectF BallGraphicsItem::boundingRect() const
{
    return QRectF(0,0,32,32);
}

void BallGraphicsItem::paint ( QPainter *painter, 
const QStyleOptionGraphicsItem */*option*/, QWidget */*widget*/ )
{
    painter->drawPixmap(0,0,mBallImage, 
mCurrentColumn* 32 ,mCurrentRow*32, 32,32);
}

void BallGraphicsItem::nextFrame()
{
    mCurrentColumn = ++mCurrentColumn % 8;
    if( mCurrentColumn == 0 ) {
        mCurrentRow = ++mCurrentRow %4;
    }
}

void BallGraphicsItem::move()
{    
    setPos( x() + 2, y());
    nextFrame();
}

And my main.cpp file looks like following.
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QTimer>
#include "ballgraphicsitem.h"

int main( int argc, char* argv[] )
{
    QApplication app(argc,argv);

    QGraphicsScene scene( 0, 0, 840, 480 );
    QGraphicsView view(&scene);
    view.setRenderHint(QPainter::Antialiasing);
    view.show();

    BallGraphicsItem* ball = new BallGraphicsItem();
    ball->setPos(10,10);
    scene.addItem( ball );

    QTimer *timer = new QTimer(qApp);
    timer->start(1000/30);
    QObject::connect(timer,SIGNAL(timeout()),ball,SLOT(move()));

    return app.exec();
} 
For above code I am using following image, don't know from where I downloaded image.

Sunday, August 8, 2010

Creating class instance from NSString in iPhone SDK

In my post Creating object dynamically from class name in Qt  I tried to create class instance from string in Qt. I thought if same can be done in iPhone SDK or not.

In iPhone SDK we can create class instance from class name using NSClassFromString function.

My sample code to test  NSClassFromString is as below.

My base class for dummy parsing

@interface Parser : NSObject {
}
-(void) parse;
@end

@implementation Parser
-(void) parse
{
NSLog(@"Parser::parse");
}
@end

Two derived class, which actually just print and dose nothing useful

@interface Parser1 : Parser {
}
@end

@implementation Parser1
-(void) parse
{
NSLog(@"Parser1::parse");
}
@end

@interface Parser2 : Parser {
}
@end

@implementation Parser2

-(void) parse
{
NSLog(@"Parser2::parse");
}
@end

and after dummy code, some useful code which does actual work and test code for testing

-(void) parse:(NSString*) aParserName
{
NSLog(@"trying to parse for %@", aParserName);
Parser* parser = [[NSClassFromString(aParserName) alloc] init];
[parser parse];
[parser release];
}

-(void) test
{
[self parse:@"Parser1"];
[self parse:@"Parser2"];
}

and finally output

2010-08-08 23:23:43.050 Test[2330:207] trying to parse for Parser1
2010-08-08 23:23:43.052 Test[2330:207] Parser1::parse
2010-08-08 23:23:43.054 Test[2330:207] trying to parse for Parser2
2010-08-08 23:23:43.055 Test[2330:207] Parser2::parse

Tuesday, August 3, 2010

Storing custom object and array in NSUserDefaults

In one of my recent program I required to save application state. Easiest solution to save application state in iPhone is to use NSUserDefaults.

In my application I was creating some custom object and array which store custom object and I required to save those in NSUserDefaults

Initially I struggled with this but finally got solution, so though to share it.

First of all, if you want to save your custom object in NSUserDefaults than it should follow NSCoding protocol.

So your custom class should implement NSCoding protocol like following.

@interface MyClass : NSObject <NSCoding>{
BOOL someFlag;
}

@end

#import "MyClass.h"

@implementation MyClass

- (void) encodeWithCoder:(NSCoder *)coder 
    //uncomment following if super class is following NSCoding protocol
    //[super encodeWithCoder:coder];
    [coder encodeBool:someFlag forKey:@"SomeFlag"];
}

- (id) initWithCoder:(NSCoder *)coder 
{
    //uncomment following if super class is following NSCoding protocol
    //self = [super initWithCoder:coder];
    self = [super init];
    if( self
    {         
        someFlag = [coder decodeBoolForKey:@"SomeFlag"];
    }    
    return self;
}

@end

Now to store and restore above defined custom class in NSUserDefaults, we can use following code as shown in saveState and restoreState function.

#import "MyClass.h"

@interface Controller : NSObject {
    MyClass* myClass;
    NSMutableArray* myClassArray
    int currentState;
}

- (void) saveState;

- (void) restoreState;

@end

#import "Controller.h"

@implementation Controller

- (void) saveState 
{    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    NSData* myClassData = [NSKeyedArchiver archivedDataWithRootObject:myClass];
    [defaults setObject:myClassData forKey:@"MyClass"];
    
    NSData* myClassArrayData = [NSKeyedArchiver archivedDataWithRootObject:myClassArray];
    [defaults setObject:myClassArrayData forKey:@"MyClassArray"];
    
    [defaults setInteger:currentState forKey:@"CurrentState"];
}

- (void) restoreState 
{    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    NSData* myClassData = [defaults objectForKey:@"MyClass"];
    myClass = [NSKeyedUnarchiver unarchiveObjectWithData:myClassData];
    
    NSData* myClassArrayData = [defaults objectForKey:@"MyClassArray"];    
    NSArray *savedMyClassArray = [NSKeyedUnarchiver unarchiveObjectWithData:myClassArrayData];
    if( savedMyClassArray != nil
        myClassArray = [[NSMutableArray alloc] initWithArray:savedMyClassArray];
   else
myClassArray =  [[NSMutableArray alloc] init];
    
    currentState = [defaults integerForKey:@"CurrentState"];
}

@end