You are on page 1of 38

ANDROID GAME DEVELOPMENT

..RACE FOR FUN'


A project report submitted in the partial fulfillment
of the requirement for the Degree of Bachelor of Technology
ln

COMPUTER SCTENCE & ENGINEERING


by

Jwngsar Brahma (Roll No. Gau.-C-12164)

Pritam Kumar (Roll No. Gau.-C-lll47)

Under the supervision of

Mr. MithunKarmakar

Assistant Professor

Department of Computer Science and Engineering

D F],PAR]" j!| liN]. o F ('ol{ PU.I'ER S(] t t]]\C [] & ENG IN E E R I NG

aa*q ffiffi qf*ra oiim-Ergrg


CENTRAL INSTITUTE OF TECHNOLOGY KOKRAJHAR
(A Centrally Funded Instihrte under Ministry of HRD, Govt of India)
:: 783370
BODOLAND TERRITORIAL AREAS DISTRICTS:: KOKRAJHAR :: ASSAM

June 2016
DEPARTMENT OIT COIUPT}TER SCIENCE & IIYGII\EERING
d?r ffiqfsqryer fu
CENTRAL INSTITUTE OF TECHNOLOGY, KOKRAJHAR

(An Autonomous Institute under MHRD)

Kokrajhar - 783370, BTAD, Assarn, India


CERTIFICATE OF APPROVAL

This is to certiff that the work contained in this project entitled Android Game
Development "Race For Fun" submitted by Jwngsar Brahma and Pritam Kumar to the
Deparfrnent of Computer Science & Engineering is carried out under our direct supervisions
and guidance.

The project work has been prepared as per the regulations of Central Institute of
Technology and this project work has been accepted by the External E:raminer in partial
fulfillment ofthe requirement forthe degree ofBachelor of Technology.

Date: 29106/2016
z2
-(fJn-P \t
o"'
t,/ rnr\t
A ,nl M\il
hdr. SanJibNarzffiy Mr. DharaniKanta Roy
HoD(i lcl Project Co-ordinator

External Examiner
T

l)tLl),{RT'\l["n*"l'{)F- C0illPIj'l'ilR S('Ilrl,\,(,f: & hl]iCIl{F:[':Rl,niG


\r
cDqFl-{T ffi @
"fg?Tr"ry
CENTRAL INSTITIJTE OF TECHNOLOGY, KOKRAJHAR
(An Autonomous Institute under MHRD)
Kokrajhar - 783370, BTAD, Assam, India

CERTIFICATE

This is to certiff that the project work entitled Android Game


Development "Race For Fun" submitted by Jwngsm Bratrma and Pritam Kumar
to the Department of Computer Science and Engineering of Central tnstitute of
Technology, Kokrajhar has been examined and evaluated.

The project work has been prepared as per the regulations of Central
Institute of Technology and qualifies to be accepted in partial fulfillment of the
requirement for the degree of Bachelor of Technology.

tl nre

IVIr. MithunKarmakar

Project Guide

Assistant Professor CIT, Kokrajhar


ACKNOWLEDC I\ffiI\II

We are the student of Central krstitute of Technology, Kolaajhar


Department of Computer Science and Engineering expresses our thanks to our
project guide for allowing us to do the project on Android Game Developmmt'

o This project work has been the most exciting part of _our learning
experienie, which would be an asset for our future carrier. No system is
created entirely by m individual. Proper organization of concept and
analysis of ttre ryit *
is due to keep interest and helping hand of our
teachers and colleagues.

. Moreover we are very much grateful to ou parents for their support and
unconditional help, which made orn project a real success.

o Specially thanks to,

Mr.MithunKarmakar

Assistant Professor, DePt. of CSE

By

JwngsarBrahma(Gau-C- 12 I 64)
Place: CIT, Kokrajhar

Date:2910612016 PritamKumar( Gau-C' | | | 47 )


-l!

ABSTRACT

Race for Fun (PiFF) is a Helicopter Racing Android Game. It includes a


virtual environment for player to race, explore, have fun and learn codes to
accomplish the task of the game. By this game, we can reduce the extra times of
our duty and sometimes boring times. This project is based on Java
programming using Android Studio and the basics of Java. If any Android
Users wants to play the game, they can download from Google Play Store and
after installing they can enjoy the game.

t';l
,rl,
I
pEqI",AB^{TrON

. We certiff that the worked contained in this project has been done under
the guidance of our supervisor. This work has not been submitted to any other
institute for any Degree or Diploma. We have followed the guidelines provided
by the krstitute in preparing the project work.

p""f* Baohr^pq Trikaryyl kU/^ry\^{ ,

JwngsarBrahma(Gau-C - 12 I 64) Pritam Kumar(Gau-C- I I 147)


List of Contents:

Chapter 1. Java, Android and Games

l. I why build games to learn to program?

1.2 Why Android and Java?

1.3 Android Studio

1.4 Installing Android Studio

chapter 2'. Getting starred with Android

2.1 Preparing Android Studio 7

2.2 Building the project 8

2.3 Exploring Android Studio l0


2.4 Android UI types L2

2.5 Layout Elements


\,
,, 'I
13

2.6 Life Cycle phases t4

2.7 Dividing our Game into Activities 15

2.8 Our first look at Java ls

2.9 Building and Installing our Garne l7


2.9.1 Creating an Emulator t7

2.9.2 Running the Emulator l8

2-9.3 Running our Game on the Ernulator t9

2.9.4 Building our Game l9

IlPagr
_-

Chapter 3: Gaming with Source Codes


3.1 Project Explorer 2l
3.2 Project Explorer 22

3.3 Game Menu 24

3.4 Creating the Game Loop with Codes 2s

Chapter 4

4.1 Conclusion 30

4.2 Future work 30

4.3 References 31

2l P a g r:
ChaPter I

Why Jav4 Android and Games [2]

Welcome to Learning Java by Building Android Games, which I hope is just the beginning of
our exciting journey Into designing and writing games. We will learn everything from using the
standard AndtoiA User InteifacJ tutl designer to creating smooth animations by plotting
individual pixels. By the end of the report, we will be able to design and implement our own 2D
Android games, to sell or just to give away, on Google Play.

1.1 Why buitd games to learn to program?

Fun, of course! But there are other reasons too. Successfully running any program we have
written is immensely satisffing, even more so when it involves using some code that we
previously didn't understand.
But making our own games, as we will soon realize, creates a feeling of pleasure that is
not easy to descr6o-it haslo be experienced. Then there are added bonuses of sharing our
creations with friends on a phone or tablet or even sharing them publicly on the Google Play
Store and we might realizethat once we start making games, we can't stop'

The learning outcome priority will always be the Java programming concept, followed by
understanding the Android environment and $tme design principles. ryavi18 said that we will
closely.ru*in. and practice plenty of Android and game programming fundamentals'

1.2 Why Android and Java?

A part of successful learning is the commitment by the student, not just to do the work but in
their belief that they are doing the right thing in the right way. So many technology-based
courses and books don't get that commiftnent from the reader, not subconsciously anyway.

o Android is the fastest evolving and growing OS ever


At one time, Android updates emerged almost every two months. Even now, they emerge about
once in six months. By comparison, Windows takes years between versions and even iOS
updates come only yearly and usually change relatively little between versions. Android
is

obviously evolving and improving at an unprecedented rate.

3lPag0
The first humble version of Android was released in 2008, around the same time when
consumers were already quite excited about the then much flashier iPhone. News
stories were
also reporting that developers were getting rich by selling apps in the iTunes
app store.

o Android developers have great prospects


Now we might have picked up this project just for the fun and satisfaction that comes with
learning to program gur.r. But if we decide to develop your leaming further, you will
find that
the demand for Android programmers is enormous and therefore very lucrative too.

. Android is open source

What open source means is that although Google develops all the flavors of Android
that are
used on the newest devices, once the codi is released, anybody can do whatever
they like with it'
Google only exerts control for a limited amount of time.
out
In practice, most Android users have the pure Google OS or the modified versions turned
taking the
by big manufacturers such as Samsung and HTC, but there is nothing to stop anybody
OS and changing, adapting, or converting it into whatever they like. In shoG Android
could
never be taken away from the programming community.

. Java is not just for Android

Java has been around a lot longer than Android, since the beginning of the
1990s in fact'
Although what Java has been urrd fot has evolved and diversified over more than two decades,
the orifrnally implemented strengths of the language itself remain the same
today.

Java was designed to be platforrn or computer-independent. This is achieved by


the use
the Java
of a virtual machine (VM). This is a program written in another language that decodes
program that we write and interacts with the computer platform it is running on. So as
long as
there is a VM for the computer you want to run your Java program on, with
a few caveats, your

Java program will work. so you learn Jav4 you are learning a language that is used
if
everywhere from the smart fridge to the Web and most places in between'

r Java is fast and easy to use

There is a decades-long debate over which language is the best overall or which
language is the

best to learn programming. Critics of Java will likely say things about Java's
speed. It is true that

the Java memory management along with the VM interpretation process does
have some speed
cost. However, these things have benefits; they siguificantly improve our
productivity and the
penalty' And
way that the Android VM interacts with a device largely negates the minor speed

4lPage
since Android 4.4,it does so completely with Android Run Time (ART), which installs apps
games in a
written in Java as fully native applications. Now Java programmers can build
fnendly, interpreted language and have they ntn as if they were written in a more challenging

natively compiled language.

1.3 Android Studio:

and uses the JDK


We leamed that Android Studio is a tool that simplifies Android development
you use instead of
to allow us to write and build Java programs. Thttt are other tools can
extremely popular
Android Studio. There are pros and cbnJin them all. For example, another
can be made
option is Eclipse. And as with so many things in programming, a sfong argument
you will
,, to *ty you should use Eclipse instead of lndroid StoAio. I use both, but what I hope
love about Android Studio are the following elements:

a) It is a very neat and, despite still being under development, a very refined and clean
interface.
tools that
b) [t is much easier to get started compared to_Eclipse because several Androidpackage,
would otherwise n ed to be installedieparately are already included in the
product called IntelliJ
c) Android Studio is being developed byGoogie,-based on another
IDEA. There is a chanJe it will be the standard way to develop Android in the
not-too-
distant future.

1.4 Installing Android Studio:

So without any delay, let's get Android Studio installed and then we can begin our first game
prq..t To do this, tet's vislt https://developer.android.comisdk/ installing/studio'html'
studio download'
1. Click on the button labeled Download Android Studio to start the Android
to the one you just
This will take you to another web page with a very similar-looking button
clicked on.
by clicking on the
2. Accept the license by checking in the check box; commence the download
for download to
button tabeled Download Android Studio for Windows, and wait
the
the current latest
complete. The exact text on the button will probably vary depending on
version.
android-studio-
3. In the folder in which you just downloaded Android Studio, right-click on the
end of your
bundle-l35.12a65-windows.exe file and click on Run as administrator.'The
your operating system'
filename will vary depending upon the version of Android Studio and
4. When asked if you want to Altow the following program from
an unknown publisher to
on Next'
make changes to your computer, click on Yes' On the next screen, click

5lPage:
5. On the screen shoum in the following screenshot, you can choose which users of your PC can
use Android Studio. Choose whatever is right for you as all options will work, and then click
on Next:
l

Orc hrr st:r


Choos. for y*ich !F3 torr wmt b |rd Indoad Sndo. .U

Schct *r.dr lor rsrril b fird ldod StS fu tqrrcf r fur J rrr d nfr ugrF
(5D|( ibEe:r uN nccd to nn s ft!& mr.) C|dt itrt b srtlnl,

l'-.1trad frr rrg:r.fig n* qfir


ii:,lru*dgrtforht

rilifi

6. tn the next dialog, leave the default settings and then click on Next.
7. Then on the Choose start menu folder dialog box, leave the defaults and on Install. click
8. On the Installation complete dialog, click on Finish to run Android Studio for the first time.
9. The next dialog is for users who have already used Android Studio, so assuming you are a first
time user, select the I do not have a previous version of Android Studio or I do not want to
import my settings checkbox, and then click on OK.

,l

Yql crr ltrft yorr 3ltUr6 from a fador^ls vtrsn of Ar#d Strdo.
i.- ) I wdrt b iiport my scttner from a arsbn locati't
Secdfy drfrg fddcr s ltdrfion tnrl of ti: trryior3 vcrdon of Andod Strdo:

uL*id:U[ijismrtifi gI ffi H*Si$-er-ffi f-d#


o(

6lPage
Slrpnter 2

Getting Started with Android


In this chapter, we will take a roller coaster ride through all the Android topics that we need to
learn in order to get started with Java. It won't just be theoretical though. Wewill be designing a
User Interfac" ruU of a game menu and we will see and edit our first Java code as well'

In addition, we willsee how we can run our apps tn either an Android emulator on our
PC/]vIac or on a real Android device if we have one.

In this chapter, we will:


a Start our first game proJect
a Explore Android Studio
a Use the Android Studio visual designer to make our game UI
a Learn about strucfuring our code for Android
o Take our first look at some Java code
o Build and install our game on an emulator and a real device

2.1 Preparing Android Studio [11

Sowith Android Studio and Java installed, we just need to add the latest versions of the Android
API that we will use to make our first game. Here is what to do to install the API:
1. From the menu bar at the top of the Android Studio UI, navigate to Tools I Android I SD-K
Manager. Scroll down in the Android SDK Manager window and select the checkbox for
Android 4.4.2 (API19).

2. Click on Install Packages.

click on the Accept license checkbox and then click on the Install button.
3. On the next screeno
Android Studio will download and install the appropriate packages.

TlPag*
2.2 Building the Project

l. Click on New Project... as indicated in the following screenshot:


'&i Ad"tidgtrdo

m
[V] N'*e'"r"t"
| I

Iflt knporterejs6...

2. the Create New Project configuration window will appear. Fill in the Application name
field with My Game and Company l)omain with pepsi.com (or we could use vour own
Gompany website name here), as shown in the following screenshot:

Conllgun you? ne{y pmfct

Arpftrtinr nrrnc $Gocx


iompcryOo.ilin: pcpti.iom

P!<frgilmc .:'.. ;:.

P,'clrliecriica F.',t\'Canul

ing$ {-d

3. Now click on the Next button. On the next screen, check that the Phone and Tablet checkbox
has a tick in it. Now we have to choose the earliest version of Android we want to build our app
for. Go ahead and play with a few options in the drop-down selector. However, the trade-off here
is that the earlier the version we select" the fewer are the cutting-edge Android features available
in our apps. A good balance is to select API 19: Android 4.4 (KitKat). Go ahead and do that
now as shown in the next screenshot:

8li];.:u;.-
_n

I|
tr

4. Click on Next. Now select Blank Activitv as shown in the next screenshot and click on Next
again:

n il
l1

. Iliil
il
mm
n
t:i!i
'

*ffi'

"iotit t
?

aal, {-.'!', t.r


riir,j

E:'H trr"$|.$l fi)sir i+{* ni trtr,*t l,if&a1'

il n
,t!tt. K .Y!

5. On the next screen, simply change Activity Name to Game and click on Finish.

glPage
n .i.r-ir"ff'
i1a.rtlr6 ,1.4.iFrF

lrb

r.,:. {!.{
#r&rrraf

6. Clear Tip of the day by clicking on Close.

2.3 Exploring Android Studio:

Android Studio is a very deep tool, but it is only necessary to learn one part at a time in order to
get started. What might be useful for us is naming a few parts of the UI so that we can refer to
them easily. Take a look at this numbered diagram and a quick explanation of some of the key
parts of Android Studio. If we can, try and memorize the parts to make future discussions of
them easier for us.

' lrr&rr;f q
4
" Frb-rc cleas 5

10fi,
Here is a handy table that you can quickly refer to and remember which part of Android Studio
we are referring to. What follows is a more detailed explanation of each area.

Numtrer Name
1 Project Explorer
2 The editor
3 Menu bar
4 Toolbar
5 Navigation bar
6 Important tool
windows

. lroject Explorer (1):


This is shbwn as I in the screenshot and is a bit like Windows Explorer. It shows us all the files
and folders that have been generated for our project We will do a number of things from here as
the book continues. Actually, if we delve into the files and folders that Android Studio creates,
the Project Explorer is not an exact mapping. It is slightly simplified and highlighted to make
managing and exploring our project easier.

r The Editor(2):
As the name suggests, we will edit our Java code files here in the editor. However, as we
will soon see, the Editor window changes depending on the type of file we are editing. We will
also be viewing and editing UI designs here.

r Menu bar (3):


Like most programs, the Menu bar gives us access to the full functionality of Android Studio.

o Tool bar (4):


This contains lpts of really useful one-click options to do things such as deploying and
debugging our games. However the mouse cursor over an icon to get a pop-up tip and gain
greater insight into each toolbar icon.

. Navigation bar (5):


Like a file path, this shows exactly where the file that is currently in the editor is located within
the project.

11 lPage
. Important tool windows (6):
These are a number of tabs that can be popped up and popped down again by clicking on them.

2.4 Android tII types

We will now take a whirlwind tour of some really useful Android UI elements, a few key
properties, and how to add them together to make a UL These will introduce us to some of the
possibilities as well as how to use them. We will then quickly use what we know to make our
menu.

TextView:

On the visual UI area, click on the words Hello world! What we have just selected is a widget
known as a TextView. TextViews can be small text like this one or large heading type text,
which might be useful in our game menu.
Let's try dragging and dropping another TextView onto our visual UI:

l. Directly under the Widgets heading in our palette, you can see there are multiple types of
TextView. They are presented in the palette as Plain TextView, Large Text, Medium Text
and Small Text. Drag and drop a Large Text widget onto our visual design. Don't let go
straightaway. As you drag it around the image of the phone, notice how Android Studio
graphically shows you different positioning options. In the following screenshot, you can see
what the designer looks like when the widget being dragged is positioned at the center:

12 | P rl f {l
2. Let go of the left mouse button where you want the widget to go. If you let go when it is
positioned as shown in the previous screenshot, then the text will appear in the center as
expected.
3. Now we can play with the properties. In the Properties window, click just to the right of
textSize. You might need to scroll to find it. Type 100sp as the value and press the Enter key.
Notice that the text gets much larger. We can refine the size of our text by increasing and
decreasing the value entered here. The unit sp stands for scaled pixels, and is simply a measuring
system that attempts to scale the text to an appropriate equivalent actual size across different
screen densities.

4. fhy with some more properties if you like and when you're done, click on the TextView we
just created in the visual designer to highlight it. Then tap on the Delete key to get rid of it. Now
delete the TextView that was present when we started-the one that says Hello world!

2.5 Layout elements

Now we have an apparently empty screen. However, if we click anywhere on the design
preview, we will see that we still have some options in the Properties window. This element is
called a Relativelayout. It is one of several layout element types provided as a base to contol
and align the layout widgets such as buttons, text, and so on. If we look at the top of the Palette
window, we will see the main layout options. We will use this layout element when we actually
build our garne menu in a moment.

ImageView Widgets:

ImageViews unsurprisingly are for displaying im4ges. In the standard Android UI, this is a really
quick way to add our designers'artwork to our game:

1. Drag and drop an ImageView element onto the design in the same way as you positioned
the TextView a moment ago. The ImageView element can be found below the Widgets heading.
Now position it centrally as before or play with the options by dragging it around the design. We
will delete it in a minute; we are just having a bit of an exploration before we do this for real.

2. In the Properties window, select the src property in the same way as you selected the
textSize property previously.

3. Notice that after you select it, you have the option to click on ... to give you more options.
Click on ... and scroll to the bottom of the list of options. These are all the image files that we
can display in this ImageView. Just for fun, scroll to the bottom of the list, choose icJauncher,
and click on OK. We can make any image we like available and this is a simple, powerful way
to build an attractive game menu screen.

13 lPage
/' i..,

4' change the layout;wjdth property to.l5Odry and the layoufiheight


properry to l50dp. The unit
dp is a way of sizing elements attd-*iagas itlot t*ui#rehtivefi
rJn*t!"i'*ross devices with
scr@ns that have very different numbers of pixels.

5' Delete the lnageview in exactly the same way as you


deleted the other views previously

ButtonView :

The use of Buttonvlt* probably gven aruay by its


lt name. Try to click and dragafew buttons
onto our layout. Notice that there are a ferv types of ButtonView,
such as Snalt Button, Button,
and' if you look further down the lYidgei iirt, rr"geiotton.
we will be using the regular
ButtonView, labelled simply as Button.

2.6Life Cycle phases

The Android system has different phases ful*I etven app can be in. Depending on the phase,
the Android system determines how the app is uiri"a
btthr user or whether it is viewed at all.
Android has these phases so that it can aeciae which urri, it in
current use and then allocate the
right amount of resources such as memory and proceiring po*rr.
But also allow us as game
developers to interact with these phases. what ii someone quits
our game to answer a phone
call? Will they lose their progress?

Android has a fairly complex system that, when simplified a little


for the purpose of
explanation, ensures that every app on an Android ievice is
in one of the following phases:
. Being created
o Starting
r Resuming
o Running
. Pausing
o Stopping
o Being desfioyed

14fPage
2.7 Dividing our glme into activities

The Java code that we write will be divided into sections or parts called activities. We can think
of activities as different screens for our game.For example, during the book, we will often create
an activity for a home screen, an activity for the game screen and an activity for the high score
screen.

. onCreate: This mettrod is executed when the activity is being created. Here we get
everything ready for the game, including graphics, sound, and perhaps the high scores.

. onStart This method is executed when the app is in the starting phase.

onResume: This method runs after onStart but can also be entered, perhaps most
logically, after our activity is resumed after being previously paused. We might reload a
previously saved game situation when the app had been intemrpted, perhaps by a phone
call or the user running another app.

onPause: This occurs when our app is pausing. Here we might want to save the current
game. You are probably getting the hang of these methods.

onStop: This relates to the stopping phase. This is where we might undo everything we
did in onCreate. If we reach here, our activity will probably get destroyed sometime soon

onDestroy: This is when our activity is finally being destroyed-our last chance to
dismantle our game. If we reach here, we will definitely be going through the phases of
the life cycle from the beginning again.

2.8 Our first look at Java

This is the code that will bring our game menu to life. Let's take a closer look. The very first line
of code in the editor window is this:
package com.pepsi.mygame;

To see the next four lines of code, we might need to click on the small * icon to reveal
them. Android Studio tries to be helpful by simpliffing our view of the code. You can expand
and collapse them to suit ourselves without affecting the functionality of the program. This is
shown in the following screenshot:

15 lPage
paclage con. p€p3i. ilyg8ilt

1 i4rort .,,
public clasg Grne ertanrds lcslvlcy I

Once we have expanded the code, we will see these four lines:
paclagp cot!. papri . Eygcct

tryort aadroLd. app.lcrlvisyt


iqlort android. os. Bundle;
iryrort andro iC. vier. lleau;
iqrort android. vieu.l{csulten;

The next line introduces a fundamental building block of Java known as a class. Classes are
something that we will continually expand our knowledge and understanding of throughout the
book. For now, take a look at this line of code, and then we will discuss it in detail:

pub,lic class MainActivity extends ActionBarActivity {


The preceding line is saying: make me a new public class called MainActivity and base it upon
(extends) ActionBarActivity.

Moving on with the code, let's look at what the code that is contained within our class actually
does.

Here is the code chunk directly after the crucial line we have just been discussing:

@Override
protected void onCreate(Bundle savedlnstanceState) {
super. onCreate(savedlnstanceState) ;
setC ontentView(R. layout. activity_main);
)

The @override word says that the method ttnt follows next is being overridden. The
protected void onCreate(Bundle savedlnstanceState) { line contains the method we are
overriding.
The somewhat odd-looking protected void before the method name oncreate and (Bundle
savedlnstanceState) after the method name are unimportant at this time because they are handled
for us. It is to do with the data that travels between various parts of our program.

Let's move on to the line:

super. onCreate( savedlnstanceS tate) ;

Here, the super keyword is referencing the code in the original onCreate method, which is
still there even though we can't see it. The code is saying: even though I am overriding you, I

16 lPage
want you to set things up, just like you normally do first. Then, after onCreate has done loads of
work that we don't see and don't need to see, the method continues and we actually get to do
something ourselves with this line of code:

setC ontentView(R. layout. activity_main) ;

Here we are telling Android to set the main content view (our users screen), which is the cool
game menu we created eadier. To be specific, we are stating it is an R or resource in the layout
folder and the file is called activity_main.

2.9 Building and Installing our Game

Before we do that, we need to find out how to use the Android emulators and how to build our
game. Then we will put these together and put our game into an emulator or real device to see it
as our players would

Emulators and Devices:

Now we have the first part of our game ready to nrn. We need to test it to check for any elrors,
crashes, or anything else turintended. It is also important to ensure that it looks good and runs
correctly on the device typeVsizes and that we want to target.

2.9.lCreating an Emulator

Let's get our emulator up and emulating:

l. On the right-hand side of the Android Studio quick launoh bar, find the AVD manager
icon:

Rgn looh VCI ffirudow Hdp


iE i:ff-,gdiJl } fi{ F:i::, &. $e ffi S ffi I ,*, ?
2. Click on the icon to start the Android Virtual Device Manager. Then click on the Create
Virtual Device... button on the bottom-left side to bring up the Virtual Device Configuration
window.

lTlPage
3. Now click on the Nexus 4 option and then click on Next.

4. Now we need to choose the version of Android we will use to build and test our games on.
The latest version (at time of writing) is Lollipop - 2l - x86. It is the only option where we don't
need to complete a download to continue. So select it (or whatever the default is at the time you
are reading this) and then click on Next to continue.

5. On the next screen we can leave all the default settings. So click on Finish.

2.9.2 Running the Emulator

Now we will launch (switch on) our virtual device then actually run ow game that we made
earlier by performing the following steps:

1. Click on Nexus 4 API2l under the Name column. Now click on the triangular play icon
to the right of the description of our emulator.

2. Once it has started, unlock the device by clicking and dragging anywhere on the screen of the
emulated device. This is analogous to swiping to unlock a real Nexus 4. Here is what our Nexus
4 virtual device looks like when it is running and unlocked:

We can play with this emulator in almost the same way as you can a real Android device.
However, we cannot download apps from Google Play. We might notice that the emulator is a
bit slow compared to a real device, wen compared to an old one. Shortly, we will look at
running our apps on a real device.

18 lPage
2.9.3 Running our Game on the Emulator

Once the emulator is running, it's usually best to leave it running so that each time we
want to
use it; we don't have to wait for it to start. Lefs use the emulator:

l. Launch the emulator if it is not already running and make sure the device is unlocked as
described previously.

2- Click on the run icon in the toolbar (shown next) to run your app. You can achieve the same
thing by navigating to Run I My Game from the menu bar:

Ielrfr ,vc$ !fiind-Ag


3HR-*"lr #{

3. Rfter a pause while Android Studio builds our application, a pop-up dialog will ask you which
device you want to run the app on. Choose the device with Nexus C lpfZt in ttre dlscription.
This is the already running device that we created earlier. Now press Otr(

4. N,otice at this point that the useful Android window appears at the bottom section of Android
Studio' In the unlikely event of you having any problerns, just check for typos in the code. If
things really don't work out, just go back to the using the sample code sectionio rorp*r with or
copy and paste the supplied code.

2.9.4 Building our Game

To run our game on a real Android devicg we need to create a .apk file, that is, a file that ends
with the extension .apk. A .apk file is a compressed archive of filei and folders that the Android
system uses to run and install our app. These are the steps to use Android Studio to make a .apk
of our game:
l. From the menu bar, navigate to Build I Generate signed ApK.

2. A slightly verbose window will pop up and say: For Gradle-based projects, the signing
configuration should be specified in the Gradle buitd scripts. You can safely dismiss this
window by clicking on OK.

3. Nefi up is the Generate Signed APK Wizard dialog. Here, we are creating a key that
identifies the key holder as authorrzedto distribute the APK. At the end of this process, you will
have a .keys file that you can use each time you build a .apk file. So this step can be missed out
in future. click on the create new button.

lglPage
4.
to-
In&e Key Store-Path
your key. You
ryq t'"" orprompted
will
go to a location on your hard drive where you would like
{ore then be to choose a filename for the keystore, Tt ir i;
arbitrary. Type MyKeystore and click on Otr("

5. Type a password in the Parsword field and then retype it in the Conlirm field. This is the
password to a store that will help protwt your key.

6. Next, in the Alias fiel4 type a memorable alias. You can think of this as a kind of username
91yog ttY. AgEin tlpe a password in the Parsword field and then retype it in the Confim
field. This is the possword to you key.

7. Leave the Validity Years dropdovm at tlre defautt of 25.

8. You can then fill out your Name and organization details (if any) and click on OK.

f.lgwour key and keystore are complete, and we can click on OK on the Gener,ute signed
APK wizard dialog.

10. We are then prompted to select Run Proguerd. Encryryting and opimizing
ogr .apk is
unnecessary at this time. so just click on Finish to gcnerate our app's .apk filel

I l. The generated .apk_file will be put in the same directory tbar you chose to put the project
files. For enample, MyGame/app.

20 f Page
ChaT'Z- tr

Gaming with Source Codes


3.1 Project Explorer ;

Project Explorer uftere An&oid Studio puts the tw'o new files it $eate for
us. I have highlight€d two folders in the next screenshot.

vh+
w fl mrnfcrr
*ffir*
s
Ytffi
HF'ra

t#sr t Brch$omd

ffi;ffi
t
ffi GunG

ffi:ffi
ffit rHG
#t HF
S t Saronqnfi
ffi t Top8ordu
.,'., * ,,fi frqldruidTest]
| fil rrr
fi
G
F trl*um$r
'|l
t ? E: tryqa
$ S rctr*y-g.illcrtnt
T
t SWrr*
F El rnrrnr
F HmFmry
F Erv*rcs
rir rl o 'r

There are two Epes of code files:

* Java code files in com.pepsi.mygame


S UI layout filesin layout

2I I P a g e
'i'll'1
" ril
]l
li
ii

3.2 Java code files


There are 12 typs of Java code files:
. Animation

. Background

. BotBorder
o Explosion
o Garne

. GameObject

r GamePanel

o MainThread

. Missile

. Player

o Smokeffi
. TopBorder

we have the following drawable type of png images:


. Brick

22 | P a g e
' Explosion

{; C. OCO
sa(}$s
ssss@
w9{Pryf
flt* L

. Helicopter

}Inff}t)j
. Light(for background)

23 lPaS{,}
crr;
*"
{n
{Ilr
$;
g
{tF;
qfln;
rm
ry'l
{fl":
trr:
fl;'
l-T-*-T-

3.3 Game IVIenu

24 lPage
3.4 Creating the Game Loop with Codes

l. Game

onCreate: when app is created and an activtty starts.

Turning title off:


requestWindowFeatu{W indow.FEAT URE _NO _TI TL E);

Setting the full Screen:


getWindowQ. setFlags(WindowManager.LayoutParam s. FLAG _F ULL SC RE E N,
Windowlvlanager. LayoutPamms FI-AG _F ULL SC RE EN);
.

Showing the content of the view:


setContentView(new GamePanel(this));

2. GamePanel
In this Java class, we will initialize all the Objects and Methods of different types of Java classes.

3. Backgrorurd

Initialization:

bg: new Background@itnapFactory.decodeResourclgdResources0,R.drawable./ight));


privafe int x, y, dx;
Here x, y is the coordinates of background i.e. of Width and Height. dx is a set vector.

public static final I*MOVESPEED: -5;


Slowly going to move offthe scrcen.

4. Player

Initialization:

player: new Playe(BitmapFactory.decodeResource(getResources0, R.drawable.helicopter),


65,25,3);

private Bitmap spritesheet ;


Here player is going to use the spritesheet.

25 lPage
f\1
\,!

For incrementing the score:

pubtic void updatd)


t
long elapsed = (q#!m. nanTtn{l,effiTirc)/ 1000000;
if (elapse#I00)
{
scorgf+;
startTime = Systcm. nan oT im();
)
If player is playing:
i(player.getPlayingo
t
bg.update0;
player.updat{;
)
If player is not playing, tha thc hcliooper is going to be doum:
if (went getActionfi*tiloti mEvmIACTION-DOWN)
{
if (lplayer.getPlayingQ) r
{
player. setPlaying(true) ;
)
els€
t
player.setUp(tnrc);
)
returntrue;
jr

5. Smokepuff

public void updareQ


{
x-:10;
)
Here the smokepuffhas a s@ of negative 10.

To initialize the smokepuff:

long elapsed : (System. nanoTimeQ - smokeStartTime/l 000000;

To update the smokepuff:

26 lPage
t'I '-?

if (elapsed>I20)
{
smoke.add(new Smokepuflplayer. get{), player. gety(F I 0));
:
smokEStartTime System,nunT in d);
)
To remove the smokeprfffrom ffre scre€n:
"

for (int i = 0; i<smoke.sizd); ir+)


t
smoke.ge(i).updat{);
if (smoke. ge(i). gctxQ€ 1 91
{
smoke.remove(i);
)
)

The smokepuffconsists of three littlo circles:

canvas.drarryCirc(r-r+2, y-t-2, r, patnt);


canvas.drawCircle(x-rr4, V-Fl, r, paint);
I

6. Missile

Speed of the niissile:


speed :7 + (int) (rand.nextDoubleQ * score / 30);

Here the range of the missile is base 7 with random number between I to 30 over score 30.

For the each element of the ray of each missiles:

for (int i :0; i < image.lengtfu i++1


{
imagetil : Bitrnap.cr eateB itnaf,spritnsheet, 0, i * height, width, height);

Add missiles to timer:


long missileElapsed : (System. nanoTime(FmissileStartTime/l 000000;

First missile is always goes down to the middile:

if (missiles. size(|:0)
{
missiles. add(new Mssi(Bim apE afiory .decode Resour c e(getkesourcesg,

iitpase
R.drawable .misstA,WIDTH + 79, HEIGH Tl2,4S, ! S,player. getScoree, I 3));
.)
Loop through every missile:

for (int i:0; i<missiles.sizee; i++)


tt
missiles. ge(i). updar{;
if(collisi on(missiles. gn(ilplayer)
{
missiles.remov{i);
player. serplayine(false);
break;
)
if (missiles. ge(i).eeO()<_ 1 00)
t
missiles.remove(i);
break;
)
)

collision method between ga'e object a and game object b:

public boolean collision(Gameobject a, Gamcobject


b)
{
i\Rect. int er s e ct s (a. getRectangl_ {), getRectangleQ))
b. s _\rrt
t
return true;
)
refurn false;
) I

7. Borders: Topborder and Botborder

Topborder:
publlc TopBorder@ifinap res, int x, int y, int h)
{
height: h;
width:20;

this.x: x;
this'Y: Y;
:
dx Gamep anel.MOVESp E ED ;
:
image Bitnap.createB itmap(res, 0, 0, width, height);
)

28 | P a g e
Botborder:
. public BotBorde(Bitnap res, int x, int y)
t
height =200;
width:20;

this.x: x;
this.y: y;
dx : GamePanel .MOWSP EED;
image = Bifrnp.cr wteBitnry(res, 0, 0, width, hei ght);
)

8. Explosion

Updat€ and Draw the player:


public void draw(Canvas canvas)
{
if ( ! animation. playedOnceQ)
{
canvas. drawBifinap(animation. getlmageO, x, y, null);
)

publicvoid u@teQ
{
if ( ! animation. playedOnceo
{ l
animation.updat{);
)
)

29 lPage
Chaots 4

4.1 Conclusion

Based on the fact that RFF offers a good interactivity with existing functionality, I can assume
ttnt it can have a good chance to grabs many useni. This project is designed to mest the
requirements of Android Game. It has been developed in Android Studio database using Java
Programming Language. It is a game to do explore and have fun.

In this project we have done:

. Collection of alt information aboutAndroid Gamp

Java codes while developing the Game

The game has been build and test it out

4.2 Future Work

The work in the firture that we bave to eng4g€ should be done with lessons we learned from the
project work that we bave done so far. We should be able to reduce the errors that we have
identified all through the time we spent for the project and that should be included with the
experience we gathered but with a hidr standard.

If we want to be a Java ernployee, that is, working full time with a professional capacity
for a medium or large company, then you will probably need a college degree and this project
hopefully has given a glimpse into the world of programming and Java itself. If we compare our
gam€ with other garnes, then we still have more of learning to do. Thus I would like to go with
the building of bigger and better games.

30 lPage
4.3 Referenccs:

Books:
1. John Horton, "Learning Java by Building Android Games'", 2OIS,PACKT publishing
2. Herbert Schil& "Java: A Beginne/s Guide", 66Editioq2}l4,Oracle press
3. Learn Java for Android Dwelopme,lrtu,20l1,Apress
4. J.F. Dilvlarzio "Android A programmu's Guide", 200 g, McGraw-Hil
5. Mark L. Murphy "Android Prograrnning Tutorial', Edition 3,2011, CommonsWare

WorldWideWeb:

httpp : //dgvploper. ardroi4. conr/studip/rqdex. hfirrl

?133 ls.s,html

Studio/

htto:/

31 lPage
'(.,{ume1eC
Isr}ueJ) uollu}S os?g 'e

puB 'sapoN Josuas I


:slueuoduroc urutu oAuJo lsrsuoc NSA\ orlJ

StrIOflIUITY Z'I

'eere p8rel e{greAoo o}.sapou.

Jo roqumu eErel;o posodruoc eJ? s{Jo^$eu rosues 'sopou Josues go sorlrcuduc remod ,no1
ol enp pa{ur1 sr sacrlop elrqout Jarpo ol puuduroc sepou rosues rog eEuer uo4?crrmtutuoc
pu? e8erono3 'olp?J rerrrod Arol pu" ,{rourour il"uts 'rossacoJd peppequa qlll\
secr^ep Josues peprsdo-fro$eq eJou Jo euoJo dn epuur eru $lJor$ou eql 'seJu luecgru8rs

? re^o ,{lesuep pomqursp sepou {Jo^uou o1w padnorE sacr^ep pcpuepl ozrsll?rus Jo
srruetu fq epou coq p€ ue ur dn 1es uago $oru $ (NSf$ ryo^$ou rosues sselerr/\A

{ro/ItleN rosues ssaloJlA\ :I't arn8rg

a8u.tols pe$qlqslp afe.np pe4lu.queJ a8uro5 peztle.qrral


'6urs sa Jo.rd 1lanqr.q^q I p ftnssarord pa4lequet ' Etussaro.rd palll qrt lsrp
' s.p srlts snoartaf,orap q 'sJosrE s snoor,nForapq '$.rostras snoatn8otuotl
'Jerl-!llrut 'pa.npnlJ .nr1€18rug 'luU rar;-a;Erng
(r) (q) (e)

? {n fl fl
qnq fl
afurolg
fen€fu8
f f o' # ff { fl
$sele.r^\ffil $ h
:

f ;f, *E flfl
N flt *il f -{l
.rosrtas.rslsrs
f, ogl
fl
Iostrrsi#'ll
I fl
rosrns olpnv
*
.rostr s mPlr\ fl
t t ll .{u.ua1up
w^
rnGtll
lj .f
aI

tr
qntl frnssero.rd o

srpeurrlFN {l fl
ONTCTT

ruts

s{ro/nFN rosues sseFrh ro1 lorolord 3VyU fmpg;3 ltuau3 JO ApnfS argereduro3

You might also like