Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Java by Building Android Games - Third Edition

You're reading from  Learning Java by Building Android Games - Third Edition

Product type Book
Published in Mar 2021
Publisher Packt
ISBN-13 9781800565869
Pages 686 pages
Edition 3rd Edition
Languages
Author (1):
John Horton John Horton
Profile icon John Horton

Table of Contents (24) Chapters

Preface 1. Chapter 1: Java, Android, and Game Development 2. Chapter 2: Java – First Contact 3. Chapter 3: Variables, Operators, and Expressions 4. Chapter 4: Structuring Code with Java Methods 5. Chapter 5: The Android Canvas Class – Drawing to the Screen 6. Chapter 6: Repeating Blocks of Code with Loops 7. Chapter 7: Making Decisions with Java If, Else, and Switch 8. Chapter 8: Object-Oriented Programming 9. Chapter 9: The Game Engine, Threads, and the Game Loop 10. Chapter 10: Coding the Bat and Ball 11. Chapter 11: Collisions, Sound Effects, and Supporting Different Versions of Android 12. Chapter 12: Handling Lots of Data with Arrays 13. Chapter 13: Bitmap Graphics and Measuring Time 14. Chapter 14: Java Collections, the Stack, the Heap, and the Garbage Collector 15. Chapter 15: Android Localization – Hola! 16. Chapter 16: Collections and Enumerations 17. Chapter 17: Manipulating Bitmaps and Coding the Snake Class 18. Chapter 18: Introduction to Design Patterns and Much More! 19. Chapter 19: Listening with the Observer Pattern, Multitouch, and Building a Particle System 20. Chapter 20: More Patterns, a Scrolling Background, and Building the Player's Ship 21. Chapter 21: Completing the Scrolling Shooter Game 22. Chapter 22: What Next? 23. Other Books You May Enjoy

Chapter 1: Java, Android, and Game Development

Welcome to Learning Java by Building Android Games (Third Edition). In this first chapter, we will delve straight into Java, Android, and game development. By the end, you will have built and deployed the first part of the first game, and you will also have a great insight into what you will achieve in this book going forward.

Additionally, we will look at some diagrams and an outline of each of the five games that we will develop throughout the book.

Furthermore, 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 that we can build and deploy the outline for our first game.

Important note

It is my aim to keep this book up to date. Please check the following web page for further discussions and tips on any changes to Android Studio...

Technical requirements

The following are the official technical requirements for Android development with Android Studio and its related tools. However, these are the absolute bare minimum requirements. Please refer to the Setting up Android Studio section for further details.

Windows

  • Microsoft® Windows® 7/8/10 (64 bit)
  • 4 GB RAM minimum; 8 GB RAM recommended
  • 2 GB of available disk space minimum; 4 GB recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Mac

  • Mac® OS X® 10.10 (Yosemite) or higher, up to 10.14 (macOS Mojave)
  • 4 GB RAM minimum; 8 GB RAM recommended
  • 2 GB of available disk space minimum; 4 GB recommended (500 MB for IDE + 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Linux

  • GNOME or KDE desktop

    Tested on gLinux, based on Debian.

  • 64-bit distribution capable of running 32-bit applications...

What's new in the third edition?

The second edition saw a massive overhaul and a doubling of the number of games built compared to the first edition. Unfortunately, there are only so many pages that can fit inside a paperback book. Therefore, this edition focuses on improving the way Java, Android, and game development concepts are taught. I have rethought the way these topics are explained and have made it more visual than before. In addition to this, I have managed to squeeze in about a dozen new mini topics. These are either Java fundamentals, such as variable types, which were not covered in earlier editions; new Android Studio features, such as the profiler; or classic programming concepts that never quite made it in before, such as method recursion.

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. However, quite quickly, through diverse handset offers that struck a chord with the practical price-conscious and the fashion-conscious and tech-savvy, Android user numbers exploded.

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

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. Programming can be fun, and I have been programming all my life. However, creating games, especially for Android, is somehow extraordinarily rewarding.

Explaining exactly why this is is quite difficult. Maybe it is the fact that the platform is free and open. You can distribute your games without requiring the permission of a big controlling corporation – nobody can...

The games we will build

Let's take a look at some useful screenshots and get a little bit more detail about each of the games from the book. We will go into further details and explanations as we start each project.

Sub' Hunter

The first game we build will allow us to introduce some key Java beginner's topics, including code comments, variables, operators, methods, loops, generating random numbers, if, else, switch, and a brief introduction to Object-Oriented Programming (OOP). We will also learn how to communicate with the Android operating system, detect screen touches, draw simple graphics, manage the screen resolution, and handle different screen sizes. All of this will be used to build a simpler variation of the classic Minesweeper game. Here is a screenshot of our game:

Figure 1.1 – The Sub' Hunter game

This will be a tap-to-shoot game where the player has to guess the position of the sub', then refine their next...

How Java and Android work together

Before we start our Android quest, we need to understand how Android and Java work together.

Android is a complex system, but you do not need to understand it in depth in order to make amazing apps.

After we write a program, in Java, for Android, we click on a button, and our code is transformed into another form – the form that is understood by Android. This other form is called bytecode, and the transformation process is called compiling. The reason you can use the Kotlin programming language to write Android apps is that it directly compiles to the same bytecode as Java. In fact, Java can be translated to Kotlin with the click of a button.

Then, when the user installs our application, the bytecode is translated by another process, known as the Android Runtime (ART), into machine code. This is the fastest possible execution format. So, if you have ever heard people saying that you shouldn't use Java because it is slow, then...

Setting up Android Studio

Setting up Android Studio is quite straightforward if a little lengthy. Grab a refreshment and get started with the following steps. This tutorial will install Android Studio to the D drive. I chose the D drive because it is a big installation – approximately 12 GB once we have everything downloaded – and the D drive on many PCs is typically larger and has more free space than the C drive. Should you wish to install Android Studio on the C drive (or any other drive), then these instructions should be easy to adjust.

Visit https://developer.android.com/studio and click on the Download Android Studio button. This will begin the download of the latest stable version for Windows. You will need to accept the terms and conditions to commence the download.

While you are waiting for the download to complete, create a new folder at the root of your D drive, called Android. Inside the Android folder, create another new folder, called Android Studio...

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. However, for now, let's just build something and see our first Android game start to take shape.

Important note

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

Follow these steps to start the project:

  1. Run Android Studio (if it isn't running already) in the same way you would 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.

  2. You will be greeted with the Android Studio welcome screen...

Android Studio and our project – a very brief guided tour

I won't go into all of the dozens of different windows and menu options because we will cover them as needed. However, here are a few details to help you begin familiarizing yourself with Android Studio.

Take a look at the following screenshot. You will notice two major sections – one section on the left and a larger window on the right:

Figure 1.13 – Project panel and Editor window

Let's take a look at the panel on the left.

The Project panel

The panel on the left can be changed into various different views. We will need it just as it is for virtually the whole book. This is the Project panel/window. Let's take a closer look:

Figure 1.14 – The Project panel folders and sub-folders

As you can see, there are several folders and sub-folders. For around 90 percent of every project, we will only need one folder. The folder I am...

Refactoring MainActivity to SubHunter

It is a good practice to use meaningful names for all the different parts of our code. We will see this as we progress through the projects. For now, I think MainActivity is a bit vague and inconclusive. We could make do with it, but let's rename it to something more meaningful. This will also allow us to see how we can use the refactoring tool of Android Studio. The reason that we use the term "refactoring" instead of just "renaming" is that when we change the names we use in our code, there is often much more than just a simple name change going on behind the scenes. For example, later, when we refactor the MainActivity filename to SubHunter, Android Studio will change the name of the file as well as some code in the AndroidManifest.xml file and the MainActivity.java (which will soon be SubHunter.java) file.

In the Project panel, right-click on the MainActivity file and select Refactor | Rename. In the pop-up window...

Locking the game to full screen and landscape orientation

We want to use every pixel that the player's Android device has to offer, so we will make changes to the AndroidManifest.xml file. This allows us to use a style for our app that hides all of the default menus and titles from the user interface.

Make sure that the AndroidManifest.xml file is open in the Editor window. If you followed along with the previous section, then it will be open already.

In the AndroidManifest.xml file, locate the following line of code:

<android:name=".SubHunter">

Place the cursor before the closing > character, as shown in the preceding code. Press the Enter key a couple of times to move the > character a couple of lines below the rest of the line.

Immediately underneath ".SubHunter", but before the newly positioned >, type in or copy and paste this next line of code. This will make the game run without any user interface.

Note that the line...

Amending the code to use the full screen and the best Android class

When you write code for Android, you will always be working within the confines of the operating system. As there are so many variations of Android apps, it makes sense that the Android team would supply lots of different options for us. We will now make a few minor changes so that we are using the most efficient code possible.

When we generated the project, Android Studio built a project that was more ideally suited to a regular app with a conventional user interface. We have already hidden the action bar by modifying the XML. Now we will make a couple of minor code changes in the SubHunter.java file to use an Android class that is more suited to game development.

Find the following line of code near the top of the SubHunter.java file:

import androidx.appcompat.app.AppCompatActivity;

Change the preceding line of code to the same as this following line of code:

import android.app.Activity;

Immediately...

Deploying the game so far

Before we can properly explain any of the code and learn our first bit of Java, you might be surprised to learn that we can already run our project. It will just be a blank screen, but as we will be running the game as often as possible to check our progress, let's learn how to do that now. You have three options:

  • Run the game on the emulator on your PC (this is part of Android Studio).
  • Run the game on a real Android device in USB debugging mode.
  • Export the game as a full Android project that can be uploaded to the Play Store.

The first option is the easiest to set up because we did it as part of setting up Android Studio. If you have a powerful PC, you will hardly see the difference between an emulator and a real device. However, screen touches are emulated by mouse clicks, so proper testing of the player's experience is not possible.

The second option that uses a real device has a couple more steps; however, once it is...

Summary

We have covered a lot of ground in this first chapter. We learned why games, Android, and Java are all useful and potentially profitable ways to learn how to program. We discovered how Android and Java work together, and we have taken a look at the five games that we will build throughout this book. Finally, we got started on the first game, Sub' Hunter, and deployed a blank project to an emulator and a real device.

In the next chapter, we will learn the first set of basics for Java and coding in general. Additionally, we will scratch the surface of some more advanced Java topics that we will keep coming back to throughout the book. These topics include OOP, classes, objects, and methods, and we will explore how these topics are intimately related.

Following this, we can then make sense of the code that Android Studio generated for us and that we modified (in SubHunter.java), and we can start to type our own code.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning Java by Building Android Games - Third Edition
Published in: Mar 2021 Publisher: Packt ISBN-13: 9781800565869
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}