How to make Mobile Game Programming for Beginners


Introduction

This article is the first part in my Mobile Game Programming for Beginners series. The series starts out with a super-simple game, but will continue to show how to implement a variety of different game types and the techniques used to code them.
The series is a four part series, where I'll go through the following games:
  • Basics
  • BreakOut
  • Top Down Scroller
  • 3D Space Game
This part will show you how to implement a very simple game, which tools you'll need, and how to actually try it out on your handset.
In this game, the goal is to navigate your avatar to a target, no obstacles, and the target isn't even moving. There's no way to "die", no way to loose, but it's a good starting point to show the basics of game programming. The areas I'll cover in this first part are:
  • Tools of the Trade, the applications required (or at least, the ones I like to use).
  • Creating a MIDlet, an application that can run on your mobile phone.
  • Basic Game Loop, the foundation of any game.
  • Reading user input.

Tools of the Trade

All the games in this series have been developed using three software packages:
  • Java 6 SDK
  • NetBeans
  • Paint.NET

Java 6 SDK

The Java SDK (or JDK, Java Development Kit) is a collection of class libraries, tools, and documentation, used when developing Java applications. It is not to be confused with a JRE, Java Runtime Environment, which is something that is used to run Java based applications. I downloaded my JDK from here. You'll need a JDK installed to use the next tool on the list, NetBeans, so make sure this is the first thing you download.

NetBeans

NetBeans is an Integrated Development Environment, IDE, mainly for Java development. It is free, which is good, but the best thing about it is that it truly rocks. According to me, it's by far the best Java IDE around right now. NetBeans is the tool that you'll use to implement and test your game as it comes bundled with a neat emulator so that you don't have to install the game on your mobile phone before you know it works.
Go here and download the Mobility pack and get that installed. The Mobility pack includes the J2ME JDK (Java 2 Mobile Edition), which contains the class libraries required to write a MIDlet (which is a Java application that can run on a mobile device) and the tools required (such as emulators for testing the game without having to install it on an actual handset).

Paint.NET

Almost all games need some sort of graphics to make them enjoyable. I prefer to use Paint.NET to create the graphics for my games (when it's not generated by the game itself, but more on that in the second part of the series). The reason I'm not using Paint that comes bundled with Windows is that it's simply not packed with all the nice features that Paint.NET has, such as support for transparent PNG files.
Head on over to Paint.NET's download page and download it.
Once you have these three tools installed, you're almost ready to start coding.

Basic Game Loop

Almost all games rely on a central game loop, it is the loop that manages or controls the game. As the games you write become more and more complicated, the methods called from the game loop will have to contain more and more logic, but the actual game loop will still be a fairly simple loop. In its simplest form, it might look something like this:

while(gameShouldStillBeRunning) {
// Capture input readInput();

// Update the game state updateGameState();

// Present the game to the user, i. e. render or draw it to screen renderGameState();

// Check for game over checkGameState();
}

Reading Input

This method is responsible for reading or capturing the current state of the input. This includes, for example, checking which keys are pressed and how far the mouse has moved since the last check. The method typically stores the input that is relevant to the game in a place where the updateGameState method can access it.
Storing the game state can be as easy as setting a boolean value to true if a key is pressed, and to false it it's not pressed. The reason for checking the input and storing it first, instead of checking it when you actually need it (i.e., when updating the game state), is because it is often quite expensive CPU wise to read the input, and it is best to get all the input required at once. Otherwise, different parts of the code that updates the game state might query the OS several times for the same key input, which would be unnecessary. Making the games run smooth and fast is a major part of game development, and I will discuss this in a later part of this series.
You'll notice that the game included in this article doesn't read the input state in the game loop, that is because it's relying on a built-in functionality of javax.microedition.lcdui.Canvas; more on this later.

Update Game State

Updating the game state includes all the actual processing of the game logic, such as moving the player's character according to the input captured, moving enemies according to their AI, updating the environment, checking for game over state, and many more things, all depending on what kind of game is being developed.
In this first part, updating the game state includes only moving the avatar and checking if the avatar has reached the goal.

Render Game State

When the game state is rendered, the state of the game (i.e., the location of the player, the map, and for example, the current score) is drawn to the screen. The Canvas class in the javax.microedition.lcdui package is used to render things to the screen in kind of the same way as java.awt or javax.swing components, by overriding Canvas.paint(Graphics graphics). Note that the Graphics parameter isn't the java.awt.Graphics object that you might recognize from desktop development, it is a javax.microedition.lcdui.Graphics object, which is like a cut down version of the AWT one.

Check for Game Over

This is where the game primarily detects if the player has lost or beaten the game, but it will also detect and act on any major state changes. Such as completing a level and moving into a game state where the level summary is shown before the next level is started (yet another state).

Getting Started

Setting up the Project

The first thing to do to get started is setting up a project in NetBeans; it is important to pick the right type of project as the project type dictates the JDK that will be used (remember, we need the J2ME JDK to get this to run on a mobile device).

Create a MIDP Application Project

In NetBeans, select File->New Project... and select the project category Mobility and project type MIDP Application, then click Next.

Give your project a name; in this example, it is called Basics.GameLoop. Then, make sure to un-tick the Create Hello MIDlet as that will create a template designed to handle a control based UI (with buttons and lists), and for a game, all rendering is custom, so no standard controls will be used. Then, click Next.

The next screen shows the configuration options. The settings picked here must match the target device's capabilities. That means that a game written for MIDP-2.1 will not run on a mobile phone that only supports MIDP-1.0, for example. For now, leave this page with its default settings, and click Finish.

In your new project's source package, create a package (as keeping classes in the root package is discouraged). You can call the package whatever you want; in the example application, it is called com.bornander.games.basics.
Create a class called BasicsMIDlet in the package you just created, this will be the entry point for the application. This is the class that the Java runtime on the mobile device will instantiate when the the user selects your MIDlet. Make sure the BasicsMIDlet class extends javax.microedition.midlet.MIDlet, as this class defines the interface used by the runtime to control a MIDlet. javax.microedition.midlet.MIDlet is an abstract class, and there are three methods that must be overridden:
  • startApp() This method is called by the runtime to start the MIDlet, either when a start is requested by the user by selecting the MIDlet in some menu, or when the mobile device decides to return the control back to a previously paused MIDlet.
  • pauseApp() This method is called by the runtime to indicate to a MIDlet that it will lose focus, possibly due to an incoming call. It is entirely up to the MIDlet to actually pause something. The example game included in this article will ignore this method, which means the game would continue to run when a call comes in.
    If a MIDlet decides to pause itself, after taking steps to suspend itself in a controlled manner, call the resumeRequest() method to notify the framework that it is interested to know when it can resume processing.
  • destroyApp(boolean conditional) This method is called when a MIDlet is being destroyed (closed), to allow it to clean up its resources in a safe and controlled way.
Make sure your BasicsMIDlet implements these three, abstract methods, after which your class should look something like this:

package com.bornander.games.basics;
import javax.microedition.midlet.MIDlet;

public class BasicsMIDlet extends MIDlet {

public BasicsMIDlet() {
}

public void startApp() {
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}
The next step is to add the the MIDlet to the Application Descriptor, which is a set of meta data that holds information about the mobile application. One mobile application can contain several MIDlets, but for this example, there's only going to be one.
Right-click Basics.GameLoop and click Properties, then select Application Descriptor, the MIDlets tab, and click Add.... This will let you select a MIDlet class, give it a name and icon, and add it to the descriptor. The dialog auto-detects classes that extends javax.microedition.midlet.MIDlet, so just click OK to accept the default proposal.

And that's it! The mobile application is created. Click Run Main Project to try it out on the emulator. This will launch a mobile phone emulator from where the MIDlet just created can be started. Note that since there's no actual implementation yet, it won't do anything. Add a System.out.println("Hello, world!"); to the BasicMIDlet.startApp method, and run the application again to see that it's actually started. The text will be printed to the NetBeans IDE, so do not expect to see it on the screen of the emulator.

Rendering to Screen

When writing MIDlets, there's a set of classes for labels, text fields, checkboxes and such, that are used in a similar way to the corresponding classes in Swing or AWT. As this article is about game programming, it won't discuss any of these controls as they're not very well suited for graphical games.
The class used to render to screen is javax.microedition.lcdui.Canvas. By extending this class, it is possible to override its paint method and implement custom rendering. Create a new class called MainCanvas and have it extend javax.microedition.lcdui.Canvas. Override paint to render red text on a blue background:

package com.bornander.games.basics;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class MainCanvas extends Canvas implements Runnable {

public MainCanvas() {
}

// The Graphics object is used to render images, lines, shapes and // text to the screen using different draw methods. protected void paint(Graphics graphics) {

// Get the width and height of the screen in pixels int w = getWidth();
int h = getHeight();

// Set the current color to blue (hex RGB value ) and draw a filled // rectangle the size of the screen graphics.setColor(0x00007F);
graphics.fillRect(0, 0, w, h);

// Set the current color to red, the font to the default font and // draw a string to the center of the screen. graphics.setColor(0xFF0000);
graphics.setFont(Font.getDefaultFont());
graphics.drawString("Hello, world!", w / 2, h / 2,
Graphics.BASELINE | Graphics.HCENTER);
}
}
In order to get the MIDlet to use this Canvas, it has to be set as the current one for the display. Modify BasicMIDlet.startApp to create a MainCanvas, and set it to the default Display:

public void startApp() {
MainCanvas mainCanvas = new MainCanvas();
Display.getDisplay(this).setCurrent(mainCanvas);
}
Run the MIDlet again; this time is should look something like this:

Now, it's time to start implementing the actual game.

Implementing the Game

Loading Resources

Even though it would be possible to render all aspects of a game using the different draw methods in javax.microedition.lcdui.Graphics, it is more common to use images created in an image editing program (such as Paint.NET). This game will use two different images: one for the player or avatar, and one for the target.
  • Avatar:
  • Target:
When creating images, it is important to make use of transparent pixels; otherwise, the avatar image wouldn't appear to be round but square.
By adding the resources to a Java package, it is possible to load them into javax.microedition.lcdui.Image objects which can then be drawn onto javax.microedition.lcdui.Graphics. A convenient way of loading resources is to use the Class.getResourceAsStream method, as it allows for referencing resources using Java package names (but with forward slashes instead of dots). Also, since the easiest way to get a Class instance is to call Object.getClass, there's always a simple way to reference resources in the same bundle as the current class.
Image resources can therefore be placed in the normal Java package structure:

By adding two javax.microedition.lcdui.Images as members to MainCanvas, and loading the resources in the constructor, the paint method can be modified to draw the avatar in the upper left corner and the target in the lower right. Notice that it's good practice not to use absolute coordinates (such as 100, 100), but instead calculate the coordinates based on the current screen width and height. Obviously, 0, 0 is always going to be the upper left corner, but the coordinates of the lower right will vary on different mobile devices. By finding the width and height of the screen, and then subtracting the width and height of the image, the target image is guaranteed to always appear in the lower right corner, regardless of screen resolution.

package com.bornander.games.basics;

import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class MainCanvas extends Canvas implements Runnable {

// Declare members for the images private Image avatar;
private Image target;

public MainCanvas() throws IOException {
// Load the image resources avatar = Image.createImage(getClass().getResourceAsStream(
"/com/bornander/games/basics/resources/avatar.png"));
target = Image.createImage(getClass().getResourceAsStream(
"/com/bornander/games/basics/resources/target.png"));
}


protected void paint(Graphics graphics) {

int w = getWidth();
int h = getHeight();

graphics.setColor(0x00007F);
graphics.fillRect(0, 0, w, h);

// Draw the images graphics.drawImage(avatar, 0, 0, 0);
graphics.drawImage(target, w - target.getWidth(),
h - target.getHeight();

graphics.setColor(0xFF0000);
graphics.setFont(Font.getDefaultFont());
graphics.drawString("Hello, world!", w / 2, h / 2,
Graphics.BASELINE | Graphics.HCENTER);

}
}

Making the Avatar Controllable

Always painting the Avatar in the upper left corner isn't going to make for a very interesting game. By declaring members for position, and also travel direction, it will be possible to control the Avatar using the keypad. Normally, I'd prefer to store the location of an Avatar in 2D space as some sort of Point object, but as the J2ME libraries is a cut down version of the J2SE, there is no such class. I could have written my own (as I have for the other games in this series), but decided to store the position as two separate integers. I store the direction as four separate booleans, for up, down, left, and right.

public class MainCanvas extends Canvas implements Runnable {

// The two images private Image avatar;
private Image target;

// The coordinates of the player. private int x = 0;
private int y = 0;

// Flags indicating which buttons are pressed. private boolean up = false;
private boolean down = false;
private boolean left = false;
private boolean right = false;

...
}
Moving the avatar (i.e., updating its X and Y coordinates according to the direction flags) is delegated to a method that also does constraint checking. By constraint checking, I mean the process in which the position is constrained to a valid one. In this example, it is invalid for the avatar to be outside the bounds of the screen.

public class MainCanvas extends Canvas implements Runnable {

...

private void moveAvatar() {
if (up)
--y;
if (down)
++y;
if (left)
--x;
if (right)
++x;

if (y < 0)
y = 0;
if (y > getHeight() - avatar.getHeight())
y = getHeight() - avatar.getHeight();

if (x < 0)
x = 0;
if (x > getWidth() - avatar.getWidth())
x = getWidth() - avatar.getWidth();
}
}
Notice again the use of getWidth/getHeight and avatar.getWidth/avatar.getHeight to make the constraint checking independent of screen size as well as image size. This method, MainCanvas.moveAvatar, will be called by the game loop for each iteration to update the position of the player. Obviously, this also requires a small change to the MainCanvas.paint method, as the avatar is no longer drawn at (0, 0), but at (x, y).

Capturing the Input

By extending Canvas, it's easy to capture the input by simply overriding some methods. Canvas exposes three methods related to key input:
  • void keyPressed(int keyCode)
  • void keyReleased(int keyCode)
  • void keyRepeated(int keyCode)
In this first example, I'm only going to use keyPressed and keyReleased, and to control the Avatar, the only thing the methods needs to do is to set up, down, left, and right according to which key was pressed or released.
The keyCode parameter passed to the key handling can be converted to key codes better suited for game programming using the aptly named function Canvas.getGameAction; this will convert the key code into one that can be checked for buttons such as up and down.

/**
* This gets called for us whenever a key is pressed.
* @param key The pressed key.
*/

protected void keyPressed(int key) {
int gameKey = getGameAction(key);
switch(gameKey) {
case Canvas.UP: up = true; break;
case Canvas.DOWN: down = true; break;
case Canvas.LEFT: left = true; break;
case Canvas.RIGHT: right = true; break;
case Canvas.FIRE: shouldRun = false; break;
}
}

/**
* This gets called for us whenever a key is released.
* @param key The released key.
*/

protected void keyReleased(int key) {
int gameKey = getGameAction(key);
switch(gameKey) {
case Canvas.UP: up = false; break;
case Canvas.DOWN: down = false; break;
case Canvas.LEFT: left = false; break;
case Canvas.RIGHT: right = false; break;
}
}

Checking for Game Over state

All games need to check the Game Over state; this can occur either when the player loses the game or when he beats it. In any case, it has to be checked, or the game can neither be won or lost.
In this first example, Game Over can only occur when the player has beaten the game. Yep, that's right. This is a game you can't fail at. You can choose not to win, but you can't lose. This implementation calls a method called isGameCompleted to check if the game is over. This method sets a member variable, completed. To change the behaviour of the game when the Game Over state is reached, the run method looks at the completed flag set when the Avatar has reached the Goal, and if it's true, then the Avatar isn't moved anymore, regardless of key presses. Also, the paint message draws a Game Over message at the center of the screen.
/**
* Detects if the game has been completed
* (i.e. the avatar has navigated to the target).
* @return true if the game is completed.
*/

private boolean isGameCompleted() {
return x == targetX && y == targetY;
}
This method is called in the run method:
protected void paint(Graphics graphics) {

...

if (completed) {
graphics.setColor(0xA0A0FF);
graphics.setFont(Font.getDefaultFont());
graphics.drawString("Game Over", w / 2, h / 2,
Graphics.BASELINE | Graphics.HCENTER);
}
}

public void run() {
while(shouldRun) {
completed = isGameCompleted();

if (!completed) {
moveAvatar();
}

repaint();

try {
Thread.sleep(20);
}
catch (InterruptedException ex) {
}
}
owner.exit();
}
And that's it! That's the whole game. It's not the most addictive game in the world, but it is enough to show how to set up a NetBeans project and the basics of a game.

Next Part

In the next part, I'll cover menus, simple AI, and basic collision detection as I demonstrate how to write a BreakOut style game.

As always, any comments on the article or the code are most welcome.
Read More

How to make own first mobile game in java

game_screen.jpg

Introduction

J2ME is an interesting environment for games. With basic knowledge of Java, preinstalled NetBeans and J2ME Wireless Toolkit, you can make simple, funny 2D games that are capable of running on your own mobile devices.
This article will make use of the 5-class Game API composed in the package javax.microedition.lcdui.game.

Background

This thread assumes that you have basic knowledge of Java, are familiar with NetBeans and have gone through the thread “Introduction to Java ME Programming”. Game making also requires certain knowledge of physics including Newton’s Law of motion, Motions, collisions, …etc.
Recently, I attend a project named Mobile Application Development Intensive Programs organized by my University and its alliances. The project is financed by Uramus, a program to encourage student exchange between European countries. We started with J2ME and it is the result of this thread. So, in this thread, I will use some of the material taken from the project.
By using the GameBuilder, the game making process is much easier. However, I’m not going to cover it in this thread. Details of game making by using GameBuilder can be found here.
As a student, I probably do not have enough experience to apply the best practice. That's why I warmly welcome any comments or suggestions to make it a better guide.

Using the Code  

The MainMidlet 

As a Midlet, the MainMidlet must extend the abstract class Midlet that can be found in the package javax.microedition.midlet. The Midlet requires override of three methods: 
  • startApp() called to start the game
  • pauseApp() called to temporarily stop the application, i.e., receiving a call. Application should stop the animation and release resources that are not needed. Application can be resumed by calling resumeMIDlet() 
  • destroyApp(boolean unconditional) called when exiting the application. In order to terminate, the MIDlet can call notifyDestroyed()
(These methods are automatically created by creating a Visual Midlet in NetBeans.)
We are, however, only needed to implement the startApp() methods by creating an instance of our GameCanvas and adding a CommandListener to exit the Midlet. It is, of course, not a good programming habit but until this step, we probably only want the application to run. Current display can be set to the GameCanvas at the end or inside the GameCanvas by the method setCurrent. This method accepts any Displayable objects as an argument. 

public class MainMidlet extends MIDlet implements CommandListener {
private SSGameCanvas gameCanvas ;
private Command exitCommand ;
public void startApp() {
try {
//create new game thread
gameCanvas = new SSGameCanvas();
gameCanvas.start(); // start game thread
exitCommand = new Command("Exit",Command.EXIT,1);
gameCanvas.addCommand(exitCommand);
gameCanvas.setCommandListener(this);
Display.getDisplay(this).setCurrent(gameCanvas);
}
catch (java.io.IOException e) { e.printStackTrace();}
}

public void pauseApp() {} 
public void destroyApp(boolean unconditional) {}

public void commandAction(Command command, Displayable displayable) {
if (command == exitCommand) {
destroyApp(true);
notifyDestroyed();
}
}
}

The GameCanvas

As an element of low level UI engine, when combined with Graphics, GameCanvas provides us flexible tools to set up our own game screen. With Graphics, you basically can draw things that you can normally do in Java 2D, including drawing shapes, strings or images. GameCanvas is an extension to the original Canvas with more control over the painting, and the rate at which keys are delivered into the game.
Using GameCanvas, you can notice its capabilities including the off-screen buffering. When you are drawing things, you probably are drawing into the off-screen and by calling the flushGraphics() method, the buffer is quickly written into the screen.
GameCanvas also simplifies the process of getting input by allowing us to query the key status usinggetKeyState() method. Processing key status, however, is left to the GameManager for easier management.  the
The origin of the game coordinate system is located in the top left corner of the screen as shown.
gamescreen.jpg In the render method, the off-screen is cleared and graphics are rendered by calling paint method of the GameManager.  

public void render(Graphics g) {

……..
// Clear the Canvas.
g.setColor(0, 0, 50);
g.fillRect(0,0,WIDTH-1,HEIGHT-1);
….….
gameManager.paint(g);
}
In this example, the SSGameCanvas implements Runnable interface, which leads to the creation of the run() methods in which we create a game loop running until we reach certain ending condition.
game_states.jpg

Game Loops


  public void run() {


while (running) {
// draw graphics
render(getGraphics());
// advance to the next tick
advance(tick++);
// display
flushGraphics();
try { Thread.sleep(mDelay); }
catch (InterruptedException ie) {}
}
}
Timing of the game is controlled by an integer named tick. tick simplifies timer problem in the game, such as firing rate of a ship, or how long a star will flash, how long a sprite will step into the next frame. If timing is done in the GameCanvas by implementing Runnable, a tick means mDelay + time to complete one gametick, we will probably have tick = mDelay. We will probably need only 24 -30 fps, so we limit the mDelay accordingly to have the desired animation effect with less power consumption. At every cycle of the game, we call the method advance of the GameManager, which extends LayerManager to check the user input, collisions and paint the graphics. cycle (milliseconds). If we create a Thread which takes care of

public void advance(int ticks) {
// advance to next game canvas
gameManager.advance(ticks);
this.paint(getGraphics());
}
}
tick  may have a limitation: it limits the game playing time by the limit of the integer, which is about over 590 hours in a 32-bit system.

Sprite

Sprite acts as the actors of the games. It could be our Mario characters, ducks, and bullets in the Mario games or space ships in a star war game. As a basic visual element, it can be rendered to display continuous action with several frames stored in an Image. The Image file must pack all the frames of the Sprite in order to be displayed. All frames must have the same and predefined width and height.

public SpaceShip(Image image, int w, int h) throws java.io.IOException {
super(image,w ,h);
WIDTH = w;
HEIGHT= h;
setFrameSequence(SEQUENCE);
defineReferencePixel(WIDTH/2,HEIGHT/2);
setTransform(this.TRANS_MIRROR_ROT270);
}

To initiate the Ship sprite, I call the constructor from the superclass Sprite: super(image, w, h); where w and h is the width and height of each frame. The image consists of 8 frames, so I set the frame sequence {0,1,2,3,4,5,6,7} using setFrameSequence method.
Next, I call the defineReferencePixel method to set the reference point to the middle of the frame. This reference pixel will be used to position the ship on the screen. And finally I rotate all the frames by the method setTransform.

public void advance(int ticks) {
if ((ticks%RATE==0))
nextFrame();
}
The method advance will change the frame of the ship to create animation accordingly to RATE. By continuously calling nextFrame(), the screen will display the frame sequence from 0 to 8 and then come back to 0: 0,1,2…7,0,1,2…. The following methods moveLeft(), moveRight(), moveUp(), moveDown()speedX and speedY. to change the position of the ship on the screen depends on its

public void moveLeft () {
if (this.getRefPixelX()>0)
this.move(-speedX, 0);
}

public void moveRight (int m) {
if (this.getRefPixelX() < m)
this.move(speedX, 0);
}

public void moveUp () {
if (this.getRefPixelY()>0)
this.move(0, -speedY);
}

public void moveDown (int m) {
if (this.getRefPixelY()<m)
this.move(0, speedY);
}
When the ship is commanded to shoot a bullet, we check whether the cool down is gone or not by comparing current time with the previous shot time.

public Bullet fire (int ticks) {
if (ticks- fireTick > SHOOT_RATE) {
fireTick = ticks;
bullet.setSpeed(BULLET_SPEED);
bullet.shot(this.getRefPixelX(), this.getRefPixelY()+HEIGHT/2);
return bullet;
}
else
return null;
}
To check the collision between the spites, images or TitledLayer (will be mentioned later), we use the method collidesWith. I will make use of this method in the GameManager to check the collision between the ship and the asteroids to reduce HP of the ship and to check collision between the bullet and the asteroids to increase score and destroy both the bullet and the asteroid.

GameManager

As a subclass of LayerManager , the GameManager is capable of managing series of Layers, automatically renders each Layer in an appropriate order. Method append is called to add a specific Layer to the LayerManager.

private Image shipImage;
private static final String SHIP_IMAGE = "/resource/blue_ship.png";
private static final int SHIP_WIDTH = 40;
private static final int SHIP_HEIGHT = 33;
shipImage = Image.createImage( SHIP_IMAGE );
// create space ship
ship = new SpaceShip(shipImage, SHIP_WIDTH, SHIP_HEIGHT);
// set it position
ship.setRefPixelPosition(height/2, width/2);
this.append(ship);
In order to respond to the user input, we query the key states with a referenced instance of our GameCanvasusing the method getKeyStates(). For each key state, we react correspondingly by moving the ship to the desired direction.
int keyState = gameCanvas.getKeyStates();

// move right
if ((keyState & GameCanvas.RIGHT_PRESSED)!= 0){
ship.moveRight(width);
}

// move left
if ((keyState & GameCanvas.LEFT_PRESSED)!= 0){
ship.moveLeft();
}

// move up
if ((keyState & GameCanvas.UP_PRESSED) != 0){
ship.moveUp();
}

// move down
if ((keyState & GameCanvas.DOWN_PRESSED) != 0){
ship.moveDown(height);
}
In the GameManager, we also check for collision between the ship, bullet and random created enemy (asteroids). If collision occurred, we change the game status accordingly to the collision.
private Obstacle checkCollisionWithAsteroids(Sprite t) {

for (int i =0; i < MAX_OBS;i++) {
if (obs[i]!=null)
if (obs[i].collidesWith(t, true)) {
return obs[i];
}
}
return null;
}
In case we reach the game ending condition, we display high score and stop the GameCanvas Thread usingstop: the method
protected void endGame(Graphics g) {
GameOver=true;
gameCanvas.stop();
Font f = g.getFont();
int h = f.getHeight()+40;
int w = f.stringWidth("High score")+40;
g.setColor(250,250,250);
g.drawString("Score " + score,(width-w)/2,(height-h)/2,g.TOP | g.LEFT);
}

Points of Interest 

With the given knowledge, I believe that you can create simple games like: go fishing, frog crossing the road. I will cover TitledLayer, sound in the next updated of the post. They will surely increase the look and the feeling of the game.
fishing.jpg frog.jpg
Read More

How to Make Mobile Games Using Java


Do you have a game that should on phones supporting Java? If so, read up on this. There's a few blockers on your way.

Steps

  1. 1
    Understand regular Java game-making. Try to create a desktop version of your game first.

  2. 2
    Know the limits of J2ME. J2ME is the JRE loaded on Java-supported phones. It's limited in some ways.
  3. 3
    Know the limits of the phones you're targeting. For example, some phones have J2ME 1.5.
  4. 4
    Test it. There's more limits in J2ME, and possibly your target phones. Testing can benefit greatly, if your game is big enough; you may want to pick a few testers before releasing.
  5. 5
    Sign the JARs. VeriSign and StartCom (just to name a few) offer code-signing certificates.
  6. 6
    Distribute it. Using forums, file hosting sites, gaming sites, and other resources to your advantage.
Read More

How to Display your own custom images as Google Search Background

As you already know that you can customized the background of your Google Search Page. This gives a good look and feel when you open google. I know many people who have google as their homepage, including myself. By using a background image, that suites your personality, you can make the way you search online more interesting. But do you know that you can also display your own customized images as your google background. This can be done by 2 methods. Either you can opt to display any of your image from Picasa or you can also upload a custom image from your computer. Here is a brief tutorial about it.
  1. Open Google Home Page and click “Change Background Image”
  2. After clicking it – In the “Select a background image” dialogue box select “From my computer”
  3. Now upload the image that you want to display in google as a background.
Read More

How to Hack any Weak Passwords

If you invited me to try and crack your password, you know the one that you use over and over for like every web page you visit, how many guesses would it take before I got it? 



Let’s see… here is my top 10 list. I can obtain most of this information much easier than you think, then I might just be able to get into your e-mail, computer, or online banking. After all, if I get into one I’ll probably get into all of them.
  1. Your partner, child, or pet’s name, possibly followed by a 0 or 1 (because they’re always making you use a number, aren’t they?)
  2. The last 4 digits of your social security number.
  3. 123 or 1234 or 123456.
  4. “password”
  5. Your city, or college, football team name.
  6. Date of birth – yours, your partner’s or your child’s.
  7. “god”
  8. “letmein”
  9. “money”
  10. “love”
Statistically speaking that should probably cover about 20% of you. But don’t worry. If I didn’t get it yet it will probably only take a few more minutes before I do…

Hackers, and I’m not talking about the ethical kind, have developed a whole range of tools to get at your personal data. And the main impediment standing between your information remaining safe, or leaking out, is the password you choose. (Ironically, the best protection people have is usually the one they take least seriously.)

One of the simplest ways to gain access to your information is through the use of a Brute Force Attack. This is accomplished when a hacker uses a specially written piece of software to attempt to log into a site using your credentials. Insecure.org has a list of the Top 10 FREE Password Crackers right here.
So, how would one use this process to actually breach your personal security? Simple. Follow my logic:
  • You probably use the same password for lots of stuff right?
  • Some sites you access such as your Bank or work VPN probably have pretty decent security, so I’m not going to attack them.
  • However, other sites like the Hallmark e-mail greeting cards site, an online forum you frequent, or an e-commerce site you’ve shopped at might not be as well prepared. So those are the ones I’d work on.
  • So, all we have to do now is unleash Brutus, wwwhack, or THC Hydra on their server with instructions to try say 10,000 (or 100,000 – whatever makes you happy) different usernames and passwords as fast as possible.
  • Once we’ve got several login+password pairings we can then go back and test them on targeted sites.
  • But wait… How do I know which bank you use and what your login ID is for the sites you frequent? All those cookies are simply stored, unencrypted and nicely named, in your Web browser’s cache. (Read this post to remedy that problem.)
And how fast could this be done? Well, that depends on three main things, the length and complexity of your password, the speed of the hacker’s computer, and the speed of the hacker’s Internet connection.
Assuming the hacker has a reasonably fast connection and PC here is an estimate of the amount of time it would take to generate every possible combination of passwords for a given number of characters. After generating the list it’s just a matter of time before the computer runs through all the possibilities – or gets shut down trying.
Pay particular attention to the difference between using only lowercase characters and using all possible characters (uppercase, lowercase, and special characters – like @#$%^&*). Adding just one capital letter and one asterisk would change the processing time for an 8 character password from 2.4 days to 2.1 centuries.
Password Length All Characters Only Lowercase
3 characters
4 characters
5 characters
6 characters
7 characters
8 characters
9 characters
10 characters
11 characters
12 characters
13 characters
14 characters
0.86 seconds
1.36 minutes
2.15 hours
8.51 days
2.21 years
2.10 centuries
20 millennia
1,899 millennia
180,365 millennia
17,184,705 millennia
1,627,797,068 millennia
154,640,721,434 millennia
0.02 seconds
.046 seconds
11.9 seconds
5.15 minutes
2.23 hours
2.42 days
2.07 months
4.48 years
1.16 centuries
3.03 millennia
78.7 millennia
2,046 millennia
Remember, these are just for an average computer, and these assume you aren’t using any word in the dictionary. If Google put their computer to work on it they’d finish about 1,000 times faster.
Now, I could go on for hours and hours more about all sorts of ways to compromise your security and generally make your life miserable – but 95% of those methods begin with compromising your weak password. So, why not just protect yourself from the start and sleep better at night?
Believe me, I understand the need to choose passwords that are memorable. But if you’re going to do that how about using something that no one is ever going to guess AND doesn’t contain any common word or phrase in it.
Here are some password tips:
  1. Randomly substitute numbers for letters that look similar. The letter ‘o’ becomes the number ’0′, or even better an ‘@’ or ‘*’. (i.e. – m0d3ltf0rd… like modelTford)
  2. Randomly throw in capital letters (i.e. – Mod3lTF0rd)
  3. Think of something you were attached to when you were younger, but DON’T CHOOSE A PERSON’S NAME! Every name plus every word in the dictionary will fail under a simple brute force attack.
  4. Maybe a place you loved, or a specific car, an attraction from a vacation, or a favorite restaurant?
  5. You really need to have different username / password combinations for everything. Remember, the technique is to break into anything you access just to figure out your standard password, then compromise everything else. This doesn’t work if you don’t use the same password everywhere.
  6. Since it can be difficult to remember a ton of passwords, I recommend using Roboform for Windows users. It will store all of your passwords in an encrypted format and allow you to use just one master password to access all of them. It will also automatically fill in forms on Web pages, and you can even get versions that allow you to take your password list with you on your PDA, phone or a USB key. If you’d like to download it without having to navigate their web site here is the direct download link.
  7. Mac users can use 1Password. It is essentially the same thing as Roboform, except for Mac, and they even have an iPhone application so you can take them with you too.
  8. Once you’ve thought of a password, try Microsoft’s password strength tester to find out how secure it is.
By request I also created a short RoboForm Tutorial. Hope it helps…
Another thing to keep in mind is that some of the passwords you think matter least actually matter most. For example, some people think that the password to their e-mail box isn’t important because “I don’t get anything sensitive there.” Well, that e-mail box is probably connected to your online banking account. If I can compromise it then I can log into the Bank’s Web site and tell it I’ve forgotten my password to have it e-mailed to me. Now, what were you saying about it not being important?
Often times people also reason that all of their passwords and logins are stored on their computer at home, which is save behind a router or firewall device. Of course, they’ve never bothered to change the default password on that device, so someone could drive up and park near the house, use a laptop to breach the wireless network and then try passwords from this list until they gain control of your network – after which time they will own you!
Now I realize that every day we encounter people who over-exaggerate points in order to move us to action, but trust me this is not one of those times. There are 50 other ways you can be compromised and punished for using weak passwords that I haven’t even mentioned.
I also realize that most people just don’t care about all this until it’s too late and they’ve learned a very hard lesson. But why don’t you do me, and yourself, a favor and take a little action to strengthen your passwords and let me know that all the time I spent on this article wasn’t completely in vain.
Please, be safe. It’s a jungle out there.




Disclaimer: I don’t take Responsibility for what you do with this script, served for Educational purpose only. 
Read More

How To Get Free Facebook Fans with Your Email .

If you’re trying to get more fans to visit your facebook fan page, there’s a little plugin you need to know about if you’re using Gmail, Yahoo Mail, AOL, or any other web-based email client. It’s called WiseStamp.
How many emails do you send per day? Probably too many, like the rest of us. And how many emails have you seen with over-sized and unattractive email signatures that doing everything except get you to click on them? Well, those days are over.
WiseStamp gives the average business owner, blogger, or online marketer the chance to have an attractive and high-performing email signature that not only catches the reader’s eye but also keeps everyone up to date on the company’s latest social updates.
wisestamp logo Workshop Wednesday: Get More Fans with Your Email SignatureWith WiseStamp, you can insert a quick link and/or icon to all of your social media hot-spots, embed your own rss feed, include your latest tweets, and the list goes on. Completely customize your email signature with fonts, text sizes, colors, links, images, and icons in order to create the perfect closing to every email you send out.
There’s not a better free way to get more facebook fans than going after everyone you already have a relationship with.
Having a special sale? Edit your signature with a few clicks of the mouse and let everyone know about it. Free advertising.
wisestamp social media email Workshop Wednesday: Get More Fans with Your Email Signature
WiseStamp also has a great installation guide in case you get a little lost, but I doubt that’s going to happen because this plugin is super easy to use and install.
Even Outlook users should stay tuned because WiseStamp is currently working on a new release for everyone not using web-based email applications.
Go grab WiseStamp now and start connecting with your current clients and leads and start adding them to your facebook fan following.
If you’re looking for even more great ways to increase your facebook fans and start driving sales right from your fan page, you should take a look at one of our newest facebook trainings, where I guarantee your fans will skyrocket in just a few days.
Read More

How to Get Facebook Updates on Your Mobile for Free

Facebook can send your Facebook friends’ updates on your Mobile for Free. Ufone has advertised the whole process on their website.
Currently Facebook is offering Updates for Ufone, Mobilink, Telenor and Warid.
Below is the complete process of how to register your Mobile number with your Facebook Account.

Registration Process:

To activate Facebook functionality on mobile handset, user will be required to login to the following link:
http://www.facebook.com/mobile
0011 Get Facebook Updates on Your Mobile for Free
  • Click on Sign up with Facebook Text Messages. (You are supposed to be logged in before clicking on this link
  • Now select your country and operator – click next
  • Send a message with ‘F’ to 32665
  • Enter confirmation code received on your cell into dialogue box appearing in facebook account – and you are done.
Important:
On next page users can edit all notification settings e.g. what kind of notifications to receive, what should be the time of notification, number of notifications to be received, etc. To save setting users will be required to click Save Preferences button.
Be sure you don’t select all updates to be received on your Phone – otherwise, your mobile will keep beeping all the times.
You can also add multiple phone numbers to a single profile or remove existing phone numbers as well, however notifications will only be sent to a single number.

How to Update Facebook through Mobile

Complete list of Facebook functionalities is mentioned below:
To update Facebook status: Send <new status message> to 32665, e.g. “I’m in at a party” to 32665. There is no need to use inverted commas.
To Undo Status Change: To immediately remove an updated status through SMS or restore previous status, send “Undo” to 32665
To send Message to a Friend: Send “MSG <friend’s name> <text>, to 32665 e.g., “MSG Usman hey man where are you” to 32665
Or
Send “M <friend’s name> <text>, to 32665 e.g., “M Usman hey man where are you” to 32665
To write on Friend’s Wall: Send “Wall <friend’s name> <text>, to 32665 e.g., “Wall Usman hey did you pass the exam?” to 32665
Or
Send “W <friend’s name> <text>, to 32665 e.g., “W Usman hey did you pass the exam?” to 32665
To Poke a Friend: Send “Poke <friend’s name>” to 32665 e.g. “Poke Usman” to 32665”
To Subscribe to a Friend’s Status Update: Send “Subscribe <friend’s name>” to 32665 e.g. “Subscribe Usman” to 32665”
Or
Send “Sub <friend’s name> to 32665” e.g. “Sub Usman” to 32665”
To Un-subscribe to a Friend’s Status Update: Send “unsubscribe <friend’s name>” to 32665 e.g. “unsubscribe Usman” to 32665”
Or
Send “unsub <friend’s name>” to 32665 e.g. “unsub Usman” to 32665”
To search for Friend’s Information: Send “Find <friend’s name>” to 32665 e.g., “Find Usman” to 32665 and get their information on name, e-mail, status, marital status, mobile number and more.
To Add a Friend: Send “Add <friend’s name>” to 32665 e.g., “Add Usman” to 32665. User will get a list of people matching their criteria with closest matches of their friend’s name.
To find a Friend’s E-mail: Send “Email <friend’s name>” to 32665 e.g. “Email Usman”. User friend has to be on Ffacebook to retrieve the email address.
To get Help on list of commands: Send “Help” to 32665.
To De-activate Notifications: Send “OFF” to 32665. User will no longer be able to receive notifications on their handset.
To Re-Activate Notifications: Send “ON” to 32665. User will start receiving notifications again. However user already needs to be a registered user to SMS mobile notifications.
Reply to Notifications: You can also reply to notifications they receive. Following is detailed list and format of notifications received on user handset. User will only be required to reply to the notifications.
Poke notification: You have been poked on Facebook by <Friend Name> Reply ‘P’ to poke <Friend Name> back.
Message notification: Facebook msg from <Friend Name> Subj: <subject> <Message Text> …(‘n’ for next) Reply to msg <Friend Name>back.
User can only reply back to message when they have read the complete message. To read remaining message they will reply back to SMS with “n”
Wall notification: <Friend Name> wrote on your Facebook wall: <Message Text> …(‘n’ for next) Reply to msg <Friend Name> back.
User can only reply back to message when they have read the complete message. To read remaining message they will reply back to SMS with “n”. Reply to this message will be posted on friend’s wall.
Add Friend notification: <Friend Name> has requested to add you as a friend on Facebook. Reply ‘add’ to add, or ‘info’ to get profile.
User can reply back with “Add” to 32665 to accept the friend request or get information about the person by replying with “Info” to 32665
Photo-tag notification: <Friend Name> added a photo of you on Facebook. <photo-link>
Photo comment notification: <Friend Name> commented on your photo. <photo-link>
Users can view the posted photo or comment on the photo by visiting the link on their handset. This would require GPRS activated handset to access the link.
If the user does not send an MO in 45 days his account will be inactivated and the following reminder message will be sent to the user
You have not used Facebook texts in over 45 days. Notifications will be turned off. To continue receiving Facebook Mobile Texts, reply “ON” within 48 hours
Picture Upload through MMS: You can also upload their pictures straight from their handset on to their facebook profile. To upload a picture user will be required to login into the below link get their unique email address.
Once user is logged in they will get their unique Facebook-MMS Email ID as shown below. They can find the Email ID under Upload via Email heading. For example purposes only, the Email ID for the logged in account whose snapshot is attached is: agatha703lepton@m.facebook.com.
Or users can simply click “Send my upload email to me now” link under Upload via Email heading and then can receive their unique Facebook-MMS Email ID on their email or mobile handset.
To upload a picture from mobile, user will only be required to MMS their picture to the provided Facebook-MMS Email ID and their uploaded picture will appear on their Facebook under Mobile Upload album.
Pricing:
  • All SMS sent to 32665 will be charged Re 1 plus tax.
  • All notifications received are free of charge.
  • Picture upload charges are as per MMS standard i.e. Rs 5 plus tax/64KB
  • For GPRS access, standard GPRS charges apply
Read More

How to make money with Facebook fan page - $500 daily!

Here I am going to tell you how to make money with Facebook fan page. I am not talking about playing games, developing applications etc. I am talking about doing it in an impressive manner and that works forever.
You have two ways to do it. First you have your own product/service/subscription OR you are offering a CPA offer. It does not matter, if you have your product, website, blog or not. If you do not have any even then you can make huge money with facebook fan page. If you already have a website then its ok otherwise you can promote a CPA offer to make money. Visit any website that offer CPA products to promote or have affiliate programs. Visit clickbank.com, maxbounty.com, ejunkie.com etc. My favourite is clickbank.com Here I am not going to tell you what is CPA offers or affiliate programs. You may do some googling about it. :)
After choosing a CPA program (or in case you have your own website & product) your first task should be to make thousands of fans for your product. Making fans begin from making thousands of friends. If you have thousands of friends on Facebook only then you will be able to make facebook fans quickly. There are so many people on the earth who make 5000 Facebook friends (maximum limit) in 7 days only. Visit Google and type "5000 Facebook Friends in 7 Days" and you are going to find very interesting results. It is not difficult. After you add 5000 Friends, you can make a Facebook Fan page.
Start suggesting your fan page to your friends and ask them to suggest it to their friends. Visit Google and type "50000 Facebook Fans in 30 Days". It will be a great help for you if you want to add facebook fans quickly.
Now, when you have thousands of Facebook fans you can suggest them your website, product or CPA offers. Ask them to visit at your website and see what you are offering.

You should keep few things in mind:

1. If you are offering a weight lose product (e.g.) then you should create a fan page only on losing weight or being fit, otherwise you wont get targeted visitors. Only people interested in losing weight should join your fan page and thereafter they will visit your site.

2. Keep your fan page simple and spam free. Do not spam people with a link to your fan page otherwise they will report you.

3. Build relation with your fans giving them free tips on weight lose and in meantime ask them to visit at your site.

In this way, if you have thousands of facebook fans then TONS of visitors will be visiting to your website and will buy your product. There are many people (including me) who are making $500 everyday with Facebook Fan page.
You may visit my site to check how to make money Facebook and you will surely like it.
Thanks

Read More

How to Add Print Friendly to Blogger or Blogspot

Step 1: Get PrintFriendly Button Code

Goto PrintFriendly.com/button. Select Blogger/Blogspot. Choose your button style, and copy and paste the PrintFriendly code snippet.



Step 2: Edit Your HTML Template
  • Log into Blogger or Blogspot
  • Click Design > Edit HTML
  • Click Check Box Expand Widget Templates (don't miss!).



Step 3: Paste Button Code
  • Find <div class="post-footer"> in template code. Tip: Press "Control" plus "F" on keyboard to search for "class='post-footer".
  • Paste PrintFriendly Button Code
  • Save Template


Customize Your Button


Align Button to Right

To align your PrintFriendly button to the Right. Add inline CSS to the PrintFriendly code snippet.
Step 1: Find the two <div class='pfbutton'>, inside your PrintFriendly button code.Step 2: Add style='float:right;' to the div.



Use a Your Own Graphic/Button

In the PrintFriendly code snippet, there's two images (one for list page, the other for post pages). Find the image tags and then change the src to the URL of the graphic/button you would like to use.




Show Only on Post Pages (not on homepage)


There's two sections to the code snippet. The "Index" section adds the button to the homepage, "Item" adds the button to the post/article page.

Change the word "Index" to "Item". Then, delete the first section.

Read More