What is better than creating simple funny games to learn the basics of Android development ? Today, you are going to learn how to use the Android Animation API by recreating the game “Spin The Bottle”.
Most of you know this game, but, for those that don’t know it, I’m going to present you its simple concept : Spin the bottle is a party game in which several players sit/stand/kneel in a circle. A bottle is placed on the floor in the center of the circle. A player spins the bottle, and must kiss the person to whom the bottle points when it stops spinning.
With our application, it is not necessary any more to have a real bottle, you will just need a smartphone. And it’s great because everyone has always a smartphone on him nowadays.
First step is to find two specific images : one for the floor which will be defined as background of the game and an other for the bottle which will be rotated during the game.
We have chosen to use these both images :
- Floor image for the background
- Bottle image
Creating the User Interface
Now, we need to define the layout of our game “Spin The Bottle”. We have a Relative Layout with the floor image as background and we add a bottle in the center of this layout :
Writing the Java Code
The next step is to write the Java code of the Main Activity. First, we get references for the views. Then, we install a click listener on the main layout of the Main Activity. Thus, the user will just have to touch the screen to spin the bottle and to start the game.
The core of the game is in the spinTheBottle() method. We are going to define a RotateAnimation from start angle to end angle centered on the center of the bottle. The end angle will be defined randomly to simulate really the game “Spin The Bottle”. We should store the last end angle value to restart the bottle in the same position for the next turn of the game.
The Code of the Main Activity will have the following form :
“Spin the Bottle” in Action
Now, we canottle test our “Spin the Bottle” game implementation. You should see the following screenshot on your Android device :
If you want to go further, you can discover this tutorial in video on YouTube :
Finally, if you want to test directly the result of this tutorial, you can try “Spin the Bottle” on the Google Play Store. It is exactly the same application we have created in this tutorial :