Learning Java by Building Android Games - Second Edition

Book description

Get ready for a fun-filled experience of learning Java by developing games for the Android platform

Key Features

  • Learn Java, Android, and object-oriented programming from scratch
  • Build games including Sub Hunter, Retro Pong, Bullet Hell, Classic Snake, and a 2D Scrolling Shooter
  • Create and design your own games, such as an open-world platform game

Book Description

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.

What you will learn

  • Set up a game development environment in Android Studio
  • Implement screen locking, screen rotation, pixel graphics, and play sound effects
  • Respond to a player's touch, and program intelligent enemies who challenge the player in different ways
  • Learn game development concepts, such as collision detection, animating sprite sheets, simple tracking and following, AI, parallax backgrounds, and particle explosions
  • Animate objects at 60 frames per second (FPS) and manage multiple independent objects using Object-Oriented Programming (OOP)
  • Understand the essentials of game programming, such as design patterns, object-oriented programming, Singleton, strategy, and entity-component patterns
  • Learn how to use the Android API, including Activity lifecycle, detecting version number, SoundPool API, Paint, Canvas, and Bitmap classes
  • Build a side-scrolling shooter and an open world 2D platformer using advanced OOP concepts and programming patterns

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 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.

Table of contents

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

Product information

  • Title: Learning Java by Building Android Games - Second Edition
  • Author(s): John Horton
  • Release date: August 2018
  • Publisher(s): Packt Publishing
  • ISBN: 9781788839150