Home Game Development Learning Java by Building Android Games - Second Edition

Learning Java by Building Android Games - Second Edition

By John Horton
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Java, Android and Game Development
About this book
Android is one of the most popular mobile operating systems presently. It uses the most popular programming language, Java, as the primary language for building apps of all types. However, this book is unlike other Android books in that it doesn’t assume that you already have Java proficiency. This new and expanded second edition of Learning Java by Building Android Games shows you how to start building Android games from scratch. The difficulty level will grow steadily as you explore key Java topics, such as variables, loops, methods, object oriented programming, and design patterns, including code and examples that are written for Java 9 and Android P. At each stage, you will put what you’ve learned into practice by developing a game. You will build games such as Minesweeper, Retro Pong, Bullet Hell, and Classic Snake and Scrolling Shooter games. In the later chapters, you will create a time-trial, open-world platform game. By the end of the book, you will not only have grasped Java and Android but will also have developed six cool games for the Android platform.
Publication date:
August 2018
Publisher
Packt
Pages
774
ISBN
9781788839150

 

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.

Note

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.

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.

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.

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!

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.

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.

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.

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.

Note

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.

  2. Accept the terms and conditions by checking the box and then click the big blue button DOWNLOAD ANDROID STUDIO FOR WINDOWS.

  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.

  5. Leave the default options selected as shown next and click the Next button.

  6. Next, we need to choose where to install Android Studio as shown in the next image.

    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.

    Note

    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.

  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.

  11. Click Next.

  12. Android Studio is now installed, check the Start Android Studio check-box and click the Finish button.

  13. You will be greeted with the Welcome screen as shown next.

  14. Click the Next button.

  15. Choose Standard install type as shown next.

  16. Click the Next button.

  17. Choose whichever color scheme looks nice to you, I chose InteliJ as shown next.

  18. Click Next.

  19. Now you will see the Verify Settings screen.

  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.

Note

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.

    Note

    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.

  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.

  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.

  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.

  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:

  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

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:

Click Install Build tools…. Then click Finish.

Note

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:

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.

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.

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.

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

Note

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.

Note

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.

  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.

  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.

  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.

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

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.

Note

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

  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.

About the Author
Latest Reviews (5 reviews total)
Muy buen libro hasta lo que llevo leído que es mas de 1/3, explicación clara y directa hasta para los que solo saben ingles técnico, es perfectamente claro.
I have the first version and was getting increasingly frustrated with it because most of the information was obsolete. When I saw this addition I decided to give it another chance. no regrets so far! Not only is the code updated, but there are entirely new games to practice on! Several week later it’s still my favorite way to spend days off.
Learning Java by Building Android  Games - Second Edition
Unlock this book and the full library FREE for 7 days
Start now