You are previewing Android Game Programming: A Developer’s Guide.
O'Reilly logo
Android Game Programming: A Developer’s Guide

Book Description

Extend your game development skills by harnessing the power of Android SDK

About This Book

  • Gain the knowledge to design and build highly interactive and amazing games for your phone and tablet from scratch

  • Create games that run at super-smooth 60 frames per second with the help of these easy-to-follow projects

  • Understand the internals of a game engine by building one and seeing the reasoning behind each of the components

  • Who This Book Is For

    If you are completely new to Java, Android, or game programming, this book is for you. If you want to publish Android games for fun or for business and are not sure where to start, then this book will show you what to do, step by step, from the start.

    What You Will Learn

  • Set up an efficient, professional game development environment in Android Studio

  • Explore object-oriented programming (OOP) and design scalable, reliable, and well-written Java games or apps on almost any Android device

  • Build simple to advanced game engines for different types of game, with cool features such as sprite sheet character animation and scrolling parallax backgrounds

  • Implement basic and advanced collision detection mechanics

  • Process multitouch screen input effectively and efficiently

  • Implement a flexible and advanced game engine that uses OpenGL ES 2 to ensure fast, smooth frame rates

  • Use animations and particle systems to provide a rich experience

  • Create beautiful, responsive, and reusable UIs by taking advantage of the Android SDK

  • Integrate Google Play Services to provide achievements and leaderboards to the players

  • In Detail

    Gaming has historically been a strong driver of technology, whether we're talking about hardware or software performance, the variety of input methods, or graphics support, and the Android game platform is no different. Android is a mature, yet still growing, platform that many game developers have embraced as it provides tools, APIs, and services to help bootstrap Android projects and ensure their success, many of which are specially designed to help game developers.

    Since Android uses one of the most popular programming languages, Java, as the primary language to build apps of all types, you will start this course by first obtaining a solid grasp of the Java language and its foundation APIs. This will improve your chances of succeeding as an Android app developer. We will show you how to get your Android development environment set up and you will soon have your first working game.

    The course covers all the aspects of game development through various engrossing and insightful game projects. You will learn all about frame-by-frame animations and resource animations using a space shooter game, create beautiful and responsive menus and dialogs, and explore the different options to play sound effects and music in Android. You will also learn the basics of creating a particle system and will see how to use the Leonids library.

    By the end of the course, you will be able to configure and use Google Play Services on the developer console and port your game to the big screen.

    This Learning Path combines some of the best that Packt has to offer in one complete, curated package. It includes content from the following Packt products:

  • Learning Java by Building Android Games by John Horton

  • Android Game Programming by Example by John Horton

  • Mastering Android Game Development by Raul Portales

  • Style and approach

    This course is a step-by-step guide where you will learn to build Android games from scratch. It takes a practical approach where each project is a game. It starts off with simple arcade games, and then gradually the complexity of the games keep on increasing as you uncover the new and advanced tools that Android offers.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

    Table of Contents

    1. Android Game Programming: A Developer's Guide
      1. Table of Contents
      2. Android Game Programming: A Developer's Guide
      3. Android Game Programming: A Developer's Guide
      4. Credits
      5. Preface
        1. What this learning path covers
        2. What you need for this learning path
        3. Who this learning path is for
        4. Reader feedback
        5. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      6. 1. Module 1
        1. 1. Why Java, Android, and Games?
          1. Is this book for me?
            1. If you just want to learn pure Java
            2. If Android is your focus
            3. Where this book will take you
          2. Why build games to learn to program?
          3. Why Android and Java?
            1. Android is the fastest evolving and growing OS ever
            2. Android developers have great prospects
            3. Android is open source
            4. Java is here to stay
            5. Java is not just for Android
            6. Java is fast and easy to use
            7. A summary of Java and Android
          4. Setting up our development environment
            1. Installing the JDK
            2. Android Studio
              1. Installing Android Studio
          5. Summary
        2. 2. Getting Started with Android
          1. Our first game project
            1. Preparing Android Studio
            2. Building the project
          2. Exploring Android Studio
          3. Using the Android Studio visual designer
            1. Android UI types
              1. TextView
              2. Layout elements
              3. ImageView widgets
              4. ButtonView
              5. Using the sample code
            2. Making our game menu
          4. Structuring our code for Android
            1. Life cycle phases – what we need to know
            2. Life cycle phases – what we need to do
              1. Dividing our game into activities
          5. Our first look at Java
            1. Cleaning up our code
          6. Building and installing our game
            1. Emulators and devices
              1. Creating an emulator
              2. Running the emulator
              3. Running our game on the emulator
            2. Building our game
            3. Installing the setup to a device
            4. Future projects
          7. Self-test questions
          8. Summary
        3. 3. Speaking Java – Your First Game
          1. Java syntax
            1. The compiler
            2. Making code clear with comments
          2. Storing data and using it with variables
            1. Types of variables
              1. Reference types
              2. Declaration
              3. Initialization
                1. Changing variables with operators
          3. Expressing yourself in Java
          4. Math game – asking a question
            1. Creating the new game activity
            2. Laying out the game screen UI
            3. Coding a question in Java
            4. Linking our game from the main menu
          5. Decisions in Java
            1. More operators
            2. Decision 1 – If they come over the bridge, shoot them
            3. Decision 2 – Else, do this
            4. Switching to make decisions
          6. Math game – getting and checking the answer
          7. Self-test questions
          8. Summary
        4. 4. Discovering Loops and Methods
          1. Looping with loops
            1. While loops
              1. Breaking out of a loop
              2. The continue keyword
            2. Do-while loops
            3. For loops
            4. Random numbers in Java
          2. Methods
            1. The structure of a method
              1. Modifier
              2. Return type
              3. Name of a method
              4. Parameters
              5. Getting things done in the method body
            2. Using methods
              1. A working method
              2. Exploring method overloading
          3. Enhancing our math game
            1. Enhancing the UI
            2. The new Java code
              1. Amending GameActivity
              2. The methods
              3. The setQuestion method
              4. The updateScoreAndLevel method
              5. The isCorrect method
              6. Calling our new methods
          4. Finishing touches
            1. Going full screen and locking orientation
            2. Adding a custom image (instead of the Android icon)
          5. Self-test questions
          6. Summary
        5. 5. Gaming and Java Essentials
          1. Java arrays – an array of variables
            1. Arrays are objects
              1. A simple example of an array
            2. Getting dynamic with arrays
              1. Dynamic array example
            3. Entering the nth dimension with arrays
              1. An example of a multidimensional array
              2. Array-out-of-bounds exceptions
          2. Timing with threads
            1. A simple thread timer example with the Handler class
          3. Beeps n buzzes – Android sound
            1. Creating sound FX
              1. Playing sounds in Android
          4. Life after destruction – persistence
            1. An example of persistence
          5. The memory game
            1. Phase 1 – the UI and the basics
            2. Phase 2 – preparing our variables and presenting the pattern
            3. Phase 3 – the player's response
            4. Phase 4 – preserving the high score
            5. Animating our game
              1. UI animation in Android
              2. Phase 5 – animating the UI
          6. Self-test questions
          7. Summary
        6. 6. OOP – Using Other People's Hard Work
          1. What is OOP?
            1. Why do it like this?
          2. Our first class and first object
            1. Basic classes
            2. More things we can do with our first class
          3. Encapsulation
            1. Controlling the use of classes with access modifiers
              1. Class access in a nutshell
            2. Controlling the use of variables with access modifiers
              1. Variable access in a nutshell
            3. Methods have access modifiers too
              1. Method access in a nutshell
            4. Accessing private variables with the getter and setter methods
            5. Setting up our objects with constructors
            6. Variables revisited
              1. The stack and the heap
              2. A quick break to throw out the trash
              3. Access, scope, this, static, and constructors demo
              4. A quick summary on stack and heap
          4. Inheritance
            1. An example of inheritance
          5. Polymorphism
            1. Abstract classes
            2. Interfaces
          6. More about OOP and classes
            1. Inner classes
          7. Self-test questions
          8. Summary
        7. 7. Retro Squash Game
          1. Drawing with Android Canvas
            1. The Android coordinate system
              1. Animating our pixels
            2. Getting started with Canvas and Paint
          2. Android Canvas demo app
          3. Detecting touches on the screen
          4. Preparing to make the retro squash game
            1. The design of the game
              1. The UI
              2. Physics
              3. The structure of the code
          5. The four implementation phases in detail
            1. Phase 1 – MainActivity and onCreate
              1. Phase 1 code explained
            2. Phase 2 – SquashCourtView part 1
              1. Phase 2 code explained
            3. Phase 3 – SquashCourtView part 2
              1. Phase 3 code explained
            4. Phase 4 – Remaining lifecycle methods
            5. Good object-oriented design
          6. Self-test questions
          7. Summary
        8. 8. The Snake Game
          1. Game design
          2. The coordinate system
            1. Keeping track of the snake segments
            2. Detecting collisions
            3. Drawing the snake
          3. The code structure
            1. MainActivity
            2. GameActivity
              1. Tidying up onCreate
          4. Animation, sprite sheets, and the Snake home screen
            1. Animating with sprite sheets
              1. Implementing the Snake home screen
          5. Implementing the Snake game activity
          6. Enhancing the game
          7. Self-test questions
          8. Summary
        9. 9. Making Your Game the Next Big Thing
          1. How to publish your app
          2. Marketing your app
          3. Adding leaderboards and achievements
            1. Planning the Snake achievements
            2. Step-by-step leaderboards and achievements
              1. Installing the Google Play Services API on your PC
              2. Configuring the Google Play developer console
              3. Implementing the leaderboard in the Google Play developer console
              4. Implementing the achievements in the Google Play developer console
              5. Setting up the Snake project ready for implementation
              6. Implementing the player's sign-in, achievements, and leaderboard buttons
              7. Implementing the leaderboards in code
              8. Implementing the achievements in code
              9. Uploading the updated Snake game to Google Play
          4. What next?
            1. Getting a programmer's job
            2. Building bigger and better games
          5. Self-test questions
          6. Summary
        10. A. Self-test Questions and Answers
          1. Chapter 2
          2. Chapter 3
          3. Chapter 4
          4. Chapter 5
          5. Chapter 6
          6. Chapter 7
          7. Chapter 8
          8. Chapter 9
      7. 2. Module 2
        1. 1. Player 1 UP
          1. A closer look at the games
            1. Tappy Defender
            2. Tough retro platformer
            3. Asteroids simulator
          2. Setting up your development environment
            1. Installing the JDK
            2. Installing Android Studio
          3. Summary
        2. 2. Tappy Defender – First Step
          1. Planning the first game
            1. Backstory
            2. The game mechanics
            3. Rules for the game
            4. The design
              1. Control
              2. Model
              3. View
              4. Design pattern reality check
            5. The game code structure
              1. The Android Activity lifecycle
            6. The Android Studio file structure
          2. Building the home screen
            1. Creating the project
              1. What we did
            2. Building the home screen UI
              1. What we did
            3. Coding the functionality
            4. Creating GameActivity
              1. What we did
            5. Configuring the AndroidManifest.xml file
              1. What we did
          3. Coding the game loop
            1. Building the view
              1. Creating a new class for the view
              2. What we did
              3. Structuring the class code
            2. The game activity
          4. The PlayerShip object
          5. Drawing the scene
            1. Plotting and drawing
            2. Drawing PlayerShip
              1. The Canvas and Paint objects
            3. Controlling the frame rate
          6. Deploying the game
            1. Debugging on an Android device
          7. Summary
        3. 3. Tappy Defender – Taking Flight
          1. Controlling the spaceship
            1. Detecting touches
            2. Adding boosters to the spaceship
            3. Detecting the screen resolution
          2. Building the enemies
            1. Designing the enemy
            2. Spawning the enemy
            3. Making the enemy think
          3. The thrill of flight – scrolling the background
          4. Things that go bump – collision detection
            1. Collision detection options
              1. Rectangle intersection
              2. Radius overlapping
              3. The crossing number algorithm
            2. Optimizations
              1. Multiple hitboxes
              2. Neighbor checking
            3. Best options for Tappy Defender
          5. Summary
        4. 4. Tappy Defender – Going Home
          1. Displaying a HUD
          2. Implementing the rules
          3. Ending the game
            1. Restarting the game
          4. Adding sound FX
            1. Generating the FX
            2. The SoundPool class
            3. Coding the sound FX
          5. Adding persistence
          6. Iteration
            1. Multiple different enemy graphics
            2. An exercise in balance
            3. Format time
            4. Handle the back button
          7. The finished game
          8. Summary
        5. 5. Platformer – Upgrading the Game Engine
          1. The game
            1. The backstory
            2. The game mechanics
            3. Rules for the game
          2. Upgrading the game engine
            1. The platform activity
            2. Locking the layout to landscape
            3. The PlatformView class
              1. The basic structure of PlatformView
              2. The GameObject class
              3. The view through a viewport
              4. Creating the levels
              5. The enhanced update method
              6. The enhanced draw method
          3. Summary
        6. 6. Platformer – Bob, Beeps, and Bumps
          1. The SoundManager class
          2. Introducing Bob
          3. Multiphase collision detection
          4. Player input
          5. Animating Bob
          6. Summary
        7. 7. Platformer – Guns, Life, Money, and the Enemy
          1. Ready aim fire
            1. Pickups
              1. The drone
              2. The guard
          2. Summary
        8. 8. Platformer – Putting It All Together
          1. Bullet collision detection
          2. Adding some fire tiles
          3. Eye candy
            1. The new platform tiles
            2. The new scenery objects
            3. Scrolling parallax backgrounds
            4. Pause menu with moveable viewport
            5. Levels and game rules
              1. Traveling between levels
            6. The level designs
              1. The cave
              2. The city
              3. The forest
              4. The mountains
              5. The HUD
          4. Summary
        9. 9. Asteroids at 60 FPS with OpenGL ES 2
          1. Asteroids simulator
            1. The game controls
            2. Rules for the game
          2. Introducing OpenGL ES 2
            1. Why use it and how does it work?
            2. What is neat about Version 2?
            3. How we will use OpenGL ES 2?
          3. Preparing OpenGL ES 2
            1. Locking the layout to landscape
            2. Activity
            3. The view
            4. A class to manage our game
            5. Managing simple shaders
            6. The game's main loop – the renderer
          4. Building an OpenGL-friendly, GameObject super class
          5. The spaceship
          6. Drawing at 60 + FPS
          7. Summary
        10. 10. Move and Draw with OpenGL ES 2
          1. Drawing a static game border
          2. Twinkling stars
          3. Bringing the spaceship to life
          4. Rapid fire bullets
          5. Reusing existing classes
            1. Adding the SoundManager class
            2. Adding the InputController class
          6. Drawing and moving the asteroids
          7. Scores and the HUD
            1. Adding control buttons
            2. Tally icons
            3. Life icons
              1. Declaring, initializing, and drawing the HUD objects
          8. Summary
        11. 11. Things That Go Bump – Part II
          1. Planning for collision detection
            1. Colliding with the border
              1. The first phase of border collision detection
            2. Colliding with an asteroid
              1. The crossing number
              2. The first phase and overview of asteroid collision detection
            3. The CollisionPackage class
              1. Adding collision packages to the objects and making them accessible
                1. Adding a collision package to the Bullet class
                2. Adding a collision package to the SpaceShip class
                3. Adding a collision package to the Asteroid class
            4. The CD class outline
              1. Implementing radius overlapping for asteroids and ships
              2. Implementing rectangle intersection for the border
          2. Performing the checks
            1. Helper methods
              1. Destroying a ship
              2. Destroying an asteroid
            2. Testing for collisions in update()
          3. Precise collision detection with the border
          4. Precise collision detection with an asteroid
          5. Finishing touches
          6. Summary
      8. 3. Module 3
        1. 1. Setting Up the Project
          1. The right tool for the right game
            1. Do you want to use 3D?
            2. Do you want to use physics?
            3. Do you want to use Java?
            4. Pros of building games with the Android SDK
            5. Cons of building games with the Android SDK
            6. I want the Android SDK!
          2. The project – YASS (Yet Another Space Shooter)
            1. Activities and Fragments
            2. Project setup
              1. Creating the stub project
              2. Cleaning up
            3. Choosing an orientation
              1. Dealing with aspect ratios
          3. Game architecture
            1. GameEngine and GameObjects
              1. Starting a game
              2. Stopping a game
              3. Managing game objects
            2. UpdateThread
            3. DrawThread
            4. User input
          4. Putting everything together
          5. Moving forward with the example
            1. Handling the back key
            2. Honoring the lifecycle
            3. Using as much screen as we can
              1. Before Android 4.4 – almost fullscreen
              2. Android 4.4 and beyond – immersive mode
              3. Putting fullscreen together
          6. Good practices for game developers
            1. Object pools
            2. Avoiding enhanced loop syntax in lists
            3. Precreating objects
            4. Accessing variables directly
            5. Being careful with floating points
            6. Performance myths – avoid interfaces
          7. Summary
        2. 2. Managing User Input
          1. The InputController base class
            1. The Player object
              1. Displaying a spaceship
              2. Firing bullets
            2. The Bullet game object
          2. The most basic virtual keypad
            1. Limitations and problems
          3. Creating a virtual joystick
            1. General considerations and improvements
          4. Physical controllers
            1. Handling MotionEvents
            2. Handling KeyEvents
            3. Detecting gamepads
          5. Sensors and InputControllers
          6. Selecting control modes
          7. Summary
        3. 3. Into the Draw Thread
          1. Using GameView
            1. The GameView interface
            2. StandardGameView
            3. SurfaceGameView
            4. Updating GameEngine
            5. Updating the game layout
          2. Improving DrawThread
          3. Sprites
            1. Updating the spaceship and bullets
          4. Adding a frames-per-second (fps) counter
          5. Spawning enemies – the GameController
            1. Procedural/random
            2. Deterministic/static
            3. Hybrid approach
            4. Our approach
            5. The asteroids
              1. More on the transformation matrix
          6. Occlusion culling
          7. Parallax backgrounds
            1. Multiple backgrounds
          8. Layers
          9. Summary
        4. 4. Collision Detection
          1. Detecting collisions
            1. Who can collide?
            2. Updating GameEngine
            3. Handling collisions
          2. Rectangular bodies
            1. Adding visual feedback
            2. Pros and cons
          3. Circular bodies
            1. Adding visual feedback
            2. Pros and cons
          4. Mixed collision detection
            1. Adding visual feedback
            2. Other options for shapes
            3. Optimization
            4. Spatial partitioning and QuadTree
              1. Duplicated collisions
          5. Summary
        5. 5. Particle Systems
          1. General concepts
            1. Particles
            2. ParticleSystem
            3. Initializers
            4. Modifiers
            5. Composite GameObjects and GameEngine
          2. Making good particle systems
          3. One shot
            1. Asteroid explosions
            2. Spaceship explosions
          4. Emitters
            1. Asteroid trails
            2. The spaceship's engine
          5. Summary
        6. 6. Sound FX and Music
          1. SoundManager
          2. Sound FX
            1. How to create sound FXs
            2. GameEvents
            3. Using SoundPool
          3. Playing music
            1. Obtaining music
            2. MediaPlayer
            3. Music and Activity life cycle
          4. Enabling and disabling music and sound FX
            1. Updating MainMenuFragment
            2. Updating SoundManager
          5. Disabling system sounds
          6. Summary
        7. 7. Menus and Dialogs
          1. Custom fonts
          2. Working with backgrounds
            1. The power of XML drawables
            2. State list drawables
              1. State lists colors
            3. Shape drawables
          3. The GameFragment
            1. Adding a score
            2. Adding lives
          4. Custom dialogs
            1. BaseCustomDialog
            2. Quit dialog
            3. Pause dialog
            4. Game Over dialog
            5. Other dialogs
          5. Designing for multiple screen sizes
          6. Summary
        8. 8. The Animation Framework
          1. Updating BaseFragment
          2. AnimationDrawable
            1. Animated sprites
            2. Animating views
            3. XML versus code
            4. Interpolators
          3. View animation
            1. Animating dialogs
              1. Delaying the action in the dialogs to onDismissed
            2. Pulsating buttons
          4. Property animation
            1. ViewPropertyAnimator
              1. Moving a spaceship around
            2. Animating the main menu
          5. Summary
        9. 9. Integrating Google Play Services
          1. Setting up the developer console
          2. Setting up the code
          3. Achievements
            1. Architecture
            2. Unlocking achievements
          4. Leaderboards
          5. Opening the Play Games UI
          6. Other features of Google Play services
            1. Events
            2. Quests
            3. Gifts
            4. Saved games
            5. Multiplayer games
          7. Summary
        10. 10. To the Big Screen
          1. Project configuration
          2. Testing for Android TV
          3. Declaring a TV Activity
          4. Providing a home screen banner
          5. Declaring it as a game
            1. Declaring Leanback support
            2. Declaring touchscreen capability as not required
          6. Reviewing the manifest
          7. Showing controller instructions
            1. Dealing with overscan
            2. Controller-based navigation
            3. Dialogs and controllers
          8. Beyond this book
          9. Summary
        11. A. API Levels for Android Versions
      9. A. Bibliography
      10. Index