Friday, April 11, 2008

Create and manipulate SQLite databases using Python

SQLite is a small,embedable relational database management System which is almost ACID compliant. It is 
heavily used in the Free/Open source world and by people like Apple. It is deployed in Firefox, Mac OS X, Skype, IPhone 
and Symbian phones. So when you use your Nokia phone (a symbian based phone), remember that you are a sqlite user. With a size less than 500k, it is one of the small but beautiful softwares which is platform independent.

Now let’s play with sqlite3 in Linux..

To create a sqlite database (here test.db), run the sqlite3 command in terminal.

sqlite3 test.db “create table t1(t1key INTEGER PRIMARY KEY, data TEXT, num double, timeEnter Date);”

now we have the test.db database in the present working directory.

To see the table details in a given database, execute this command.

sqlite3 test.db “.table”
t1

Now let’s populate the database..
sqlite3 test.db “insert into t1(data,num) values(’this is a sample data’,3);”

Ok, now let’s use python’s sqlite bindings to manipulate the database and the data in it..

>>> import sqlite
>>> con = sqlite.connect(’test.db’)
>>> cur = con.cursor()
>>> cur.execute(’insert into t1(data,num) values(“this is again a test”,1)’)
>>> cur.commit()
>>> cur.execute(’SELECT * from t1′)
>>> print cur.fetchall()
[(1, 'this is a sample data', 3.0, None), (2, 'this is again a test', 1.0, None)]

>> cur.execute(’select * from t1 where num=3′)
>>result=cur.fetchall()[0]
>>print result
(1, ‘this is a sample data’, 3.0, None)
>> print result[1]
this is a sample data

Well, if you think it is not enough to use sqlite in your project, refer this SQLite tutorial : http://souptonuts.sourceforge.net/readme_sqlite_tutorial.html

Posted by maxinbjohn at 05:45:50 | Permalink | No Comments »

Tuesday, April 8, 2008

ChickenWarrior : An epic game development in JavaME using Gnu/Linux and NetBeans Mobility Pack

Today, I am releasing the beta version of my new game, ChickenWarrior. This game is  in J2ME, intented for the Mobile Phone users. I have tested this game in Motorolla MotoRokr, Sony Ericsson K700i and Sony Ericsson K300i and it works fairly well Cool

The theme of this game is a chicken desperate to save it’s eggs falling from the sky at night.  Ten eggs will fall from the Sky and the chicken will have to save it .

The NetBeans IDE 6.0 with Mobility pack was used to create this game. The Game Designing part of Mobility pack helps us to easily create the Sprite objects , TiledLayer objects and other game objects  which is very complex to code otherwise.

For game play, we can use the left and right keys to move the chicken left and right. The up key will terminate the game if we wish to terminate the game in the middle.

Source Code :
1) ChickenWarrior.java

/**
  *  @author Maxin B. John <maxinbjohn@gmail.com>
  *
  */

package com;

import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;

/**
 * @author maxin.john
 */
public class ChickenWarrior extends MIDlet implements CommandListener {

    private boolean midletPaused = false;
    private Player player ;
    private Display d;
    //<editor-fold defaultstate=”collapsed” desc=” Generated Fields “>//GEN-BEGIN:|fields|0|
    private Command exitCommand;
    private Command playCommand;
    private Form form;
    private StringItem stringItem;
    //</editor-fold>//GEN-END:|fields|0|

    /**
     * The HelloMIDlet constructor.
     */
    public ChickenWarrior() {
     
    }

    //<editor-fold defaultstate=”collapsed” desc=” Generated Methods “>//GEN-BEGIN:|methods|0|
    //</editor-fold>//GEN-END:|methods|0|

    //<editor-fold defaultstate=”collapsed” desc=” Generated Method: initialize “>//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initilizes the application.
     * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
    //</editor-fold>//GEN-END:|0-initialize|2|

    //<editor-fold defaultstate=”collapsed” desc=” Generated Method: startMIDlet “>//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {
       
        switchDisplayable(null, getForm());
       // show();
    }
   
    void show() {
       
        System.out.println(“Midlet running \n”);
        MyGameCanvas dgn = new MyGameCanvas();
        dgn.mid= this;
        new Thread(dgn).start();
        d = Display.getDisplay(this);
        d.setCurrent(dgn);

    }
   
    //<editor-fold defaultstate=”collapsed” desc=” Generated Method: resumeMIDlet “>//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {
      
    }

    //<editor-fold defaultstate=”collapsed” desc=” Generated Method: switchDisplayable “>//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
     * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }

    //<editor-fold defaultstate=”collapsed” desc=” Generated Method: commandAction for Displayables “>//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a particular displayable.
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|19-preAction
            if (command == exitCommand) {//GEN-END:|7-commandAction|1|19-preAction
                // write pre-action user code here
                exitMIDlet();//GEN-LINE:|7-commandAction|2|19-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|7-postCommandAction
            if (command == playCommand) {//GEN-END:|7-commandAction|1|19-preAction
                // write pre-action user code here
                show();//GEN-LINE:|7-commandAction|2|19-postAction
                // write post-action user code here
            }//GE
        }//GEN-END:|7-commandAction|3|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|4|
    //</editor-fold>//GEN-END:|7-commandAction|4|

    //<editor-fold defaultstate=”collapsed” desc=” Generated Getter: exitCommand “>//GEN-BEGIN:|18-getter|0|18-preInit
    /**
     * Returns an initiliazed instance of exitCommand component.
     * @return the initialized component instance
     */
    public Command getExitCommand() {
        if (exitCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            exitCommand = new Command(“Exit”, Command.EXIT, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return exitCommand;
    }
   
   
    public Command getPlayCommand() {
        if (playCommand == null) {//GEN-END:|18-getter|0|18-preInit
            // write pre-init user code here
            playCommand = new Command(“Play”, Command.OK, 0);//GEN-LINE:|18-getter|1|18-postInit
            // write post-init user code here
        }//GEN-BEGIN:|18-getter|2|
        return playCommand;
    }
   
    //</editor-fold>//GEN-END:|18-getter|2|

    //<editor-fold defaultstate=”collapsed” desc=” Generated Getter: form “>//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initiliazed instance of form component.
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            form = new Form(“       Save the Eggs! “, new Item[] { getStringItem() });//GEN-BEGIN:|14-getter|1|14-postInit
            form.addCommand(getExitCommand());
            form.addCommand(getPlayCommand());
            form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return form;
    }
    //</editor-fold>//GEN-END:|14-getter|2|

    //<editor-fold defaultstate=”collapsed” desc=” Generated Getter: stringItem “>//GEN-BEGIN:|16-getter|0|16-preInit
    /**
     * Returns an initiliazed instance of stringItem component.
     * @return the initialized component instance
     */
    public StringItem getStringItem() {
        if (stringItem == null) {//GEN-END:|16-getter|0|16-preInit
            // write pre-init user code here
            stringItem = new StringItem(“A Chicken Desperate to save it’s eggs..”, “”);//GEN-LINE:|16-getter|1|16-postInit
            // write post-init user code here
        }//GEN-BEGIN:|16-getter|2|
        return stringItem;
    }
   
    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay () {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable (null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet ();
        } else {
            initialize ();
           // startMIDlet ();
           try{
           player = Manager.createPlayer(getClass().getResourceAsStream(“/Arcade.mid”), “audio/midi”);
           player.setLoopCount(-1);
           player.start();
           }catch(MediaException me)
    {
    }catch(java.io.IOException e)
    {
   
         }
         System.out.println(“Before start midlet\n”);
         startMIDlet ();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
         try{
        player.stop();
    }catch (MediaException me){
    }
       
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
        try{
        player.stop();
    }catch (MediaException me){
    }
    }
    }

############################################################

2) MyGameCanvas.java

/**
  *  @author Maxin B. John <maxinbjohn@gmail.com>
  *
  */

package com;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.midlet.*;

/**
 *
 * @author Maxin B. John <maxinbjohn@gmail.com>
 *
 */
public class MyGameCanvas  extends GameCanvas implements Runnable{
     private static final int SPEED = 5;
     private LayerManager lm;
     //private byte lastDirection = -1;
     private SpriteAnimationTask spriteEggAnimator;
     private SpriteAnimationTask spriteChickenAnimator;
     private EggFall EggRandomMovement;
     private boolean interrupted;
     private Timer timer;
     private MyGameDesign gameDesign;
     private int eggNumber;
     private Sprite Egg;
     private Sprite Chicken;
     public MIDlet mid;
     public int canvasHeight;
     public int canvasWidth;
    
    
     public MyGameCanvas(){
            super(true);
            this.eggNumber=0;
            this.setFullScreenMode(true);
            this.init();
        }
    
    public void stop() {
        this.interrupted = true;
    }
     private void init()  {
         try{
         System.out.println(“In init \n”);
         this.timer = new Timer();
         this.gameDesign= new MyGameDesign();
         this.Egg = gameDesign.getEgg();
         this.Chicken = gameDesign.getMyChicken();
         this.Egg.defineReferencePixel(8, 8);
         this.Chicken.defineReferencePixel(8, 8);
         this.canvasHeight= this.getHeight();
         this.canvasWidth = this.getWidth();
         this.spriteEggAnimator = new SpriteAnimationTask(this.Egg, false);
         this.spriteChickenAnimator = new SpriteAnimationTask(this.Chicken, false);
         this.timer.scheduleAtFixedRate(this.spriteEggAnimator, 0, gameDesign.Eggseq001Delay);
         this.timer.scheduleAtFixedRate(this.spriteChickenAnimator, 0, gameDesign.MyChickenseq001Delay);
         this.lm = new LayerManager();
         gameDesign.updateLayerManagerForMySky(lm);
         this.EggRandomMovement = new EggFall(this, Egg);
     
         this.EggRandomMovement.setSequences(
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE,
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE,
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE,
            gameDesign.MyChickenseq001, Sprite.TRANS_NONE
            );
      
        (new Thread(EggRandomMovement)).start();
         }catch (IOException io){}
         }
    
     public boolean setEggNo(){
         this.eggNumber+=1;
         return true;
     }
    
     public int getEggNo(){
         return this.eggNumber;
       }

      /**
     * Check if sprite collides with the Chicken object
     *
     * @param sprite the sprite checked for collision with other layers
     * @return true is sprite does collide, false otherwise
     */
    public boolean spriteCollides(Sprite sprite) {
     return sprite.collidesWith(this.Chicken, true);
       }
    
     public void run(){
           System.out.println(“Inside the run \n”);
           Graphics g = getGraphics();
           while (!this.interrupted) {
            //check for user input
            int keyState = getKeyStates();
            if ((keyState & LEFT_PRESSED) != 0) {
                this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
                this.Chicken.setTransform(Sprite.TRANS_MIRROR);
                this.spriteChickenAnimator.backward();
                this.Chicken.move(-SPEED, 0);
                System.out.println(“Left key pressed \n”);
              
            }
            if ((keyState & RIGHT_PRESSED) != 0) {
                this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
                this.Chicken.setTransform(Sprite.TRANS_MIRROR);
                this.Chicken.move(SPEED, 0);
                System.out.println(“Right key pressed \n”);
               
           
            }
            if ((keyState & UP_PRESSED) != 0) {
                this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
                this.Chicken.setTransform(Sprite.TRANS_MIRROR);
                System.gc();
                try{
                   this.mid.notifyDestroyed();
                  }catch(Exception ex){
                
              }
            } 
                       
            this.Chicken.setFrameSequence(gameDesign.MyChickenseq001);
            this.spriteChickenAnimator.setMoving(true);
            this.lm.paint(g, 0, 0);
            flushGraphics(0, 0, this.getWidth(), this.getHeight());
             try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
         }
     }
    
/**
     * Animates a sprite.
     */
  private class SpriteAnimationTask extends TimerTask {

        private boolean moving = false;
        private boolean forward = true;
        private Sprite sprite;

        public SpriteAnimationTask(Sprite sprite, boolean forward) {
            this.sprite = sprite;
            this.forward = forward;
        }

        public void run() {
            if (!this.moving) {
                return;
            }
           
            if (this.forward) {
                this.sprite.nextFrame();
            } else {
                this.sprite.prevFrame();
            }
        }

        public void forward() {
            this.forward = true;
            this.moving = true;
        }

        public void backward() {
            this.forward = false;
            this.moving = true;
        }

        public void setMoving(boolean isMoving) {
            this.moving = isMoving;
        }
    }
}

##############################################################

3) EggFall.java

package com;

/**
 *  @author Maxin B. John <maxinbjohn@gmail.com>
 */

import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Random;

public class EggFall implements Runnable,CommandListener{

    private static final int SPEED = 3;
    private MyGameCanvas canvas;
    private Sprite sprite;
   
    private byte previousDirection = GameCanvas.DOWN;
    private byte direction = GameCanvas.DOWN;
    private boolean interrupted;
    private int[] downSeq;
    private int downTrans;
    private int[] upSeq;
    private int upTrans;
    private int[] leftSeq;
    private int leftTrans;
    private int[] rightSeq;
    private int rightTrans;
    private int finalScore=0;
    private Command exitCommand;
    private Form form;
    private StringItem stringItem;
    private Display dsp;
   
 
    public EggFall(MyGameCanvas canvas, Sprite sprite) {
        this.canvas = canvas;
        this.sprite = sprite;
    }
  
    /////////////////////////////////////////////////////////
    public void commandAction(Command command, Displayable displayable){
        
   if (command == exitCommand) {
             exitMIDlet();
             System.out.println(“Exit Command \n”); 
            }
   
      }
   
    public Command getExitCommand() {
      
        if (exitCommand == null) {
           exitCommand = new Command(“Exit”, Command.EXIT, 0);
           }
        return exitCommand;
    }
   

      public void exitMIDlet() {
            this.canvas.mid.notifyDestroyed();
    
    }
     
    

     
     /////////////////////////////////////////////////////////
    public void setSequences(int[] downSeq, int downTrans, int[] upSeq, int upTrans, int[] leftSeq, int leftTrans, int[] rightSeq, int rightTrans) {
        this.downSeq = downSeq;
        this.downTrans = downTrans;
        this.upSeq = upSeq;
        this.upTrans = upTrans;
        this.leftSeq = leftSeq;
        this.leftTrans = leftTrans;
        this.rightSeq = rightSeq;
        this.rightTrans = rightTrans;
    }

    public void stop() {
        this.interrupted = true;
    }
   
   public int getRandomNumber(){
        int intervalMin = 10;
        int intervalMax = 100;
        int halfInterval = (intervalMin - intervalMax) / 2;
        int integerDisc = Integer.MAX_VALUE / halfInterval;
        Random r = new Random(System.currentTimeMillis());
        int randomNumber = r.nextInt();
        randomNumber = randomNumber / integerDisc;
        randomNumber = randomNumber + halfInterval;
        randomNumber = randomNumber <0 ? -1*randomNumber: randomNumber;
       
        return randomNumber;
    }
   
    public void run() {
        while (!this.interrupted) {
            if (this.direction == GameCanvas.DOWN) {
                if (this.previousDirection != this.direction) {
                    this.sprite.setFrameSequence(this.downSeq);
                    this.sprite.setTransform(this.downTrans);
                    this.previousDirection = this.direction;
                }
                this.sprite.move(0, SPEED);
                if(this.sprite.getY()> this.canvas.canvasHeight && this.sprite.isVisible()){
                    System.out.println(“This egg got broken .. you loose one egg\n”);
                    this.sprite.setVisible(false);
                    if (this.canvas.getEggNo() >= 10){
                        System.out.println(“Game over You scored ..\n”+ this.finalScore);
                        this.canvas.stop();
                        this.stop();
                        this.canvas.setFullScreenMode(false);
                        this.canvas.setCommandListener(this);
                        this.canvas.addCommand(this.getExitCommand());
                       
                     }
                    else{
                        this.canvas.setEggNo();
                        this.sprite.setPosition(this.getRandomNumber(), 0);
                        this.sprite.setVisible(true);
                         System.out.println(this.canvas.getEggNo());
                    }
                    }
               
                if (this.canvas.spriteCollides(this.sprite)) {
                    this.sprite.setVisible(false);
                    this.finalScore += 1;
                    System.out.println(“You secured your egg!scored”+this.finalScore+”\n”);
                   
                     if (this.canvas.getEggNo() >= 10){
                        System.out.println(“Game over \n”+ this.finalScore);
                        this.canvas.stop();
                        this.stop();
                        this.canvas.setFullScreenMode(false);
                        this.canvas.setCommandListener(this);
                        this.canvas.addCommand(this.getExitCommand());
                    }
                    else{
                        this.canvas.setEggNo();
                        this.sprite.setPosition(this.getRandomNumber(), 0);
                        this.sprite.setVisible(true);
                         System.out.println(this.canvas.getEggNo());
                    }
                    continue;
                }
             }
            try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

########################################################

4) MyGameDesign.java

/**
  * Maxin B. John <maxinbjohn@gmail.com>
  */

package com;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import java.io.IOException;
import java.util.Random;

/**
 * @author maxin.john
 */
public class MyGameDesign {

    //<editor-fold defaultstate=”collapsed” desc=” Generated Fields “>                     
    private Image eggs;
    private Sprite MyEgg;
    public int MyEggseq001Delay = 200;
    public int[] MyEggseq001 = {68, 68, 68, 67, 67};
    private TiledLayer MyLayer;
    private Sprite Chicken;
    public int Chickenseq001Delay = 100;
    public int[] Chickenseq001 = {84, 85, 86, 87, 84};
    private Image chickens;
    private TiledLayer ChicLayer;
    private Sprite Egg;
    public int Eggseq001Delay = 200;
    public int[] Eggseq001 = {69, 69, 69, 69, 69};
    private Sprite MyChicken;
    public int MyChickenseq001Delay = 200;
    public int[] MyChickenseq001 = {0, 0, 5, 16, 21};
    //</editor-fold>                   
   /* public int canvasHeight=100;
    public int canvasWidth;*/
    //<editor-fold defaultstate=”collapsed” desc=” Generated Methods “>                      
    //</editor-fold>                    

    

                     
    
    public void updateLayerManagerForMySky(LayerManager lm) throws java.io.IOException {                                             
        // write pre-update user code here
        int intervalMin = 10;
        int intervalMax = 100;
        int halfInterval = (intervalMin - intervalMax) / 2;
        int integerDisc = Integer.MAX_VALUE / halfInterval;
        Random r = new Random(System.currentTimeMillis());
        int randomNumber = r.nextInt();
        randomNumber = randomNumber / integerDisc;
        randomNumber = randomNumber + halfInterval;
        randomNumber = randomNumber <0 ? -1*randomNumber: randomNumber;
        getEgg().setPosition(randomNumber, 0);
        getMyChicken().setPosition(10,100);
        getMyChicken().setVisible(true);
        getEgg().setVisible(true);
        lm.append(getEgg());
        lm.append(getMyChicken());
        getChicLayer().setPosition(0, 0);
        getChicLayer().setVisible(true);
        lm.append(getChicLayer());
                                              
        // write post-update user code here
    }                                   
                                 
 

    public Image getChickens() throws java.io.IOException {                                
        if (chickens == null) {                              
            // write pre-init user code here
            chickens = Image.createImage(“/chickens.png”);                                 
        }                               
        // write post-init user code here
        return this.chickens;                       
    }
                     

    public TiledLayer getChicLayer() throws java.io.IOException {                                
        if (ChicLayer == null) {                              
            // write pre-init user code here
            ChicLayer = new TiledLayer(20, 20, getChickens(), 16, 16);                                
            int[][] tiles = {
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52 },
                { 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52 },
                { 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52 }
            };                              
            // write mid-init user code here
            for (int row = 0; row < 20; row++) {                                 
                for (int col = 0; col < 20; col++) {
                    ChicLayer.setCell(col, row, tiles[row][col]);
                }
            }
        }                               
        // write post-init user code here
        return ChicLayer;                       
    }
                     

    public Sprite getEgg() throws java.io.IOException {                                  
        if (Egg == null) {                                
            // write pre-init user code here
            Egg = new Sprite(getChickens(), 16, 16);                                   
            Egg.setFrameSequence(Eggseq001);                                 
            // write post-init user code here
        }                        
        return Egg;
    }
                      

    public Sprite getMyChicken() throws java.io.IOException {                                  
        if (MyChicken == null) {                                
            // write pre-init user code here
            MyChicken = new Sprite(getChickens(), 16, 16);                                   
            MyChicken.setFrameSequence(MyChickenseq001);                                 
            // write post-init user code here
        }                        
        return MyChicken;
    }
                      

}

#############################################################

The resources used in this project, chickens.png


The complete sourcecode along with ChickenWarrior.jad and ChickenWarrior.jar can be downloaded from
http://pysportslive.googlecode.com/files/ChickenWarrior.zip

Wow…. Now I got my own game in My mobile.. So from now on , I can play my games when I get bored… :)

Posted by maxinbjohn at 09:13:08 | Permalink | No Comments »

Friday, April 4, 2008

Bluejacking in Linux

It’s 6.30 in the afternoon. You are walking out of the Forum in Bengaluru ( New name of Bangalore).  Suddenly your  bluetooth enabled  phone  cries with a strange tone…  You takes it out of your pocket and finds that it’s just vcard sent by some other anonymous bluetooth device.. You opens the vcard and it says..
 ”You have been bluejacked !”…  and now your blood turns cold…

Relax.. real bluejacking wont’ do anything to your phone.. It is just another prank.. to pump up some adrenaline to your blood stream.

Bluejacking is the sending of unsolicited messages over Bluetooth to Bluetooth-enabled devices such as mobile phones, PDAsby sending a vCard which typically contains a message in the name field  to another bluetooth enabled device via the Obex protocol.

The http://www.bluejackq.com/ has some interesting information regarding bluejacking.

We can do Bluejacking in Linux using ussp-push ,  an OBEX object pusher for Linux, using the BlueZ BlueTooth stack. If you have the bluetooth dongle in your machine(Laptop), you can bluejack your friends (certainly don’t do it on strangers, as it may hurt their feelings..).

Download ussp-push from http://freshmeat.net/projects/ussp-push/ and compile it. It depends on the Bluez library, openobex library and usblib libraries. Make sure you satisfy all these dependencies. For that , install the bluez-devel, openobex-devel and libusb-devel packages.

After compiling it, run it as

./ussp-push $MAC@$OCHAN $FILENAME $FILENAME
here MAC is the address of the bluetooth device obtained by the

hcitool scan

and OCHAN can be 1, but if it is not given, the ussp-push uses the sdp protocol to find the supported channel on the device.FILENAME is the name of the file to be sent to the remote phone.

Well, if you really want to see the wild side of ussp-push, see this shell program. http://archives.neohapsis.com/archives/fulldisclosure/2007-01/att-0435/obex_dos.sh

It successfully performed a DOS attack on my friend Jibin’s phone (done with his consent, just to check whether it works on a Sony Ericsson K700i)

Posted by maxinbjohn at 05:49:22 | Permalink | No Comments »

Wednesday, March 12, 2008

Creating your own themes for Sony Ericsson K300i in Linux

First of all, Get some funny tux pictures from http://tux.crystalxp.net/en.cat.16.3.12.html.

Now get the tux.thm(or any other theme) from http://www.esato.com/logos/colour/k300themes.php?p=42

Ok , let’s check the theme file.

file tux.thm
tux.thm: POSIX tar archive
Oh.. It’s just a tar file ..Now Let’s untar it:

tar xvf tux.thm

background.png highlightSmall.png softkeys.png tabUnselected.png
desktop.png popupHighlight.png standby.png Theme.xml
doubleTitle.png popup.png status.png titleSmall.png
highlight.png popupTitle.png tabSelected.png

These files has a pre-defined sizes . It will be better to keep the size of
each image files as it will look good in the mobile.

Let’s peek into the Theme.xml file and see it’s structure.

<?xml version=”1.0″?>

<Sony_Ericsson_theme version=”3.0″>

<Author_firstname value=”Maxin”/>

<Author_url value=”153EE6″/>

<Background Color=”0xbbf7fb”/>

<Background_image Source=”background.png”/>

<Desktop Color=”0×153ee6″/>

<Desktop_image Source=”desktop.png”/>

<Desktop_title_text Color=”0xbbf7fb”/>

<Highlight_text Color=”0xbbf7fb”/>

<Highlight Color=”0×153ee6″/>

<Highlight_image Source=”highlight.png”/>

<Highlight_small_image Source=”highlightSmall.png”/>

<Popup_text Color=”0xbbf7fb”/>

<Popup Color=”0×153ee6″/>

<Popup_frame Color=”0xbbf7fb”/>

<Popup_highlight_text Color=”0×000040″/>

<Popup_highlight Color=”0xbbf7fb”/>

<Popup_highlight_image Source=”popupHighlight.png”/>

<Popup_image Source=”popup.png”/>

<Popup_scrollbar_background Color=”0×3cacff”/>

<Popup_scrollbar_slider Color=”0xbbf7fb”/>

<Popup_title_text Color=”0×000040″/>

<Popup_title Color=”0xbbf7fb”/>

<Popup_title_image Source=”popupTitle.png”/>

<Scrollbar_background Color=”0xbbf7fb”/>

<Scrollbar_slider Color=”0×0018b1″/>

<Softkeys_text Color=”0xbbf7fb”/>

<Softkeys Color=”0×153ee6″/>

<Softkeys_image Source=”softkeys.png”/>

<Standby_image Source=”standby.png”/>

<Standby_operatorname_text Color=”0xffffff”/>

<Standby_operatorname_outline Color=”0×000040″/>

<Standby_softkey_image Source=”softkeys.png”/>

<Standby_time Color=”0xffffff”/>

<Standby_time_outline Color=”0×000040″/>

<Standby_statusbar_image Source=”status.png”/>

<Tab_text Color=”0xbbf7fb”/>

<Tab Color=”0×153ee6″/>

<Tab_image Source=”doubleTitle.png”/>

<Tab_selected_image Source=”tabSelected.png”/>

<Tab_unselected_image Source=”tabUnselected.png”/>

<Text Color=”0×000040″/>

<Title_image Source=”doubleTitle.png”/>

<Title_small_image Source=”titleSmall.png”/>

<Title_text Color=”0xbbf7fb”/>

<Title Color=”0×153ee6″/>

<Wapbrowser_underline Color=”0×0000ff”/>

<Wapbrowser_tableborder Color=”0×0000ff”/>

</Sony_Ericsson_theme>

If you need to rename some of your files, then never forget to make change in this XML file too.. Otherwise, just replace the required files and don’t touch the XML file.. that’s safe if you are new to XML format :)

Now open the png image in GIMP and resize the image as that of the equivalent image in the theme.

Here the desktop.png file should be of size 128×110. You can resize your image in gimp by..

Image -> Scale Image ->
Then give Width as 128 and Height as 110

or just use the convert file if you want to write a shell script for the theme creation

convert -resize 128×110 source.png destination.png

This will take care of your resizing requirements :)

After that save that image as desktop.png .. Go on modifying these files till
you are satisfied.

Now create your theme by issuing this command.

tar cvf tux.thm *

Now let’s transfer the theme to K300i using the USB cable connected to our Gnu/Linux Machine.

obexftp –tty /dev/ttyUSB0 -p ./tux.thm Themes/tux.thm
Connecting…done
Sending “./tux.thm”…|done
Sending “Themes/tux.thm”… failed: Themes/tux.thm
(Don’t care the failed message.. )

Disconnecting…done

Save the theme in your mobile and apply it.. Now you have the cool tux theme in your mobile.

Posted by maxinbjohn at 05:48:53 | Permalink | No Comments »

Tuesday, March 4, 2008

Sending Linus.mp3 to K300i from Linux - The obexftp way

One of the most difficult things that I faced when connecting my Sony Ericsson K300i to the Gnu/Linux box was the difficulty in sending and receiving data from Linux to Mobile and vice versa. Today, I have managed to overcome that difficulty too.. Now my mobile is completely useful… (Atleast from the Gnu/Linux side :) )

First I need the obex installation in my system (Fedora core 6)
For that
yum install openobex

After the installation, connect the mobile phone using usb cable. Now dmesg shows that we have a new device called ‘/dev/ttyUSB0′.

Here are the following steps:

obexftp –tty /dev/ttyUSB0 -c . -l

This gives the following output..

Connecting…done
Sending “.”… failed: .
Receiving “(null)”… <?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE folder-listing SYSTEM “obex-folder-listing.dtd”>
<!–
XML Coder, May 24 2005, 21:06:32, (C) 2001 Sony Ericsson Mobile Communications AB
–>
<folder-listing version=”1.0″><folder name=”Pictures”/>
<folder name=”Sounds”/>
<folder name=”Themes”/>
<folder name=”Videos”/>
<folder name=”Other”/>
</folder-listing>
done
Disconnecting…done

Then download the Linus torvald’s voice

wget http://www.paul.sladen.org/pronunciation/torvalds-says-linux.mp3

Now push the mp3 to the mobile phone

obexftp –tty /dev/ttyUSB0 -p ./torvalds-says-linux.mp3 Sounds/linux.mp3

After about 5 seconds, your phone will prompt you to save the mp3 to phone memory. Now play the torvalds-says-linux.mp3
 
Now you have the voice of Linus in your mobile….. Cheers.. Wink

Posted by maxinbjohn at 08:58:25 | Permalink | No Comments »

Friday, February 22, 2008

Sony Ericsson K300i AT commands in Linux

I am always interested in using unconventional methods to control the mobile phone using linux. I found that the AT commands has immense potential to control the functioning of my K300i mobile. We can make phone calls, invoke apps and java applications in the phone, change the profile , enable or disable certain features like silent mode, read & send sms…… I have downloaded the AT commands list from http://developer.sonyericsson.com/getDocument.do?docId=65054 Now to send the AT commands, I need a terminal connection to phone. I love minicom, best terminal emulator in Linux. After connecting the k300i phone to the usb of the system using it’s usb cable, dmesg : usb 2-2: new full speed USB device using uhci_hcd and address 2 usb 2-2: configuration #1 chosen from 1 choice usbcore: registered new driver usbserial drivers/usb/serial/usb-serial.c: USB Serial support registered for generic usbcore: registered new driver usbserial_generic drivers/usb/serial/usb-serial.c: USB Serial Driver core drivers/usb/serial/usb-serial.c: USB Serial support registered for pl2303 pl2303 2-2:1.0: pl2303 converter detected usb 2-2: pl2303 converter now attached to ttyUSB0 usbcore: registered new driver pl2303 drivers/usb/serial/pl2303.c: Prolific PL2303 USB to serial adaptor driver Hmm .. the serial device is ttyUSB0… Then this should be the serial port setup in minicom : /dev/ttyUSB0 57600 8N1 Ok then I have configured minicom and logged on to K300i.. to check whether it is success or not , ATI K300 series OK It is OK.. or more than ok :).. the AT commads are working :) Then some more AT commands to test know more about it… Modifying the profile to enable alerts : AT+CVIB? +CVIB: 16 OK AT+CVIB=? +CVIB: (0-1,16) OK AT+CVIB=1 OK Profile Updated: HOME Modified … splashed on screen :) Showing the default language AT*ELAN? *ELAN: “en” Executing Java Apps T*EJAVA=? *EJAVA: 1 *EJAVA: 2,(1-4294967295) *EJAVA: 3,120 *EJAVA: 4,(1-4294967295) 0 Run a java application. The search path to the application must be provided in . 1 List installed java applications. No value on needed. 2 Delete a java application. The object id of the application must be provided in . 3 Install a java application. The search path to the application must be provided in . 4 Run an installed java application. The object id of the application must be provided in . *EJAVA: “Alert”,”Sun Microsystems, Inc.”,”1.0″,524298,10 *EJAVA: “Audio Player”,”Sun Microsystems, Inc.”,”2.0″,65542,6 *EJAVA: “Bouncing Ball”,”Sun Microsystems, Inc.”,”2.0″,196614,6 *EJAVA: “ChoiceGroup”,”Sun Microsystems, Inc.”,”1.0″,458762,10 *EJAVA: “Colors”,”Sun Microsystems, Inc.”,”2.0″,65541,5 *EJAVA: “Converter”,”Sony Ericsson”,”2.1.6″,65537,1 *EJAVA: “CustomItem”,”Sun Microsystems, Inc.”,”1.0″,65546,10 *EJAVA: “Darts”,”Sony Ericsson”,”0.0.3″,65538,2 *EJAVA: “Datagram Demo”,”Sun Microsystems, Inc.”,”1.0″,131083,11 *EJAVA: “DateField”,”Sun Microsystems, Inc.”,”1.0″,196618,10 *EJAVA: “FiveStones”,”Sony Ericsson Mobile Communications AB”,”1.2″,65539,3 *EJAVA: “FontTestlet”,”Sun Microsystems, Inc.”,”2.0″,327685,5 *EJAVA: “Gauge”,”Sun Microsystems, Inc.”,”1.0″,589834,10 *EJAVA: “HelloMIDlet”,”Vendor”,”1.0″,65548,12 *EJAVA: “Http”,”Sun Microsystems, Inc.”,”2.0″,393221,5 *EJAVA: “List”,”Sun Microsystems, Inc.”,”1.0″,393226,10 *EJAVA: “ManyBalls”,”Sun Microsystems, Inc.”,”2.0″,131077,5 *EJAVA: “Mascot Capsule V3 Demo”,”Hi Corp.”,”2.0″,65543,7 *EJAVA: “Mix Demo”,”Sun Microsystems, Inc.”,”2.0″,131078,6 *EJAVA: “PhotoAlbum”,”Sun Microsystems, Inc.”,”2.0″,65545,9 *EJAVA: “Properties”,”Sun Microsystems, Inc.”,”2.0″,458757,5 *EJAVA: “PushPuzzle”,”Sun Microsystems, Inc.”,”2.0″,131076,4 *EJAVA: “Socket Demo”,”Sun Microsystems, Inc.”,”1.0″,65547,11 *EJAVA: “Start”,”Sony Ericsson Mobile Communications AB”,”2.1.4″,65544,8 *EJAVA: “Stock”,”Sun Microsystems, Inc.”,”2.0″,262149,5 *EJAVA: “StringItem”,”Sun Microsystems, Inc.”,”1.0″,655370,10 *EJAVA: “TextBox”,”Sun Microsystems, Inc.”,”1.0″,327690,10 *EJAVA: “TextField”,”Sun Microsystems, Inc.”,”1.0″,262154,10 *EJAVA: “Ticker”,”Sun Microsystems, Inc.”,”1.0″,131082,10 *EJAVA: “Tickets”,”Sun Microsystems, Inc.”,”2.0″,196613,5 *EJAVA: “TilePuzzle”,”Sun Microsystems, Inc.”,”2.0″,65540,4 *EJAVA: “WormGame”,”Sun Microsystems, Inc.”,”2.0″,196612,4 To execute the Darts game in the mobile , type: AT*EJAVA=4,65538 and viola, I got to see the Darts game start executing in the phone :)
Posted by maxinbjohn at 05:24:00 | Permalink | No Comments »

Wednesday, January 16, 2008

decompiling c and c++ programs in Linux

Suppose you are working on one project and suddenly due to hdd crash you lost all your source code and suppose that you didn’t use any source code management softwares such as subversion or cvs, and all that left is the compiled binary of your project , then what will you do ??
Decompiling is the process of generating the source code out of running binaries (eg. file.c out of a.out) .  I have used the mocha decompiler for my previous java project when the customer just provided us the class files instead of java source code. We decompiled the classes and generated the source code out of it and studied the structure and logical flow of the project. I must say it was a tedious project.
Now , say for example, you have the source code and then you compiled it and later you will extract the source code from the binary , then how the two codes will differ, just let us see..
For this purpose, I am using the well known decompiler boomerang . It is available for both windows and linux. For linux we need to download  it from http://boomerang.sourceforge.net/. As it depends on a seperate libgc, download that too from the same site and copy it to the /lib directory. Then again it depends on the libexpat .. just create a link to the existing expat library in /lib and it won’t complain again :)

My C program to test decompilation using boomerang is
/**************************************************/
/* Program to check the characteristics of malloc */
/*                               */
/**************************************************/

#include <stdio.h>
#include <stdlib.h>
int *fun(void)
{
    int *a;
    a = (int *) malloc(sizeof(int));
    free(a);
    return a;
}

int main()
{
    int *j;
    j = fun();
    *j = 5;
    printf(“%d\n”, *j);
    return 0;
}

Then compile it as
cc test.c  , now we got the much awaited a.out

then run the boomerang on a.out. You will see something like
./boomerang a.out
Boomerang alpha 0.3 13/June/2006
setting up transformers…
loading…
Warning: dynamic symbol table hack used!
decoding entry point…
decoding anything undecoded…
finishing decode…
found 2 procs
decompiling…
decompiling entry point main
 considering main
  considering fun
  decompiling fun
 decompiling main
generating code…
output written to ./output/a
completed in 0 secs.

go to output/a then you will find another test.c
// address: 0×80483d9
int main(int argc, char **argv, char **envp) {
    int local7;                 // r24
        
    local7 = fun();
    *(int*)local7 = 5;
    printf(“%d\n”, 5);
    return 0;
}           
     
// address: 0×80483b4
fun() {
    int local5;                 // r24
   
    local5 = malloc(4);
    free(local5);
    return local5;
}  
   
Well, almost similar without header files and simple changes. But it is exactly what the previous source code meant to do :) ..
I will definitely call it a 90% success.

Posted by maxinbjohn at 04:57:41 | Permalink | No Comments »

Monday, January 7, 2008

What George Bernard Shaw thinks about Apple……

If you have an apple and I have an apple and we exchange apples then you and I will still each have one apple. But if you have an idea and I have an idea and we exchange these ideas, then each of us will have two ideas.

George Bernard Shaw

It is quoted at the mklinux web page . Mklinux  is microkernel “Linux” … a project funded by Apple Inc. I have never seen the combination of GBS with Linux  till now…  Seems very interesting …  as  I am  a  self proclaimed  disciple of  George Bernard Shaw and  an ardent lover of Linux…..

Posted by maxinbjohn at 12:42:34 | Permalink | No Comments »

Wednesday, November 14, 2007

Android : The Linux/Google/Java/Mobile combination

Seems like I am more attracted towards  google’s innovations in the Linux domain. The new craze is Android API. 

Android is a software stack for mobile devices that includes an operating system, middleware and key applications. This early look at the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

The Android SDK is available at http://code.google.com/android/download.html . If you are interested in making some USD (a cool 10 M !!), then have a look at the Android Developer challenge (http://googleblog.blogspot.com/2007/11/calling-all-developers-10m-android.html)

Posted by maxinbjohn at 10:43:21 | Permalink | No Comments »