Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning Java by Building Android  Games
Learning Java by Building Android  Games

Learning Java by Building Android Games: Learn Java and Android from scratch by building six exciting games , Second Edition

eBook
AU$36.99 AU$53.99
Paperback
AU$67.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learning Java by Building Android Games

Chapter 1. Java, Android and Game Development

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

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

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

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

In summary this chapter will cover:

  • Why choose the combination of Java, Android, and games?
  • Look at the six neat games we will use to learn Java and Android
  • How Java and Android work together
  • Setting up the Android Studio development environment
  • Building and running a blank game project on the Android emulator or a real device

Let's get started.

What's new in the second edition?

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

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

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

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

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

Why Java, Android and Games?

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

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

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

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

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

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

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

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

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

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

Java: The first stumbling block

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

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

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

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

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

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

Tip

Plus, you get to blow stuff up!

The games you will build

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

Sub' Hunter

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

Sub' Hunter

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

Pong

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

Pong

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

Bullet Hell

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

Bullet Hell

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

Snake Clone

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

Snake Clone

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

Scrolling Shooter

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

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

Scrolling Shooter

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

Open-World Platformer

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

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

Open-World Platformer

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

Open-World Platformer

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

How Java and Android work

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

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

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

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

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

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

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

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

How Java and Android work

Tip

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

Let's set up Android Studio.

Setting up Android Studio

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

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

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

    Tip

    Write down a note of where you choose

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

Final step

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

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

Note

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

Tip

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

Starting the first project: Sub' Hunter

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

Note

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

Follow these steps to start the project:

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

    Tip

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

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

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

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

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

    Option

    Value entered

    Application name:

    Sub Hunter

    Company domain:

    gamecodeschool.com

    Include C++ support

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

    Project location:

    D:\AndroidProjects\SubHunter

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

    Note

    You can write Android apps and games in a few different languages including C++ and Kotlin. There are various advantages and disadvantages to each compared to using Java. Learning Java will be a great introduction to other languages and Java is also the official language of Android. Most top apps and games on the Play store are written in Java.

  7. Click the Next button and we will continue to configure the Sub Hunter project. The following set of options is the Target Android Devices window. We can leave the default options selected as we are only making games for Phone and Tablet. The Minimum SDK option can be left as it is because it means our game will run on most (nearly all) Android devices from Android 4 to the latest version.

    Note

    If you are reading this some years in the future, then the Minimum SDK option will probably default to something different but the code in this book will still work.

  8. This next picture shows the Target Android Devices window we have just discussed, mainly just for your reference.
    Starting the first project: Sub' Hunter
  9. Click the Next button and we will move on.
  10. The window that follows has the slightly obscure-sounding title, Add an Activity to Mobile. These are some useful project templates that Android Studio can generate for you depending on the type of app you are going to develop.

    We will learn about Android Activity as the book progresses, but we are making games and want to control every pixel, beep and player input. For this reason, we will use the Empty Activity option. Android Studio will auto-generate a small amount of code to get our project started. Here is a picture of the Add an Activity to Mobile screen with the Empty Activity option selected.

    Starting the first project: Sub' Hunter
  11. Make sure Empty Activity is selected and click Next.
  12. On the Customize Activity screen which you should now be looking at, we have a few changes to make. We could leave the defaults but then Android would generate more files than we need. In addition, we want to change the Activity Name to something more appropriate than MainActivity. Follow this short list of changes to configure the Customize Activity screen:
    • Rename the Activity Name: to SubHunter
    • Uncheck the Generate Layout File option – we do not want a layout generated as we will be laying out every pixel ourselves
    • Uncheck Backwards Compatibility (AppCompat) we won't need it for our games and they will still run on almost every phone and tablet
  13. This is what the Customize the Activity screen should look like when you're done:
    Starting the first project: Sub' Hunter
  14. Finally, for this section, you can click the Finish button and we will explore a little of what we (and Android Studio) have just done.

At this stage you might be ready to proceed but depending on the install process you might need to click a couple of extra buttons. This is why I mentioned that we are "probably" finished installing and setting up. Look in the bottom window of Android Studio and see if you have the following message.

Note

Note that if you do not see a horizontal window at the bottom of Android Studio like the one shown below you can skip these two extra steps.

Extra step 1

Extra step 1

If you do, click Install missing platform(s) and sync project, accept the license agreement and click Next followed by Finish.

Extra step 2

If you get another message like this:

Extra step 2

Click Install Build tools…. Then click Finish.

Tip

You can tidy up a bit and close this bottom horizontal window by clicking the Messages tab on the very bottom of Android Studio, but this isn't required.

Android Studio and our project – A very brief guided tour

I won't go into all the dozens of different windows and menu options because we will cover them as we need them but here are a few details to help begin getting familiar with Android Studio.

Have a look at the screen below and you will notice two major sections. One on the left and a larger window on the right:

Android Studio and our project – A very brief guided tour

Let's have a look at the panel on the left

The Project panel

The panel on the left can be changed to 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.

The Project panel

As you can see there are a few folders and sub-folders. For around 90% of every project, we will only need one folder. The folder I am referring to is the Java | com.gamecodeschool.subhunter folder. It is the one with the SubHunter file in it. The little blue C icon to the left of SubHunter indicates that this file is a class and we will explore classes throughout the entirety of this book. The extension of all class files is .java. The extension for class files is not shown in the Project panel. All we need to know for now is that a class file is a file with code in it.

Notice that below the com.gamecodeschool.subhunter folder (with the SubHunter class file in it) there are two more folders with the same name. These folders, however, are postfixed with the words (androidTest) and (test), respectively. Whenever we add new code files it will always be to the top folder, the one without any prefix, that contains the SubHunter class/file.

Feel free to explore the other folders. We will also be using the res folder in later projects to add sound files and graphics. We will be making brief adjustments to the file in the manifests folder in a moment as well.

The important points to take away from this section is that this is the Project panel and all our code will go in the top com.gamecodeschool.subhunter folder. If you entered a different company domain back in the Starting the first project – Sub Hunter section, then the name of the folders in your Project panel will be different but the exact same principle applies – use the top one.

Let's explore the place where the real action happens – the Editor window.

The Editor window

This is where, as the name suggests, we will edit our code. Typically, we will add multiple code files to the com.gamecodeschool.subhunter folder and add code to them through the editor window. We can have multiple code files ready for editing at once. Have a look at the next image of the code editor as it stands now.

The Editor window

Now, in preparation for the next section, open the manifests folder at the top of the Project panel. You do this by left-clicking on the little triangle to the left of the folder. I have highlighted this in the next image.

The Editor window

Inside the manifests folder, there is a single file, AndroidManifest.xml. Double-click the file and notice that it has been opened in the editor window and that we now have two tabs so that we can quickly switch between AndroidManifest.xml and SubHunter.java. This next image makes this clear.

The Editor window

Also, note that you can now see the .java extension of SubHunter. Now that we know where our code files will go, how to get to them and how to edit them we can move on to the Sub Hunter project.

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 which allows us to make configuration changes.

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

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

android:name=".SubHunter">

Place the cursor before the closing > shown above. Tap the Enter key a couple of times to move the > a couple of lines below the rest of the line shown above.

Immediately below ".SubHunter" but before the newly positioned > type or copy and paste these two lines to make the game run full screen and lock it in the landscape orientation.

android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:screenOrientation="landscape"

This is a fiddly set of steps and it is the first code we have edited in the book so here I am showing you a bigger range of this file with the code we just added highlighted amongst it.

…
<activity android:name=".SubHunter"
   android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
   android:screenOrientation="landscape"
   >
   <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
</activity>
…

Tip

The code we have just written and the rest of the contents of AndroidManifest.xml we call XML (extensible markup language). Android uses XML for several different configurations. It is not necessary to learn this language as to make all the projects in this book this minor modification is all we will ever need to do.

Now our game will use all the screen space the device makes available and the screen has been locked in landscape mode even if the player holds their device in portrait orientation.

Deploying the game so far

Before we explore 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 see how to do that now. You have three options:

  • Run the game on the Emulator on your PC (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 the emulator and a real device. However, screen touches are emulated by mouse clicks and proper testing of the player's experience is not possible.

The second option using a real device has a couple more steps but once set up, is as good as option one and the screen touches are for real.

The final option takes a few minutes (at least) to prepare and then you need to manually put the created package onto a real device and install it.

Probably the best way is to use the emulator to quickly test minor increments in your code and then fairly regularly use USB debugging mode on a real device to make sure things are still as expected. Only occasionally will you want to export an actual deployable package.

Tip

If you have an especially slow PC or a particularly aging Android device, you will be fine just running the projects in this book using just one option or the other. Note that a slow Android phone will probably be OK and cope, but a very slow PC will probably not handle the emulator running games and you will benefit from running the games on your phone/tablet – especially the later games.

For these reasons, I will now go through how to run the game using the emulator and USB debugging on a real device.

Running the game on an Android emulator

Follow these simple steps to run the game on the default Android emulator.

  1. On the Android Studio menu bar select Tools | Android AVD Manager. AVD stands for Android Virtual Device (an emulator). You will see the following window.
    Running the game on an Android emulator
  2. Notice there is an emulator in the list. In my case, it is Pixel API 25 if you are following this sometime in the future it will probably be a different emulator that was installed by default. It won't matter. Click the green play icon shown in the next image and wait while the emulator boots up.
    Running the game on an Android emulator
  3. Now you can see the emulator as shown in the next image. Note also in the next image I have highlighted one of the icons in the control panel to the right of the emulator. Click that icon to rotate the phone into landscape mode ready to run the game.
    Running the game on an Android emulator
  4. Now you can click the play icon on the Android Studio quick-launch bar as shown in the next image and when prompted choose Pixel API 25 (or whatever your emulator is called) and the game will launch on the emulator.
    Running the game on an Android emulator

You're done. Here is what the running game looks like so far:

Running the game on an Android emulator

Clearly, we have more work to do but it is a good start. Let's see how to do the same on a real device and then we can go about building Sub' Hunter further.

Running the game on a real device

The first thing to do is to visit your device manufacturer's website and obtain and install any drivers that are needed for your device and operating system.

Tip

Most newer devices won't need a driver. So you may want to just try the following steps first.

The next few steps will set up the Android device for debugging. Note that different manufacturers structure the menu options slightly differently to others. But the following sequence is probably very close, if not exact for enabling debugging on most devices:

  1. Tap the Settings menu option or the Settings app on your phone/tablet
  2. This next step will vary slightly for different versions of Android. The Developer options menu is hidden away so as not to trouble regular users. You must perform a slightly odd task to unlock the menu option. Tap the About device or About Phone option. Find the Build Number option and repeatedly tap it until you get a message informing you that You are now a developer!
  3. Go back to the Settings menu
  4. Tap Developer options
  5. Tap the checkbox for USB Debugging
  6. Connect your Android device to the USB port of your computer
  7. Click the play icon from the Android Studio toolbar as shown in the next image
    Running the game on a real device
  8. When prompted click OK to run the game on your chosen device.

We are now ready to learn some Java and add real code to the Sub' Hunter project.

Summary

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

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

We can then make sense of the code that Android Studio generated for us (in SubHunter.java) and start to add our own code.

Left arrow icon Right arrow icon

Key benefits

  • 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

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.

Who is this book 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.

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
Estimated delivery fee Deliver to Australia

Economy delivery 7 - 10 business days

AU$19.95

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 29, 2018
Length: 774 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788839150
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Australia

Economy delivery 7 - 10 business days

AU$19.95

Product Details

Publication date : Aug 29, 2018
Length: 774 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788839150
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
AU$249.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts
AU$349.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 203.97
Mastering Java 11
AU$67.99
Java Projects
AU$67.99
Learning Java by Building Android  Games
AU$67.99
Total AU$ 203.97 Stars icon

Table of Contents

27 Chapters
1. Java, Android and Game Development Chevron down icon Chevron up icon
2. Java: First Contact Chevron down icon Chevron up icon
3. Variables, Operators and Expressions Chevron down icon Chevron up icon
4. Structuring Code with Java Methods Chevron down icon Chevron up icon
5. The Android Canvas Class – Drawing to the Screen Chevron down icon Chevron up icon
6. Repeating Blocks of Code with Loops Chevron down icon Chevron up icon
7. Making Decisions with Java If, Else and Switch Chevron down icon Chevron up icon
8. Object-Oriented Programming Chevron down icon Chevron up icon
9. The Game Engine, Threads, and The Game Loop Chevron down icon Chevron up icon
10. Coding the Bat and Ball Chevron down icon Chevron up icon
11. Collisions, Sound Effects and Supporting Different Versions of Android Chevron down icon Chevron up icon
12. Handling Lots of Data with Arrays Chevron down icon Chevron up icon
13. Bitmap Graphics and Measuring Time Chevron down icon Chevron up icon
14. The Stack, the Heap, and the Garbage Collector Chevron down icon Chevron up icon
15. Android Localization -Hola! Chevron down icon Chevron up icon
16. Collections, Generics and Enumerations Chevron down icon Chevron up icon
17. Manipulating Bitmaps and Coding the Snake class Chevron down icon Chevron up icon
18. Introduction to Design Patterns and much more! Chevron down icon Chevron up icon
19. Listening with the Observer Pattern, Multitouch and Building a Particle System Chevron down icon Chevron up icon
20. More Patterns, a Scrolling Background and Building the Player's ship Chevron down icon Chevron up icon
21. Completing the Scrolling Shooter Game Chevron down icon Chevron up icon
22. Exploring More Patterns and Planning the Platformer Project Chevron down icon Chevron up icon
23. The Singleton Pattern, Java HashMap, Storing Bitmaps Efficiently and Designing Levels Chevron down icon Chevron up icon
24. Sprite-sheet animations, Controllable Player and Parallax Scrolling Backgrounds Chevron down icon Chevron up icon
25. Intelligent Platforms and Advanced Collision Detection Chevron down icon Chevron up icon
26. What next? Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(11 Ratings)
5 star 54.5%
4 star 9.1%
3 star 27.3%
2 star 9.1%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Sand George Ionut Sep 14, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
good bok
Amazon Verified review Amazon
Sandra Porter Jun 18, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I do know other programming languages like VB.NET but wanted to learn Java for a while and how to program Android devices. This book really is for beginners and you do not have any previous knowledge. As it says at the beginning of the book, if you do know some of the stuff, you'll just be quicker through the first few chapters. He explains everything in plain English and just brings in the technical terminology slowly so that you will be able to communicate with the the tech community. What I really like is that important subjects are explained from different angles. So even though you might not have understood something the first time round you probably will the second time around. You can download the code for every chapter which was very useful at the beginning.This edition is very much up to date.
Amazon Verified review Amazon
Amazon Customer Dec 28, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great
Amazon Verified review Amazon
Anon Oct 19, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I had no experience in Android programing and felt the Google tutorials were not really teaching anything but copy and paste, seriously. John's book on the other hand explained many things that Google doesn't and at the same time it has been fun to make the games. His approach is very straight forward and he does a great job of explaining everything along the way. I never felt lost and never had to copy and paste code to just make something work. I would recommend this book to everyone. I am not yet an accomplished Android programmer but thanks to John I am on my way now.
Amazon Verified review Amazon
janusz Jan 23, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It was not too easy and not too hard, just right for someone to learn some new concepts.I learned something so nice!Good read.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela