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.
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.
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?
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.
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.
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.
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,
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.
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,
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.
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.
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.
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
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!
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.
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.
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.
Let's learn a little about 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.
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.
Let's set up Android Studio.
Visit developer.android.com/studio/index.html. Click the big green button to proceed.
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.
Click the Next button to proceed.
Leave the default options selected as shown next and click the Next button.
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.
When you are ready click the
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.
You will be greeted with the Welcome screen as shown next.
Choose Standard install type as shown next.
Click the Next button.
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.
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
Or if you installed Android Studio at
D:/Program Files/Android then create your new folder as
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.
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.
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:
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.
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.
After this, Android Studio will bring up the New Project window. This is where we will:
The name of our project is going to be
Sub Hunterand the location for the files will be your
AndroidProjectsfolder 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.comor something that you just make up yourself. It is only important when you come to publish.
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.
Include C++ support
Leave this option unchecked (see the next information box if you want to know more)
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.
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.
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.
This next picture shows the Target Android Devices window we have just discussed, mainly just for your reference.
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.
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
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
This is what the Customize the Activity screen should look like when you're 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 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.
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:
Let's have a look at the panel on the left
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.
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.
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.
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.
Make sure the
AndroidManifest.xml file is open in the editor window. If you followed along with the previous section it will be already.
AndroidManifest.xml file, locate the following line of code:
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.
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> …
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.
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.
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.
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.
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.
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.
You're done. Here is what the running game looks like so far:
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:
Tap the Settings menu option or the Settings app on your phone/tablet
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!
Go back to the Settings menu
Tap Developer options
Tap the checkbox for USB Debugging
Connect your Android device to the USB port of your computer
Click the play icon from the Android Studio toolbar as shown in the next image
When prompted click OK to run the game on your chosen device.
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.