dcsimg
September 26, 2016
Hot Topics:

Creating Android Games with Java

  • August 28, 2015
  • By Manoj Debnath
  • Send Email »
  • More Articles »

Android games are intriguing due to their simplicity, yet they have engrossing appeal. With the evolution of Android as a platform in hand-held devices, there is a growing demand for games. There are literally as many varieties of games as utility apps found in the arena. Building engaging games requires a high level of creativity along with a good understanding of Android intricacies. Because Java is a de facto language of the Android platform, programmers who know Java can leverage their skill and try their hand at creating games with relative ease. The article focuses on some key areas of Android with Java that would help in building one.

Game Design

Ideas are the root to game design. The booming game industry is always looking for designers, artists, and programmers who have creative enterprise to take up the challenge in building the next killer game in the market. Unlike PC, Xbox programmers who virtually have unlimited amount of resources and have the luxury to exploit every bit of it, the resources of Android programmers are limited. So, creating engaging games in Android can be an interesting challenge. Although it may seem to be an uphill task, the resources provided by Android and their implementation are quite simple. The main reason for simplicity is obviously Java, backed by its huge collection of API libraries. There are several aspects that come into play, especially in game programming, such as using threads, animation, sound FX, data persistence, and so forth, apart from commonly used data structures. Let's get into some of its details and see how to implement them.

Thread

Threading plays an important part in programming games. To put it simply, thread is a part of the code that usually runs in multiple processes, to give an illusion of simultaneous execution. For example, in a racing game when you are speeding a car to win the race, another car is chasing to outrun you. There may be multiple cars jostling to outrun each other in a competition. So, here each car represents a thread running concurrently with an equal chance of winning any one of them. In this example, most threads are timed automatically by the system, except the one that is in your control. It basically provides a mechanism to handle different aspects of programming concurrently. However, be cautious of multiple threads in execution. Without proper synchronization, they are notorious for erratic behavior; also, too many of them slack in performance. Thread in Android can be implemented in a similar manner as implemented in Java.

UI Animation

Animation is a complex phenomenon made simple in Android with the help of the Animation class. This, however, creates a simple animation of the user interface, such as animating a component fade in/out, rotating, sliding, scaling, or morphing colors. Suppose we want to use scale and fade in a button; what we have to do is create a XML file, as follows, in the anim folder under the res directory.

<?xml version="1.0" encoding="utf-8"?>
      <rotate xmlns:android="http://schemas.android.com/
      apk/res/android"
   android:duration="200"
   android:fromDegrees="-10"
   android:pivotX="50%"
   android:pivotY="50%"
   android:repeatCount="10"
   android:repeatMode="reverse"
   android:toDegrees="10" />

public class MainActivity extends Activity
      implements View.OnClickListener{
   Button button1;
   Animation animation;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      animation= AnimationUtils.loadAnimation
          (this,R.anim.my_animation);

      button1=(Button)findViewById(R.id.button1);
      button1.setOnClickListener(this);


   }

   @Override
   public void onClick(View v) {
      switch(v.getId()) {
         case R.id.button1:
            button1.setAnimation(animation);
       }
   }
}

Sound Effects

Sound effects are important to make an illusion of a live impact of an event. Imagine a gun firing without a sound; it has no impact. Sound effects are nothing but loading sound files and playing the same on the occurrence of an event. There are different formats of sound files, but Android has a special affinity towards the OGG format. Get bfxr, an open source application, where you can edit a preset sound library and save it to OGG format. These files then can be used in code as follows.

public class MainActivity extends Activity
      implements View.OnClickListener{

   private SoundPool soundPool;
   int sound1=-1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      soundPool=new SoundPool(10, AudioManager.STREAM_MUSIC,0);
      try{
         AssetManager manager=this.getAssets();
         AssetFileDescriptor descriptor=
            manager.openFd("sound1.ogg");
         sound1=soundPool.load(descriptor,0);

      }catch(IOException ioException){

      }
      Button button1=(Button)findViewById(R.id.playButton);
      button1.setOnClickListener(this);
   }

   @Override
   public void onClick(View v) {
      switch(v.getId()) {
         case R.id.playButton:
            soundPool.play(sound1, 1, 1, 0, 0, 1);
      }
   }
}

Data Persistence

Persistence helps in remembering the state of the game while switching between the tasks, such as answering incoming calls in mobile devices or saving/pausing the game state for later use. This helps in resuming the exact state when the game is revisited. Persistence in Android is implemented in a bit different way than in Java. Android simplified the process of data persistence with the help of the SharedPreferences class. This class hides the complexity of files' read/write and can be implemented as follows.

public class MainActivity extends Activity
      implements View.OnClickListener{

   SharedPreferences sharedPreferences;
   SharedPreferences.Editor editor;
   int currentScore;
   Button button1;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      sharedPreferences=getSharedPreferences("userData",
         MODE_PRIVATE);
      editor=sharedPreferences.edit();

      // load data
      currentScore=sharedPreferences.getInt("score",0);


      button1=(Button)findViewById(R.id.button1);
      button1.setOnClickListener(this);
      button1.setText(currentScore);

   }

   @Override
   public void onClick(View v) {
      switch(v.getId()) {
         case R.id.button1:
            currentScore=currentScore+1;
            // save data
            editor.putInt("score",currentScore);
            editor.commit();
            button1.setText(currentScore);

      }
   }
}

Conclusion

Game programming is not a one-man activity, especially those graphics-intensive, big budget games. However, it is also true that there are games thatich require more intellectual effort than graphics, such as Sudoku. I think such games can be an interesting project to deal with single handedly. Apart from fun, these games are a great intellectual exercise as well. The article is not intended to provide a comprehensive guidance to game programming in Android, but an attempt to provide some clues to creating Android games with Java.


Tags: Java, UI, Android, threads, animation, game, bfxr, OGG




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel