Learning Java by Building Android  Games - John Horton - E-Book

Learning Java by Building Android Games E-Book

John Horton

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Android is one of the most popular mobile operating systems presently. It uses the most popular programming language, Java, as the primary language for building apps of all types. However, this book is unlike other Android books in that it doesn’t assume that you already have Java proficiency.

This new and expanded second edition of Learning Java by Building Android Games shows you how to start building Android games from scratch. The difficulty level will grow steadily as you explore key Java topics, such as variables, loops, methods, object oriented programming, and design patterns, including code and examples that are written for Java 9 and Android P.

At each stage, you will put what you’ve learned into practice by developing a game. You will build games such as Minesweeper, Retro Pong, Bullet Hell, and Classic Snake and Scrolling Shooter games. In the later chapters, you will create a time-trial, open-world platform game.

By the end of the book, you will not only have grasped Java and Android but will also have developed six cool games for the Android platform.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 885

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Java by Building Android Games Second Edition
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is Searching for Authors Like You
Preface
About the book
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
1. Java, Android and Game Development
What's new in the second edition?
Why Java, Android and Games?
Java: The first stumbling block
The games you will build
Sub' Hunter
Pong
Bullet Hell
Snake Clone
Scrolling Shooter
Open-World Platformer
How Java and Android work
Setting up Android Studio
Final step
Starting the first project: Sub' Hunter
Extra step 1
Extra step 2
Android Studio and our project – A very brief guided tour
The Project panel
The Editor window
Locking the game to full-screen and landscape orientation
Deploying the game so far
Running the game on an Android emulator
Running the game on a real device
Summary
2. Java: First Contact
Planning the Sub' Hunter game
Actions flowchart/diagram
Code comments
Mapping out our code using comments
Introduction to Java methods
Overriding methods
Structuring Sub' Hunter with methods
Introduction to Object Oriented Programming
Classes and Objects
The important thing about OOP, Classes, and Objects
Classes, objects, and instances
Final word on OOP, Classes, and Objects – for now
Using Java packages
Adding classes by importing packages
Linking up our methods
Summary
3. Variables, Operators and Expressions
Handling syntax and jargon
Java Variables
Different types of variables
Primitive types
Reference variables
String references
Array references
Object/class references
How to use variables
Declaring variables
Initializing variables
Making variables useful with operators
Most used operators in this book
Casting
Concatenation
Declaring and Initializing the Sub' Hunter Variables
Planning the variables
Declaring the variables
Handling different screen sizes and resolutions
Handling different screen resolutions part 1: Initialising the variables
Errors, warnings, and bugs
Printing Debugging Information
Testing the game
Summary
4. Structuring Code with Java Methods
Methods
Methods revisited and explained further
The method signature
Modifier
Return type
A closer look at method names
Parameters
Doing things in the method body
Method Overloading by Example
Creating a new project
Coding the method overloading mini-app
Running the method overloading mini-app
How it works
Scope: Methods and Variables
Revisiting the code and methods we have used already
Generating random numbers to deploy a sub
The Random class and the nextInt method
Adding Random based code to newGame
Testing the game
Summary
5. The Android Canvas Class – Drawing to the Screen
Understanding the Canvas class
Getting started drawing with Bitmap, Canvas, and ImageView
Canvas and Bitmap
Paint
ImageView and Activity
Canvas, Bitmap, Paint and ImageView quick summary
Using the Canvas class
Preparing the objects of classes
Initializing the objects
Setting the Activity content
Canvas Demo app
Creating a new project
Coding the Canvas demo app
Exploring the Bitmap initialization
Drawing on the screen
Explaining Color.argb
Android Coordinate system
Plotting and drawing
Drawing the Sub' Hunter graphics and text
Preparing to draw
Initializing a Canvas, Paint, ImageView, and Bitmap
Drawing some grid lines
Drawing the HUD
Upgrading the printDebuggingText method
Summary
6. Repeating Blocks of Code with Loops
Decisions, decisions
Keeping things tidy
More operators
Loops
While loops
Breaking out of a loop
Do while loops
For loops
Nested loops
Using for loops to draw the Sub' Hunter grid
Summary
7. Making Decisions with Java If, Else and Switch
If they come over the bridge shoot them
Else do this instead
Switching to make decisions
Switch example
Combining different control flow blocks
Continue...
Making sense of the screen touches
Coding the onTouchEvent method
Final tasks
Coding the takeShot method
Explaining the takeShot method
Coding the boom method
Drawing the shot on the grid
Running the game
Summary
8. Object-Oriented Programming
Basic Object-Oriented Programming
Humans learn by doing
Introducing OOP
Encapsulation
Inheritance
Polymorphism
Why we do it like this?
Class recap
Looking at the code for a class
Class implementation
Declaring, initializing and using an object of the class
Basic classes mini-app
Creating your first class
More things we can do with our first class
Remember that encapsulation thing?
Controlling class use with access modifiers
Class access in a nutshell
Controlling variable use with access modifiers
Variable access summary
Methods have access modifiers too
Method access summary
Accessing private variables with getters and setters
Setting up our objects with constructors
Using "this"
Static methods
Encapsulation and static methods mini-app
OOP and inheritance
Inheritance mini-app
Polymorphism
Abstract classes
Interfaces
Starting the Pong game
Planning the Pong game
Setting up the Pong project
Summary
9. The Game Engine, Threads, and The Game Loop
Coding the PongActivity class
Coding the PongGame class
Coding the PongGame class
Adding the member variables
Coding the PongGame constructor
Coding the startNewGame method
Coding the draw method
Adding the printDebuggingText method
Understanding the draw method and the SurfaceView class
The game loop
Threads
Problems with threads
Java try, catch exception handling
Implementing the game loop with a thread
Implementing Runnable and providing the run method
Coding the thread
Starting and stopping the thread
Activity lifecycle
A simplified explanation of the Android lifecycle
Lifecycle phases: What we need to know
Lifecycle phases: What we need to do
Using the Activity lifecycle to start and stop the thread
Coding the run method
Running the game
Summary
10. Coding the Bat and Ball
The Ball Class
Communicating with the game engine
Representing rectangles and squares with RectF
Coding the variables
Coding the Ball constructor
Coding the RectF getter method
Coding the Ball update method
Coding the Ball helper methods
Coding a realistic-ish bounce
Using the Ball class
The Bat class
Coding the Bat variables
Coding the Bat constructor
Coding the Bat helper methods
Coding the Bat's update method
Using the Bat Class
Coding the Bat input handling
Running the game
Summary
11. Collisions, Sound Effects and Supporting Different Versions of Android
Handling collisions
Collision detection options
Rectangle intersection
Radius overlapping
Crossing number algorithm
Optimizations
Multiple hitboxes
Neighbour checking
Best options for Pong
The RectF intersects method
Handling different versions of Android
Detecting the current Android version
The Soundpool class
Initializing SoundPool the new way
Java Method chaining explained
Back to initializing SoundPool (the new way)
Initializing SoundPool the old way
Loading sound files into memory
Playing a sound
Stopping a sound
Generating sound effects
Adding sound to the Pong game
Adding the sound variables
Initializing the SoundPool
Coding the collision detection and playing sounds
The bat and the ball
The four walls
Playing the game
Summary
12. Handling Lots of Data with Arrays
Planning the project
Starting the project
Change the AndroidManifest.xml to lock in landscape and full-screen
Creating the classes
Reusing the Pong engine
Coding the BulletHellActivity
Coding the BulletHellGame class
Coding the member variables
Coding the BulletHellGame constructor
Coding the BulletHellGame methods
Coding draw and onTouchEvent
Coding pause, resume, and printDebuggingText
Testing the Bullet Hell engine
Coding the Bullet class
Spawning a bullet
Java Arrays
Arrays are objects
Simple array example mini-app
Getting dynamic with arrays
Dynamic array example
Entering the nth dimension with Arrays
Multidimensional Array mini app
Array out of bounds exceptions
Spawning an array of bullets
Running the game
Summary
13. Bitmap Graphics and Measuring Time
The Bob (player's) class
Adding the Bob graphic to the project
Coding the Bob class
Using the Bob class
Adding Bob to the collision detection
Drawing Bob to the screen
Adding the sound effects
Activating Bob's teleport
Coding the printDebuggingText method
Coding the spawnBullet method (again)
Coding the startGame method
Running the game
Summary
14. The Stack, the Heap, and the Garbage Collector
Managing and understanding memory
Variables revisited
The stack and the heap
A quick break to throw out the trash
Stack and Heap quick summary
Introduction to the Snake game
Looking ahead to the Snake game
Getting started with the Snake game
Make full screen and landscape
Adding some empty classes
Coding SnakeActivity
Adding the sound effects
Coding the game engine
Coding the members
Coding the constructor
Coding the newGame method
Coding the run method
Coding the updateRequired method
Coding the update method
Coding the draw method
Coding onTouchEvent
Coding pause and resume
Running the game
Summary
15. Android Localization -Hola!
Making the snake game Spanish, English and German
Adding Spanish support
Adding German support
Add the string resources
Amending the code
Run the game in German or Spanish
Summary
16. Collections, Generics and Enumerations
Adding the graphics
Coding the apple
The Apple constructor
Using the apple
Running the game
Using Arrays in the snake game
ArrayLists
The enhanced for loop
Arrays and ArrayLists are polymorphic
Enumerations
Summary
17. Manipulating Bitmaps and Coding the Snake class
Rotating Bitmaps
What is a Bitmap exactly
The Matrix class
Inverting the head to face left
Rotating the head to face up and down
Add the sound to the project
Coding the Snake class
Coding the constructor
Coding the reset method
Coding the move method
Coding the detectDeath method
Coding the checkDinner method
Coding the draw method
Coding the switchHeading method
Using the snake class and finishing the game
Running the completed game
Summary
18. Introduction to Design Patterns and much more!
Introducing the Scrolling Shooter project
Game programming patterns and the structure of the Scrolling Shooter project
Starting the project
Editing the manifest
Code the GameActivity class
Getting started on the GameEngine class
Controlling the game with a GameState class
Passing GameState from GameEngine to other classes
Communicating from GameState to GameEngine
Giving partial access to a class using an interface
Interface refresher
What we will do to implement the interface solution
1. Coding the new interface
2. Implementing the interface
3. Passing a reference to the interface into the class that needs it
Coding the GameState class
Saving and loading the high score- forever
4. Pressing the "special button" - Calling the method of the interface
Finishing off the GameState class
Using the GameState class
Building a sound engine
Adding the sound files to the project
Coding the SoundEngine class
Using the SoundEngine class
Testing the game so far
Building a HUD class to display control buttons and text
Coding the prepareControls method
Coding the draw method of the HUD class
Coding drawControls and getControls
Building a Renderer class to handle the drawing
Using the HUD and Renderer classes
Running the game
Summary
19. Listening with the Observer Pattern, Multitouch and Building a Particle System
The Observer pattern
The Observer pattern in the Scrolling Shooter project
Coding the Observer pattern in Scrolling Shooter
Coding the Broadcaster interface
Coding the InputObserver interface
Making GameEngine a Broadcaster
Coding a Multitouch UI controller and making it a listener
Coding the required handleInput method
Using the UIController
Running the game
Implementing a particle system explosion
Coding the Particle class
Coding the ParticleSystem class
Adding a particle system to the game engine and drawing it with the Renderer
Building a physics engine to get things moving
Running the game
Summary
20. More Patterns, a Scrolling Background and Building the Player's ship
Meet the game objects
Reminder of how all these objects will behave
The Entity-Component pattern
Why lots of diverse object types are hard to manage
The first coding nightmare
Using a generic GameObject for better code structure
Composition over inheritance
The Simple Factory pattern
At last some good news
Summary so far
The object specifications
Coding the ObjectSpec parent class
Coding all the specific object specifications
AlienChaseSpec
AlienDiverSpec
AlienLaserSpec
AlienPatrolSpec
BackgroundSpec
PlayerLaserSpec
PlayerSpec
Coding the component Interfaces
GraphicsComponent
InputComponent
MovementComponent
SpawnComponent
Coding the player's and the background's empty component classes
StdGraphicsComponent
PlayerMovementComponent
PlayerSpawnComponent
PlayerInputComponent and the PlayerLaserSpawner interface
LaserMovementComponent
LaserSpawnComponent
BackgroundGraphicsComponent
BackgroundMovementComponent
BackgroundSpawnComponent
Every GameObject has a transform
Every object is a GameObject
Completing the player's and the background's components
The player's components
Completing the StdGraphicsComponent
Completing the PlayerMovementComponent
Completing the PlayerSpawnComponent
Completing the PlayerInputComponent
Completing the LaserMovementComponent
Completing the LaserSpawnComponent
Coding a scrolling background
Completing the BackgroundGraphicsComponent
Completing the BackgroundMovementComponent
Completing the BackgroundSpawnComponent
GameObject/Component reality check
Building the GameObjectFactory
Coding the Level class
Putting everything together
Updating GameEngine
Updating PhysicsEngine
Updating Renderer
Running the game
Summary
21. Completing the Scrolling Shooter Game
Adding the alien's components
AlienChaseMovementComponent
Code AlienLaserSpawner
Implement the Interface in GameEngine
AlienDiverMovementComponent
AlienHorizontalSpawnComponent
AlienPatrolMovementComponent
AlienVerticalSpawnComponent
Spawning the Aliens
Updating GameEngine
Updating Level
Updating GameObjectFactory
Running the game
Detecting collisions
Running the completed game
Summary
22. Exploring More Patterns and Planning the Platformer Project
Platform Game: Bob Was in A Hurry
How we will build the platformer
Level design files example
The graphics
Cameras and the real world
The slightly modified ObjectSpec
New improved transform hierarchy
Project patterns
BitmapStore
Levels and LevelManager
Getting started with Bob was in a hurry
Creating the project and adding the assets
Specifying all the game objects with GameObjectSpec classes
GameObjectSpec
BackgroundCitySpec
BackgroundMountainSpec
BackgroundUndergroundSpec
BrickTileSpec
CartTileSpec
CoalTileSpec
CollectibleObjectSpec
ConcreteTileSpec
DeadTreeTileSpec
FireTileSpec
GrassTileSpec
LamppostTileSpec
MoveablePlatformSpec
ObjectiveTileSpec
PlayerSpec
ScorchedTileSpec
SnowTileSpec
SnowyTreeTileSpec
StalactiteTileSpec
StalagmiteTileSpec
StonePileTileSpec
Summary of component classes
Coding the component interfaces
GraphicsComponent
UpdateComponent
Coding the other interfaces
EngineController
GameEngineBroadcaster
InputObserver
Summary
23. The Singleton Pattern, Java HashMap, Storing Bitmaps Efficiently and Designing Levels
The Singleton pattern
The Singleton code
More Java Collections – Meet Java Hashmap
The memory problem and the BitmapStore
Coding the BitmapStore class
Coding the basic transform
Coding the inanimate and decorative components
DecorativeBlockUpdateComponent
InanmiateBlockGraphicsComponent
InanimateBlockUpdateComponent
Create the levels
Level
LevelCity
LevelMountains
LevelUnderground
Coding a stripped down GameObjectFactory
Coding a slightly commented-out game object
Coding the GameState
Code the SoundEngine
Coding the physics engine (without collision)
Coding a Renderer
Coding the camera
Testing the formulas with hypothetical coordinates
Coding the Hud
Coding the UIController class
Code the Activity
Code the GameEngine
Coding the LevelManager class
Running the game
Summary
24. Sprite-sheet animations, Controllable Player and Parallax Scrolling Backgrounds
Animating sprite-sheets
Coding the Animator
Coding the player's components and transform
PlayerTransform
AnimatedGraphicsComponent
PlayerInputComponent
PlayerUpdateComponent
Coding a parallax background
Coding the BackgroundTransform
Coding the BackgroundGraphicsComponent
Coding the BackgroundUpdateComponent
Updating the levelManager, GameObjectFactory and GameObject
Running the game
Summary
25. Intelligent Platforms and Advanced Collision Detection
Coding the moving platform component class
MoveableBlockUpdateComponent
Update LevelManager and GameObjectFactory
Running the game
Coding the detectCollisions method: Part 1
Explaining part 1
Coding the detectCollisions method: Part 2
Explaining part 2
Running the game
Summary
26. What next?
Publishing
Using the assets from the book
Future learning
My other channels
Thanks
Index

Learning Java by Building Android Games - Second Edition

Learning Java by Building Android Games Second Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Amarabha Banerjee

Acquisition Editor: Reshma Raman

Content Development Editors: Onkar Wani

Technical Editor: Ralph Rosario

Copy Editor: SAFIS

Project Coordinator: Devanshi Doshi

Proofreader: Safis Editing

Indexers: Pratik Shirodkar

Graphics: Jason Monterio

Production Coordinator: Aparna Bhagat

First published: January 2015

Second edition: August 2018

Production reference: 1270818

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78883-915-0

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionalsLearn better with Skill Plans built especially for youGet a free eBook or video every monthMapt is fully searchableCopy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.

About the reviewer

Boon Hian Tek is a 18 years Java veteran. He has honed his software development skills in a varying industries. He helped bringing medical records online, aided the advertising industry target ads, assisted in getting disposing of chemical weapons, and more recently part of making fin tech work some wonders.

He is always passionate with automation. Boon spends his days automating so that he can spend more time with his family. No one should spend be forced to spend time doing mundane stuff. Except for wax on, wax off!

He works for one of the largest fin tech in Singapore also reviewed First Edition of this book.

My wife and daughter putting up with the time I spent away from them to help with the book.

Packt is Searching for Authors Like You

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Preface

About the book

Android is one of the most popular mobile operating systems presently. It uses the most popular programming language, Java, as the primary language for building apps of all types. However, this book is unlike other Android books in that it doesn't assume that you already have Java proficiency.

This new and expanded second edition of Learning Java by Building Android Games shows you how to start building Android games from scratch. The difficulty level will grow steadily as you explore key Java topics, such as variables, loops, methods, object-oriented programming, and design patterns, including code and examples that are written for Java 9 and Android P.

At each stage, you will put what you've learned into practice by developing a game. You will build games such as Minesweeper, Retro Pong, Bullet Hell, and Classic Snake and Scrolling Shooter games. In the later chapters, you will create a time-trial, open-world platform game.

By the end of the book, you will not only have grasped Java and Android but will also have developed six cool games for the Android platform.

Who this book is for

Learning Java by Building Android Games is for you if you are completely new to Java, Android, or game programming, and you want to make Android games. This book also acts as a refresher for those who already have experience of using Java on Android or any other platform without game development experience.

What this book covers

Chapter 1, Java, Android, and Game Development, In this first chapter we will get straight into Java, Android and game development. Also, we will look at some images and an outline of each of the six games we will develop throughout the book. Further, we will explore and discover what is so great about Android, what exactly Android and Java are, how they work and complement each other. Moving quickly on we will set up the required software and then build and deploy the outline for the first game.

Chapter 2, Java: First Contact, In this chapter, we will make significant progress with the Sub' Hunter game even though this is the first lesson on Java. We will look in detail at exactly how Sub' Hunter will be played and the steps/flow that our completed code will need to take to implement it. We will also learn about Java code comments for documenting the code, take a brief initial glimpse at methods to structure our code and an even briefer first glimpse at object-oriented programming that will begin to reveal the power of Java and the Android API.

Chapter 3, Variables, Operators, and Expressions, We are going to make good progress in this chapter. We will learn about Java variables that allows us to give our game the data it needs. Things like the sub's location and whether it has been hit, will soon be possible to code. Furthermore, the use of operators and expressions will enable us to change and mathematically manipulate this data as the game is executing.

Chapter 4, Structuring Code with Java Methods, As we are starting to get comfortable with Java programming, in this chapter, we will take a closer look at methods because although we know that you can call them to make them execute their code, there is more to them that haven't been discussed so far.

Chapter 5, The Android Canvas Class - Drawing to the Screen, While we will leave creating our own classes for a few more chapters our new-found knowledge about methods enables us to start taking greater advantage of the classes that Android provides. This entire chapter will be about the Android Canvas class and some related classes like Paint and Color. These classes combined bring great power when it comes to drawing to the screen. Learning about Canvas will also teach us the basics of using any class.

Chapter 6, Repeating Blocks of Code with Loops, In this brief chapter, we will learn about Java loops that enable us to repeat sections of our code in a controlled manner. Loops in Java take a few different forms and we will learn how to use them all and throughout the rest of the book we will put each of them to good use.

Chapter 7, Making Decisions with Java if, else, and switch, Welcome to the final part of the first game. By the end of this chapter, you can say you have learned most of the Java basics. In this chapter, we will learn more about controlling the flow of the game's execution and we will also put the finishing touches to the Sub' Hunter game to make it playable.

Chapter 8, Object-Oriented Programming, In this chapter, we will discover that in Java, classes are fundamental to everything. We have already talked about reusing other people's code, specifically the Android code, but in this chapter, we will really get to grips with how this works and learn about Object Oriented Programming as well as how to use it. Topics including encapsulation, inheritance, and polymorphism. We will start to write our own reusable classes and look at some more advanced OOP like abstract classes and interfaces. At the end of the chapter we will know enough about OOP to get started on the Pong game.

Chapter 9, The Game Engine, Threads, and the Game Loop, During this chapter we will see the game engine come together. By the end of the chapter, we will have an exciting blank screen that draws debugging text at 60 frames per second on a real device, although, probably less on an emulator. While doing so we will learn about programming threads, try-catch blocks, the Runnableinterface, Android Activity lifecycle and the concept of a game loop. My expression of excitement for a blank screen might seem sarcastic but, once this chapter is done we will be able to code and add game objects, almost at will. Furthermore, this game engine code will be used as an approximate template (we will improve it each project) for future projects making the realization of future games faster and easier.

Chapter 10, Coding the Bat and Ball, As we have done so much theory and preparation work in the previous two chapters we can quickly make some progress in this one. We already have our bare-bones game engine coded and ready to update, draw and track time down to the nearest millisecond. Now we can add code to the Bat and the Ball classes. By the end of the chapter, we will have a moving ball and a player-moveable bat.

Chapter 11, Collisions, Sound Effects, and Supporting Different Versions of Android, By the end of this chapter, we will have a fully working and beeping implementation of the Pong game. We will start the chapter off by looking at some collision detection theory which will be put in to practice near the end of the chapter. We will also learn about how we can detect and handle different versions of Android. We will then be able to study the SoundPool class and the different ways we use it depending on the Android version the game is running on. At this point, we can then put everything we have learned into producing some more code to get the Pong ball bouncing and beeping as well as put the finishing touches on the game.

Chapter 12, Handling Lots of Data with Arrays, In this chapter, we will first get the Bullet Hell project setup and ready to roll with a single bullet whizzing across the screen. Then we will learn about Java arrays which allow us to manipulate a potentially huge amount of data in an organized and efficient manner. Once we are comfortable handling arrays of data we will see how we can spawn hundreds or thousands of our new Bullet class instances, without breaking a sweat.

Chapter 13, Bitmap Graphics and Measuring Time, So far in this book, we have drawn exclusively with primitive shapes and text. In this section, we will see how we can use the Canvas class to draw Bitmap graphics- after all Bob is so much more than just a block or a line. We will also code Bob and implement his teleportation feature, shield and collision detection. To finish the game off, we will add a HUD, measure the time, and code a solution to remember the longest (best) time.

Chapter 14, The Stack, the Heap, and the Garbage Collector In this chapter, we will make a good start with the next project, an authentic looking, clone of the classic Snake game. It is also the time that we understood a little better what is going on underneath the Android hood. We constantly refer to 'references' but what exactly is a reference and how does it affect how we build games?

Chapter 15, Android Localization- Hola!, This chapter is quick and simple but what we will learn to do can make your game accessible to millions more potential gamers. We will see how to add additional languages. We will see the "correct" way to add text to our games and use this feature to make the Snake game multilingual. This includes using String resources instead of hard-coding Strings in our code directly as we have done so far throughout the book.

Chapter 16, Collections, Generics, and Enumerations, This chapter will be part practical and part theory. First, we will code and use the Apple class and get our apple spawning ready for dinner. Afterward, we will spend a little time getting to know to new Java concepts ArrayList and enumerations (enum for short). These two new topics will give us the extra knowledge we will need to finish the game (mainly the Snake class) in the next chapter.

Chapter 17, Manipulating Bitmaps and Coding the Snake Class, In this chapter, we will finish the Snake game and make it fully playable. We will put what we learned about ArrayList and enum to good use and we will properly see the benefit of encapsulating all the object-specific drawing code into the object itself. Furthermore, we will learn how to manipulate Bitmaps so that we can rotate and invert them to face any way that we need them to.

Chapter 18, Introduction to Design Patterns and Much More!, Since the second project, we have been using objects. You might have noticed that many of the objects have things in common. Things like variables for speed and direction, a RectF for handling collisions and more besides.

As our objects have more in common we should start taking advantage of OOP, inheritance, polymorphism and a concept we will now introduce design patterns.

Inheritance, polymorphism and design patterns will enable us to fashion a suitable hierarchy to try and avoid writing duplicate code and avoid sprawling classes with hundreds of lines. This type of dissorganised code is hard to read, debug or extend. The bigger the game project and the more object types, the more of a problem this would become.

This project and the next will explore many ways that we can structure our Java code to make our code efficient, reusable and less buggy. When we write code to a specific, previously devised solution/structure we are using a design pattern.

Don't worry, in the remaining chapters we will also be finding out about more game development techniques to write better, more advanced games. In this chapter, we will start the Scrolling Shooter project.

Chapter 19, Listening with the Observer Pattern, Multitouch, and Building a Particle System, In this chapter we will get to code and use our first design pattern. The Observer pattern is exactly what it sounds like. We will code some classes that will indeed observe another class. We will use this pattern to allow the GameEngine class to inform other classes when they need to handle user input. This way individual classes can handle different aspects of user input.

In addition, we will code a particle system. A particle system comprises of hundreds or even thousands of graphical objects that are used to create an effect. Our particle system will look like an explosion.

Chapter 20, More Patterns, a Scrolling Background, and Building the Player- Ship, This is one of the longest chapters and we have quite a bit of work as well as theory to get through before we can see the results of it on our device/emulator. However, what you will learn about and then implement will give you the techniques to dramatically increase the complexity of the games you are able to build. Once you understand what an entity-component system is and how to construct game objects using the Factory pattern you will be able to add almost any game object you can imagine to your games. If you bought this book not just to learn Java but because you want to design and develop your own video games, then this part of the book is for you.

Chapter 21, Completing the Scrolling Shooter Game, In this chapter we will complete the Scrolling Shooter game. We will achieve this by coding the remaining component classes which represent the three different types of alien and their lasers that they can shoot at the player. Once we have completed the component classes we will make minor modifications to the GameEngine, Level and GameObjectFactory classes to accommodate these newly completed entities.The final step to complete the game is the collision detection that we will add to the PhysicsEngine class.

Chapter 22, Exploring More Patterns and Planning the Platformer Project, Welcome to the start of the final project. Over the next four chapters we will build a platform game packed full of features like parallax effect scrolling, animated controllable character, multiple different and challenging levels and much more (keep reading for more details.) During this project we will discover more Java patterns like the Singleton, another Java data class, the HashMap and explore the gaming concepts of a controllable camera and an animator. At the same time, we will reinforce all the Java concepts we have already learned including aiding our understanding of and improving upon the entity-component/factory patterns we used in the previous project.

Chapter 23, The Singleton Pattern, Java HashMap, Storing Bitmaps Efficiently, and Designing Levels, This is going to be a very busy and varied chapter. We will learn the theory of the Singleton design pattern. We will be introduced to another of the classes of the Java Collections, HashMap in which we will see how we can more efficiently store and make available the wide variety of bitmaps that are required for this project. We will also get started on our new and improved Transform class, code the first of the component-based classes, code the all-new Camera class and make a significant start on some of the more familiar classes, GameState, PhysicsEngine, Renderer, GameEngine and more besides.

Chapter 24, Sprite Sheet Animations, the Controllable Player, and Parallax Scrolling Backgrounds, In this chapter we will look at how basic animation occurs by "flipping" through different images to create a moving effect. This is the same technique used to make a simple cartoon. Of course, we will then need to code a solution to achieve this simple animation in our game objects and will do so by coding an Animator class and adding one to any graphics-related component class that needs it. We will also implement another scrolling background but slightly differently to the scrolling background in the previous project because this time it will need to be positioned both horizontally and vertically, each frame, relative to the position of the camera.

Chapter 25, Intelligent Platforms and Advanced Collision Detection, This chapter is the final chapter of the final project and shorter than most. We will however, add quite a bit to the game. First, we will code an intelligent platform- one that moves up and down of its own accord. This greatly increases the potential for interesting level designs and looks good too. The final thing we will add is the collision detection. This will be more advanced than in any of the other projects as we will need to respond differently depending on which collider of the player collide with various different game objects. In addition, the collision code will need to communicate with the movement code to make the whole system behave as needed.

Chapter 26, What next?, We are just about done with our journey. This chapter is just a few ideas and pointers that you might like to look at before rushing off and making your own games.

To get the most out of this book

To succeed with this book, you don't need any experience whatsoever. If you are confident with your operating system of choice (Windows, Mac or Linux) you can learn to make Android games using the Java programming language. Learning to develop professional quality games is a journey that anybody can embark upon and stay on for as long as they want.If you do have previous, programming (Java or any other language), Android or game development experience then you will make faster progress with the earlier chapters.

Download the example code files

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

You can download the code files by following these steps:

Log in or register at http://www.packtpub.com.Select the SUPPORT tab.Click on Code Downloads & Errata.Enter the name of the book in the Search box and follow the on-screen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Java-by-Building-Android-Games-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/LearningJavabyBuildingAndroidGamesSecondEdition_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

[default] @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }

Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: "Select System info from the Administration panel."

Note

Warnings or important notes appear like this.

Tip

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected], and mention the book's title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book we would be grateful if you would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Chapter 1. Java, Android and Game Development

Welcome to Learning Java by Building Android Games (second edition). In this first chapter we will get straight into Java, Android and game development and by the end, we will have a great insight into what we will achieve in the book as well as have built and deployed the first part of the first game.

Also, we will look at some images and an outline of each of the six games we will develop throughout the book.

Further, we will explore and discover what is so great about Android, what exactly Android and Java are, how they work and complement each other, and what that means to us as future game developers.

Moving quickly on we will set up the required software, so we can build and deploy the outline for the first game.

In summary this chapter will cover:

Why choose the combination of Java, Android, and games?Look at the six neat games we will use to learn Java and AndroidHow Java and Android work togetherSetting up the Android Studio development environmentBuilding and running a blank game project on the Android emulator or a real device

Let's get started.

What's new in the second edition?

Everything! The Java theory has been reworked and reorganized so if you read the first edition you might recognize a few of the words to be similar but all the games are new. Even the Snake and Pong games which made an appearance in the first edition have totally reworked code now.

This second edition goes much deeper than the previous, into crucial topics like object-oriented programming and goes even further to cover more advanced topics like Java design patterns, loading game levels from files and Java collections.

More game specific topics are covered as well. Collision detection, physics and huge scrolling game worlds using a movable camera are just some of the additions.

Also, more Android topics are covered, including handling different screen sizes/resolutions and input with multiple fingers. And as you would expect if you had read the first edition, everything is put into practice using a game.

It is hard to know which topics should be highlighted in this summary of contents as so many are covered and I urge potential readers to read ahead in this chapter to see the wide range of games we will build together and then look at the table of contents to see the full scope of the Java topics you will learn at the same time.

Why Java, Android and Games?

When Android first arrived in 2008, it was a bit drab compared to the much more stylish iOS on the Apple iPhone/iPad. But quite quickly, through diverse handset offers that struck a chord with both the practical price-conscious as well as the fashion-conscious and tech-savvy, Android user numbers exploded.

For many, myself included, developing Android games is the most rewarding pastime and business bar none.

Quickly putting together, a prototype of a game idea, refining it and then deciding to run with it and wire it up into a fully-fledged game is such an exciting and rewarding process. Any programming can be fun, and I have been programming all my life, but creating games, especially for Android is somehow extraordinarily rewarding.

Defining exactly why this is the case is quite difficult. Maybe it is the fact that the platform is free and open. You can distribute your games without needing the permission of a big controlling corporation - nobody can stop you. And at the same time, you have the well-established, corporate controlled mass markets like Amazon App Store and Google Play.

More likely, the reason developing Android games gives such a buzz is the nature of the devices themselves. They are deeply personal. You can develop games which interact with people's lives. Educate, entertain, tell a story, etc. But it is there in their pocket ready to play in the home, the workplace or on holiday.

You can certainly build something bigger for Windows or Xbox etc. but knowing that thousands (or millions) of people are carrying your work in their pockets and sharing it with friends is more than a buzz.

No longer is developing games considered geeky, nerdy or reclusive. In fact, developing Android games is considered highly skillful and the most successful are hugely admired, even revered.

If all this fluffy and spiritual stuff doesn't mean anything to you then that's fine too; developing for Android can make you a living or even, make you wealthy. With the continued growth of device ownership, the ongoing increase in CPU and GPU power and the non-stop evolution of the Android operating system itself, the need for professional game developers are only going to grow.

In short, the best Android developers – and, more importantly, the Android developers with the best ideas and most determination – are in greater demand than ever. Nobody knows who these future Android game developers are and they might not even have written their first line of Java yet.

So why isn't everybody an Android developer? Obviously, not everybody will share my enthusiasm for the thrill of creating software that can help people make their lives better, but I am guessing that because you are reading this, you might?

Java: The first stumbling block

Unfortunately, for those that do share my enthusiasm, there is a kind of glass wall on the path of progress that frustrates many aspiring Android game developers.

Android uses Java to make games. Every Android book, even those aimed at so-called beginners assumes readers to have at least an intermediate level of Java, and most require anadvanced level. So good-to-excellent Java knowledge was a prerequisite for learning Android.

Unfortunately, learning Java in a completely different context to Android can sometimes be a little dull and much of what you learn is not directly transferable into the world of Android anyway.

To add to this that games are arguably more advanced than regular GUI based apps and you can see why beginners to Android game development are often put off from starting.

But it doesn't need to be like this. In this book I have carefully placed all the Java topics you would learn in a thick and weighty beginner's tomb and reworked them into six games, starting from the incredibly simple through to an open-world 2D platformer.

If you want to make games or just want to have more fun when learning Java and Android, it makes more sense, is vastly more enjoyable, and is significantly quicker and more rewarding to teach Java and Android in a game development environment. This book will teach Java with the single overriding goal of learning to develop professional standard games, but this knowledge is also transferable to non-Android Java environments and non-games Android environments. And that's what this book is about.

Tip

Plus, you get to blow stuff up!

The games you will build

Let's look at some of the screen-shots and get a little bit more detail about each of the games from the book. We will go in to further detail and explanation as we start each project.

Sub' Hunter

The first game we build will allow us to introduce some key Java beginner's topics. Code comments, variables, operators, methods, loops, generating random numbers, if, else, switch and a brief introduction to object-oriented programming. We will also see how to communicate with the Android OS, detect screen touches, draw simple graphics, detect the screen resolution and handle different screen sizes. All this will be used to build a simpler variation of the classic Minesweeper type game. Here is one of the screens from that game.

This will be a tap-to-shoot game where the player has to guess the position of the sub', then refine their next shot based on the "sonar" report of the previous shot.

Pong

For the second project, we will slightly increase the complexity and move on to 60 frames per second smoothly animated Pong clone. The Java topics covered include classes, interfaces, threads, try-catch blocks, method overloading vs. overriding and a much deeper look at object-oriented programming including writing and using our own classes. This project will also leave the reader competent with understanding the game loop, simple bouncing physics, playing sound effects and detecting game object collisions. Here is a picture of the simple but still a step-up Pong game.

If the Pong game doesn't seem very busy, then the next game will not only be the exact opposite but will also giv e you the knowledge to improve the first two games.

Bullet Hell

In this project, we will meet Bob. In this Bullet Hell game, Bob will be a static image that can teleport at will anywhere on the screen to avoid the ever-growing number of bullets. In the final game we will also animate Bob, so he can run and jump around an explorable scrolling world. This short implementation will enable us to learn about Java arrays, Bitmap graphics and measuring time. We will also see how we can quite simply use Java arrays alongside what we have already learned about classes to spawn vast numbers of objects in our games.

The objective of Bullet Hell is to survive for as long as possible. If a bullet is about to hit Bob the player can teleport him by tapping the desired destination on the screen, but each teleport spawns more bullets.

Snake Clone

This game is a remake of the classic that has been enraging gamers for decades. Guide your snake around the screen and gaining points by eating apples. Each time you eat an apple your snake gets longer and harder to keep alive. In this project we learn about Java ArrayList, enhanced for loop, the Stack, the Heap and the Garbage collector (seriously- it's a thing) and we will also see how to make our games multilingual. Hola!

The game ends when the snake bumps into the edge of the screen or ends up eating part of his own body.

Scrolling Shooter

This project, technically speaking, is a big step up from Snake. We will learn how to handle multiple different alien types with unique behaviour, appearance and properties. Other features of the game include rapid fire lasers, scrolling background, persistent high score and a cool star-burst particle system explosion effect.

In this project we are introduced to Java and game programming patterns which are key to writing complex games with manageable code. We will learn about and use the Entity-Component pattern, Strategy pattern, Factory pattern and Observer pattern.

The techniques learned in this project are vital if you want to design your own games while structuring your Java code in a way that allows your games to become more complex and yet keep the code manageable.

Open-World Platformer

In this project Bob makes a second appearance. The game will be a time trial where the player must get from the start point to the exit in the fastest time possible. There will be deadly jumps, moving platforms to navigate, fire pits and collectible coins. Every coin the player fails to collect will add a time penalty.

In this project we learn about the concept of a moveable camera that tracks the part of the game-world that needs to be shown to the player at any given moment. We will also learn some new Java patterns and reinforce the vital knowledge from the previous chapter. Furthermore, we will see how we can design levels as text layouts and then load them in code as playable levels.

There are three levels and the player will choose the level they want to play from a home-screen which will also show the fastest times for each level.

Let's learn a little about how Java and Android work.

How Java and Android work

After we write a game in Java for Android, we click on a button in Android Studio to change our code into another form, a form that is understood by Android devices. We call this "other form" Dalvik EXecutable (DEX) code, and the transformation process is called compiling.

Compiling takes place on the development machine after we click on that button. We will see this work right after we set up our development environment in a minute.

Android is a complex system, but you do not need to understand it in depth, in fact, it is designed to hide the complexity, all operating systems are, and Android does this better than most.

The part of the Android system that executes (runs) our compiled DEX code is called the Dalvik Virtual Machine (DVM). The DVM itself is a piece of software that runs on a specially adapted version of the Linux operating system. So, what the user sees of Android, is, Android just as an app running on yet another operating system. Therefore the apps and games that we write are apps running on top of the app which is Android itself.

The purpose of the DVM is to hide the complexity and diversity of the hardware and software that Android runs on but, at the same time, its purpose is to expose all its useful features. This exposing of features works in two ways.

The DVM itself must have access to the hardware, which it does, but this access must be programmer friendly and easy to use. The way the DVM allows us access is indeed easy to use because of the Android Application Programming Interface (API).

This API is primarily designed to use with Java. In fact, most of the Android API, is itself, Java code. As I may have mentioned already, this makes Android games the most fun and thorough way to learn Android, Java and game development.

If you want to see the relationship between The Android API, DEX code, DVM and an Android device, look at this picture.

Tip

Don't worry too much about this initially convoluted sounding system, it is much more fun, quicker and easier to get to know how things work by writing some real code.

Let's set up Android Studio.

Setting up Android Studio

Setting up Android Studio is quite straightforward if a little lengthy. Grab some refreshment and get started with the following steps.

Visit developer.android.com/studio/index.html. Click the big green button to proceed.Accept the terms and conditions by checking the box and then click the big blue button DOWNLOAD ANDROID STUDIO FOR WINDOWS.When the download is completed run the file you just downloaded. It has a name that starts android-studio-ide… the end of the name of the file will vary based on the current version at time of reading.Click the Next button to proceed.Leave the default options selected as shown next and click the Next button.Next, we need to choose where to install Android Studio as shown in the next image.

The install wizard recommends 500mb, however there are more requirements later in the install process. It is much easier if you have all your Android Studio parts as well as your project files on the same hard drive. I recommend having at least 2gb of free space. If you need to switch drives to accommodate this, then use the Browse.. button to browse to a suitable place on your hard drive.

Tip

Write down a note of where you choose

When you are ready click the Next button.In this next window you are choosing the folder in your start menu where Android Studio will appear. Leave it at the default as shown next.Click Install.This step might take some time, especially on older machines or if you have a slow Internet connection. When this stage is done you will see this screen.Click Next.Android Studio is now installed, check the Start Android Studio check-box and click the Finish button.You will be greeted with the Welcome screen as shown next.Click the Next button.Choose Standard install type as shown next.Click the Next button.Choose whichever color scheme looks nice to you, I chose InteliJ as shown next.Click Next.Now you will see the Verify Settings screen.Click the Finish button. Android Studio will now commence some more downloads, they could take some time.When Android Studio is ready you will have the option to run Android Studio. At this point click the Finish button. Android Studio is ready- probably. You can leave it open if you are carrying straight on with the next section or you can close it and then reopen it when instructed in the next section.

Final step

Using your preferred file manager software, perhaps Windows Explorer, Create a folder called AndroidProjects. Make it at the root of the same drive where you installed Android Studio. So, if you installed Android Studio at C:/Program Files/Android then create your new folder as C:/AndroidProjects.

Or if you installed Android Studio at D:/Program Files/Android then create your new folder as D:/AndroidProjects.

Note

Note that the screen shots in the next section show the AndroidProjects folder on the D: drive. This is because my C: drive is a bit full-up. Either is fine. Keeping it on the same drive as the Android installation is neater and could avoid future problems so do so if you can.

Tip

Notice that there is no space between the words Android and Projects and that the first letter of both words is capitalized.

Starting the first project: Sub' Hunter

Now we can get started on the first game. I will go into a lot more detail about what exactly Sub' Hunter does and how it is played but for now, let's just build something and see our first Android game start to take shape. Then we can run it on an emulator and a real device.

Note

The complete code as it stands at the end of this chapter is in the download bundle in the Chapter 1 folder. Note however that you still need to go through the project creation phase explained in this chapter (and at the beginning of all projects) as Android Studio does lots of work that we can't see.

Follow these steps to start the project:

Run Android Studio in the same way you run any other app. On Windows 10, for example, the launch icon appears in the start menu.

Tip

If you are prompted to Import Studio settings from:, choose Do not import settings.

You will be greeted with the Android Studio welcome screen as shown in the next image. Locate the Start a new Android Studio project option and left-click it.After this, Android Studio will bring up the New Project window. This is where we will:
Name the new project Choose where on our computer the project files should go Provide a Company domain to distinguish our project from any others in case we should ever decide to publish the game on the Play store

The name of our project is going to be Sub Hunter and the location for the files will be your AndroidProjects folder that we created in the Setting up Android Studio section.

The company domain can be almost anything you like. If you have a website, you could use the format. Yourdomain.com. If not, feel free to use gamecodeschool.com or something that you just make up yourself. It is only important when you come to publish.

To be clear in case you can't see the details in the next image clearly, here are the values I used. Remember that yours might vary depending upon your choices for company domain and project location.

Option

Value entered

Application name:

Sub Hunter

Company domain:

gamecodeschool.com

Include C++ support

Leave this option unchecked (see the next information box if you want to know more)

Project location:

D:\AndroidProjects\SubHunter

The next picture shows the New Project screen once you have entered all the information. In the previous image, you can see that Android Studio has auto-generated a Package name: based on the information entered. Mine is com.gamecodeschool.subhunter. Yours might be the same or not, it doesn't matter.

Note