Book Image

Learning Java by Building Android Games - Second Edition

By : John Horton
Book Image

Learning Java by Building Android Games - Second Edition

By: John Horton

Overview of this 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.
Table of Contents (30 chapters)
Learning Java by Building Android Games Second Edition
Contributors
Preface
Index

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 Runnable interface, 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:

  1. Log in or register at http://www.packtpub.com.

  2. Select the SUPPORT tab.

  3. Click on Code Downloads & Errata.

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

  • Zipeg / iZip / UnRarX for Mac

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

Note

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.