Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Android Game Programming By Example
Android Game Programming By Example

Android Game Programming By Example: Harness the power of the Android SDK by building three immersive and captivating games

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Android Game Programming By Example

Chapter 2. Tappy Defender – First Step

Welcome to the first game, which we will learn about in three chapters. In this chapter, we will closely examine the goals for the finished product. It helps a lot when building a game, if we know exactly what we are trying to achieve.

We can then look at the structure of our code, including an approximate design pattern that we will be adhering to. Then, we will put together the code skeleton of our first game engine. Finally, to finish the chapter, we will draw our first real object from the game and animate it on the screen.

We will then be ready for Chapter 3, Tappy Defender – Taking Flight, where we can make really fast progress before completing our first game in Chapter 4, Tappy Defender – Going Home.

Planning the first game

In this section, we will flesh out exactly what our game will be. The backstory; who is our hero and what are they trying to achieve? The game mechanics; what will the player actually do? What buttons will he press and in what way is that a challenge or fun thing to do? Then, we will look at the rules. What constitutes victory, death, and progress? Finally, we will get technical and start to examine how we will actually build the game.

Backstory

Valerie has been defending the far outposts of humanity since the early '80s. Her brave exploits were originally immortalized in the 1981 arcade classic, Defender. However, after over 30 years on the front line, she is retiring and it is time to begin the journey home. Unfortunately, in a recent skirmish, her ship's engines and navigation systems were severely damaged. Therefore, now she must fly all the way home using only her boost thruster.

This means that she must fly her ship by simultaneously thrusting up and...

Building the home screen

Since we have done all the planning and preparation, we can get started with the code.

Note

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

To use the code files, you will still need to create an Android Studio project. In addition, you will need to change the package name in the very first line of code of each of the JAVA files. Change the package name to match the package name of the project you created. Finally, you will need to make sure that any assets such as images or sound files are placed into the appropriate folder in the project. All the required assets for each project are supplied in the download bundle.

Creating the project

Fire up Android Studio and create a new project by following these steps...

Coding the game loop

We said that we will not be using a UI layout for our game screen, but instead a dynamically drawn view. This is where the view of our pattern comes in. Let's create a new class to represent our view, then we will put in the fundamental building blocks of our Tappy Defender game.

Building the view

We will leave our two activity classes alone for a while so that we can take a look at our class that will represent the view of our game. As we discussed at the start of this chapter, the view and the controller aspects will be part of the same class.

The Android API provides us with an ideal class for our requirements. The android.view.SurfaceView class not only provides us a view that is designed for drawing pixels, text, lines, and sprites onto, but also enables us to quickly handle player input as well.

As if this wasn't useful enough, we can also spawn a thread by implementing the runnable interface allowing our main game loop to get player input and other system...

The PlayerShip object

We need to keep the model part of our code as separate as possible from the rest. We can do this by creating a class for our player's spaceship. Let's call our new class PlayerShip.

Go ahead and add a new class to the project, and call it PlayerShip. Here are a few quick steps on how to do that. Now, right-click the folder with our .java files in it and navigate to New | Java Class, then enter PlayerShip as the name and click on OK.

What do we need our PlayerShip class to be able to know about itself? As a bare minimum it needs to:

  • Know where it is on the screen
  • What it looks like
  • How fast it is flying

These requirements suggest a few member variables we can declare. Enter the code just after the class declaration that we generated:

private Bitmap bitmap;
private int x, y;
private int speed = 0;

As usual, use the Alt | Enter keyboard combination to import any missing classes. In the previous block of code, we see that we have declared an object of type Bitmap that...

Drawing the scene

As we will see, drawing a bitmap is really trivial. But the coordinate system that we use to draw our graphics onto needs a brief explanation.

Plotting and drawing

When we draw a Bitmap object to the screen, we pass in the coordinates we want to draw the object at. The available coordinates of a given Android device depend on the resolution of its screen.

For example, the Samsung Galaxy S4 phone has a screen resolution of 1920 pixels (across) by 1080 pixels (down) when held in a landscape view.

The numbering system of these coordinates starts in the top-left hand corner at 0,0 and proceeds down and to the right until the bottom right corner is pixel 1919, 1079. The apparent 1 pixel disparity between 1920/ 1919 and 1080/ 1079 is because the numbering starts at 0.

Therefore, when we draw a bitmap or any other drawable to the screen, we must specify x, y coordinates.

Furthermore, a bitmap is, of course, comprised of many pixels. So which pixel of a given bitmap is drawn at the...

Deploying the game

Now, we can run our game to see our spaceship floating through space (starting at 50 pixels on the x axis and 50 pixels on the y axis).

Android Studio enables us to fairly quickly create emulators, on which we can test our games on a development PC. However, even the most simple of games will not run well on an emulator. When we start testing things like player input, the experience is so awful that it is best to avoid using emulators completely.

The solution is to carry out debugging on a real Android device. It is very easy to prepare for this.

Debugging on an Android device

The first thing to do is to visit your device manufacturer's website and obtain and install any drivers that are required for your device and operating system.

The next few steps will setup the Android device for debugging. Note that different manufacturers structure the menu options slightly differently than others. The following sequence is probably very close, if not exact to enable debugging...

Planning the first game


In this section, we will flesh out exactly what our game will be. The backstory; who is our hero and what are they trying to achieve? The game mechanics; what will the player actually do? What buttons will he press and in what way is that a challenge or fun thing to do? Then, we will look at the rules. What constitutes victory, death, and progress? Finally, we will get technical and start to examine how we will actually build the game.

Backstory

Valerie has been defending the far outposts of humanity since the early '80s. Her brave exploits were originally immortalized in the 1981 arcade classic, Defender. However, after over 30 years on the front line, she is retiring and it is time to begin the journey home. Unfortunately, in a recent skirmish, her ship's engines and navigation systems were severely damaged. Therefore, now she must fly all the way home using only her boost thruster.

This means that she must fly her ship by simultaneously thrusting up and forward,...

Left arrow icon Right arrow icon

Description

The book is best suited for existing Android or Java programmers who want to adapt their skills to make exciting Android games. The book is also for determined readers who might have no Android, game programming or even Java experience, but a reasonable understanding of object oriented programming knowledge is assumed.

What you will learn

  • Build simple to advanced game engines for different types of game, with cool features such as sprite sheet character animation and scrolling parallax backgrounds
  • Design and implement genuinely challenging and playable levels
  • Implement the critical main game loop
  • Implement basic and advanced collision detection mechanics
  • Bring to life a challenging enemy AI
  • Make the math behind 2D rotation, velocity, and collisions simple
  • Run your game designs at 60 frames per second or better
  • Process multitouch screen input effectively and efficiently
  • Implement a multitude of other game features such as pickups, firing weapons, HUDs, generating and playing sound FX, scenery, level transition, high scores, and more
  • Implement a flexible and advanced game engine that uses OpenGL ES 2 for fast, smooth frame rates

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 30, 2015
Length: 388 pages
Edition : 1st
Language : English
ISBN-13 : 9781785286193
Vendor :
Google
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 30, 2015
Length: 388 pages
Edition : 1st
Language : English
ISBN-13 : 9781785286193
Vendor :
Google
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 152.97
Android Game Programming By Example
$48.99
Learning Java by Building Android Games
$48.99
Android NDK Beginner`s Guide - Second Edition
$54.99
Total $ 152.97 Stars icon

Table of Contents

12 Chapters
1. Player 1 UP Chevron down icon Chevron up icon
2. Tappy Defender – First Step Chevron down icon Chevron up icon
3. Tappy Defender – Taking Flight Chevron down icon Chevron up icon
4. Tappy Defender – Going Home Chevron down icon Chevron up icon
5. Platformer – Upgrading the Game Engine Chevron down icon Chevron up icon
6. Platformer – Bob, Beeps, and Bumps Chevron down icon Chevron up icon
7. Platformer – Guns, Life, Money, and the Enemy Chevron down icon Chevron up icon
8. Platformer – Putting It All Together Chevron down icon Chevron up icon
9. Asteroids at 60 FPS with OpenGL ES 2 Chevron down icon Chevron up icon
10. Move and Draw with OpenGL ES 2 Chevron down icon Chevron up icon
11. Things That Go Bump – Part II Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(9 Ratings)
5 star 66.7%
4 star 11.1%
3 star 22.2%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Rodger Jan 06, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
John Horton describes exactly how to write for Android and Java without throwing masses of unintelligible buzzwords at you. Each stage is carefully and easily explained and each new concept and word is explained in plain english. This does not mean that he doesn't teach in depth but only that he introduces the ideas as you need them to understand what you are doing. I have read and tried to follow many books and videos on android and John Hortons books have taught me more than any of the others.
Amazon Verified review Amazon
Guillermo Rodriguez Jul 17, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is excellent! It has a fresh, fun style, but at the same time it covers the topics of Android Game Development with technical depth and correctness It is a wonderful tool for every Android programmer.
Amazon Verified review Amazon
Hugo Oct 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I think the title is wrong, this isn't just a programming book, this is a complete game development course, the author starts by talking about what you will have at the end, them he introduces every game talking about the foundations not just code and result, you are introduced to good practices to achieve your game complete, it is fundamental in my opinion to have a project complete, the programming part is really good as he is presenting the critical points of the game structure in natural basis, you understand what he does because you understand the need of that code part. I think that the difficult of this book is between intermediate to advanced, but he made a book that everyone who wants to make a mobile game can start with solid basis. All the projects has its own focus and difficult level, I think they shown almost every feature you need to make a good 2d mobile game.
Amazon Verified review Amazon
jamie Jul 30, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Fantastic book and i would give 10 stars if possible! i have to disagree with another review i have seen about the book not being useful to developers at beginner level, although the book intro does assume you have some development knowledge it all depends on what you are looking to take from this book! i am practically new to android game development and needed to know more on game loops and sprites and i got this know how by reading this book and putting it to practice with the games made in this book so even from a beginners point of view i have to say that what i have took from this book has been a massive help towards my understanding of what it takes to get games built and running! java code in any book anywhere can seem daunting to all of us but by using examples i find it is the best method and by example is exactly what this book shows, if you still do not get whats happening in code then simply go over it again as with everything in life, things become clearer the more you practice.Before i read and used the examples in this book i was at a stand still with my games development and was annoyed with my self as was trying to take so much information in from a number of different sources it was really taking a toll on me but when i came accross this book it ticked all the right boxes and i am glad i gave my time to read this as all this time it was one source i really needed to focus on with the right information and it happend to be the best choice i made investing my time into this because it gave me everything i needed to know and more! i am now confident with my own looping and sprites, and much better ways of the headach i was having with fps, this book is not just good to give a once over! for me it is also an ideal reference book.The way the book has been written is very straight forward and informative this makes it easy to follow, you can copy and paste the code or download the code if you have a paperback copy however if your new to development and really keen to learn i find that by writing the code myself gives me that bit extra of my learning progress and comes across clearer then copy and pasting chunks of code.I hope this book helps you all as much as it has helped me, if your really serious about android games development then you can never have enough learning books, i do highly recommend to add this to your front collection.thank you to John Horton and also to Packt for this book being here today! i had almost given up so for this i am truly thankful and will look out for more books from you in the future should there be any.Jamie LoweGames Developer in the making.
Amazon Verified review Amazon
Thomas Möller Aug 15, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Der Autor erläutert die Spieleprogrammierung auf Android-Geräten anhand von drei 2D-Spielen. Diese Rezension bezieht sich nur auf die ersten beiden Spiele. Das dritte Spiel (Asteroids mit Nutzung von OpenGL ES 2) habe ich bisher noch nicht durchgearbeitet.John Horton nutzt für die Spieleprogrammierung keine UI-Elemente des Android Betriebssystem (wie z.B. Button, Layout, Textfields usw.) und benötigt daher keinen Rückgriff auf die mit den Activities assozierten XML-Dateien. Daher braucht man keine weiteren Kenntnisse über die Android-UI-Bibliotheken, was recht entspannend ist.Alles wird im Android-Canvas (eine Art Leinwand, die später im Spiel die Displayanzeige darstellt) direkt in Java programmiert.Der Autor entwickelt im ersten Spiel eine Game-Engine, die gut funktioniert und sich auch leicht auf eigene Spielideen übertragen lässt.Im zweiten Spiel (Run & Jump) wird die Game-Engine dann erweitert und verwaltet zahlreiche Grafikobjekte, mit denen der Spieler auf verschiedene Weise interagiert. Dazu kommt noch ein mehrstufig scollender Hintergrund, der dadurch sogar eine räumliche Tiefe des Hintergrunds erzielt. Das Spiel wird von Anfang an so programmiert, dass es einen Level-Editor enthält, mit dem ohne größere Eingriffe in das Javaprogramm eigene Levels erstellt und beliebig geändert werden können. Dazu reicht ein einfacher Texteditor aus. Die neuen oder geänderten Level müssen lediglich in das Programm eingebunden werden, was aber mit wenigen Programmzeilen möglich ist.John Horton erklärt recht kleinschrittig die einzelnen Programmschritte. Ich fand sie dadurch gut nachvollziehbar. Ein Spiel erstreckt sich über mehrere Buchkapitel. Mindestens am Ende jedes Kapitels, häufig aber auch zwischendurch, werden Teilabschnitte der Programmierung fertiggestellt, die ein Testen des Spiels zulassen. So bleibt die Motivation hoch und man kann schnell die Wirkung der Programmteile erkunden.Pro: - Gut verständlich, sofern man Javakenntnisse besitzt. - Motivierende und grafisch schon recht anspruchsvolle Spiele (zumindest das 2. Spiel). - Gut strukturierte Programmierung durch Nutzung von Vererbung, MVC-Architektur (zumindest soweit sinnvoll) und Datenkapselung. - Der Autor erläutert meistens recht genau, wo jeweils die neuen Codezeilen in den Klassen programmiert werden müssen, so dass man auch ohne Downloads der Source-Dateien das Programm nach und nach selbst eintippen kann. - Am Ende jedes Spiels zeigt der Autor noch einige Ideen auf, wie das Spiel ohne großen Programmieraufwand erweitert und verbessert werden kann. Dazu können in der Regel die bisher geschaffenen Programmelemente genutzt werden oder müssen nur geringfügig erweitert werden.Contra: - Das Layout der Codezeilen ist teilweise schlecht formatiert. Es sind z.T. Einrückungen vorhanden, wo keine hingehören und umgekehrt. Das erschwert das Lesen und Verstehen des Codes etwas. - Im zweiten (und schon recht komplexen Spiel) wollte der Autor wohl mit den letzten Programmteilen schnell (oder endlich) fertig werden. Leider enthalten dort zwei Klassen bzw. umfangreichere Methoden Fehler (keine bloßen Flüchtigkeitsfehler). Sie fallen bei einem Kurztest möglicherweise nicht aber bei etwas längeren Tests oder geändertem Level schon. Sofern man aber bis dahin den Erklärungen folgen konnte, ist man auch in der Lage, die Programme entsprechend zu ändern, obwohl die notwendigen Änderungen jeweils recht umfangreich waren.Trotz dieser eher kleinen Abstriche steckt das Buch aber so voller Ideen und hilfreicher Konzepte, dass es für mich sehr wertvoll ist und 5 Sterne verdient. Ich freue mich schon auf die Erläuterungen für das dritte und letzte Spiel (welches w.o. erwähnt sogar OpenGL ES 2 nutzt).Für den Leser sind moderate Java-Kenntnisse erforderlich, Android-Kenntnisse dagegen kaum.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.