34,79 €
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.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 885
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Amarabha Banerjee
Acquisition Editor: Reshma Raman
Content Development Editors: Onkar Wani
Technical Editor: Ralph Rosario
Copy Editor: SAFIS
Project Coordinator: Devanshi Doshi
Proofreader: Safis Editing
Indexers: Pratik Shirodkar
Graphics: Jason Monterio
Production Coordinator: Aparna Bhagat
First published: January 2015
Second edition: August 2018
Production reference: 1270818
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78883-915-0
www.packtpub.com
mapt.io
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Boon Hian Tek is a 18 years Java veteran. He has honed his software development skills in a varying industries. He helped bringing medical records online, aided the advertising industry target ads, assisted in getting disposing of chemical weapons, and more recently part of making fin tech work some wonders.
He is always passionate with automation. Boon spends his days automating so that he can spend more time with his family. No one should spend be forced to spend time doing mundane stuff. Except for wax on, wax off!
He works for one of the largest fin tech in Singapore also reviewed First Edition of this book.
My wife and daughter putting up with the time I spent away from them to help with the book.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
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.
Learning Java by Building Android Games is for you if you are completely new to Java, Android, or game programming, and you want to make Android games. This book also acts as a refresher for those who already have experience of using Java on Android or any other platform without game development experience.
Chapter 1, Java, Android, and Game Development, In this first chapter we will get straight into Java, Android and game development. Also, we will look at some images and an outline of each of the six games we will develop throughout the book. Further, we will explore and discover what is so great about Android, what exactly Android and Java are, how they work and complement each other. Moving quickly on we will set up the required software and then build and deploy the outline for the first game.
Chapter 2, Java: First Contact, In this chapter, we will make significant progress with the Sub' Hunter game even though this is the first lesson on Java. We will look in detail at exactly how Sub' Hunter will be played and the steps/flow that our completed code will need to take to implement it. We will also learn about Java code comments for documenting the code, take a brief initial glimpse at methods to structure our code and an even briefer first glimpse at object-oriented programming that will begin to reveal the power of Java and the Android API.
Chapter 3, Variables, Operators, and Expressions, We are going to make good progress in this chapter. We will learn about Java variables that allows us to give our game the data it needs. Things like the sub's location and whether it has been hit, will soon be possible to code. Furthermore, the use of operators and expressions will enable us to change and mathematically manipulate this data as the game is executing.
Chapter 4, Structuring Code with Java Methods, As we are starting to get comfortable with Java programming, in this chapter, we will take a closer look at methods because although we know that you can call them to make them execute their code, there is more to them that haven't been discussed so far.
Chapter 5, The Android Canvas Class - Drawing to the Screen, While we will leave creating our own classes for a few more chapters our new-found knowledge about methods enables us to start taking greater advantage of the classes that Android provides. This entire chapter will be about the Android Canvas class and some related classes like Paint and Color. These classes combined bring great power when it comes to drawing to the screen. Learning about Canvas will also teach us the basics of using any class.
Chapter 6, Repeating Blocks of Code with Loops, In this brief chapter, we will learn about Java loops that enable us to repeat sections of our code in a controlled manner. Loops in Java take a few different forms and we will learn how to use them all and throughout the rest of the book we will put each of them to good use.
Chapter 7, Making Decisions with Java if, else, and switch, Welcome to the final part of the first game. By the end of this chapter, you can say you have learned most of the Java basics. In this chapter, we will learn more about controlling the flow of the game's execution and we will also put the finishing touches to the Sub' Hunter game to make it playable.
Chapter 8, Object-Oriented Programming, In this chapter, we will discover that in Java, classes are fundamental to everything. We have already talked about reusing other people's code, specifically the Android code, but in this chapter, we will really get to grips with how this works and learn about Object Oriented Programming as well as how to use it. Topics including encapsulation, inheritance, and polymorphism. We will start to write our own reusable classes and look at some more advanced OOP like abstract classes and interfaces. At the end of the chapter we will know enough about OOP to get started on the Pong game.
Chapter 9, The Game Engine, Threads, and the Game Loop, During this chapter we will see the game engine come together. By the end of the chapter, we will have an exciting blank screen that draws debugging text at 60 frames per second on a real device, although, probably less on an emulator. While doing so we will learn about programming threads, try-catch blocks, the Runnableinterface, Android Activity lifecycle and the concept of a game loop. My expression of excitement for a blank screen might seem sarcastic but, once this chapter is done we will be able to code and add game objects, almost at will. Furthermore, this game engine code will be used as an approximate template (we will improve it each project) for future projects making the realization of future games faster and easier.
Chapter 10, Coding the Bat and Ball, As we have done so much theory and preparation work in the previous two chapters we can quickly make some progress in this one. We already have our bare-bones game engine coded and ready to update, draw and track time down to the nearest millisecond. Now we can add code to the Bat and the Ball classes. By the end of the chapter, we will have a moving ball and a player-moveable bat.
Chapter 11, Collisions, Sound Effects, and Supporting Different Versions of Android, By the end of this chapter, we will have a fully working and beeping implementation of the Pong game. We will start the chapter off by looking at some collision detection theory which will be put in to practice near the end of the chapter. We will also learn about how we can detect and handle different versions of Android. We will then be able to study the SoundPool class and the different ways we use it depending on the Android version the game is running on. At this point, we can then put everything we have learned into producing some more code to get the Pong ball bouncing and beeping as well as put the finishing touches on the game.
Chapter 12, Handling Lots of Data with Arrays, In this chapter, we will first get the Bullet Hell project setup and ready to roll with a single bullet whizzing across the screen. Then we will learn about Java arrays which allow us to manipulate a potentially huge amount of data in an organized and efficient manner. Once we are comfortable handling arrays of data we will see how we can spawn hundreds or thousands of our new Bullet class instances, without breaking a sweat.
Chapter 13, Bitmap Graphics and Measuring Time, So far in this book, we have drawn exclusively with primitive shapes and text. In this section, we will see how we can use the Canvas class to draw Bitmap graphics- after all Bob is so much more than just a block or a line. We will also code Bob and implement his teleportation feature, shield and collision detection. To finish the game off, we will add a HUD, measure the time, and code a solution to remember the longest (best) time.
Chapter 14, The Stack, the Heap, and the Garbage Collector In this chapter, we will make a good start with the next project, an authentic looking, clone of the classic Snake game. It is also the time that we understood a little better what is going on underneath the Android hood. We constantly refer to 'references' but what exactly is a reference and how does it affect how we build games?
Chapter 15, Android Localization- Hola!, This chapter is quick and simple but what we will learn to do can make your game accessible to millions more potential gamers. We will see how to add additional languages. We will see the "correct" way to add text to our games and use this feature to make the Snake game multilingual. This includes using String resources instead of hard-coding Strings in our code directly as we have done so far throughout the book.
Chapter 16, Collections, Generics, and Enumerations, This chapter will be part practical and part theory. First, we will code and use the Apple class and get our apple spawning ready for dinner. Afterward, we will spend a little time getting to know to new Java concepts ArrayList and enumerations (enum for short). These two new topics will give us the extra knowledge we will need to finish the game (mainly the Snake class) in the next chapter.
Chapter 17, Manipulating Bitmaps and Coding the Snake Class, In this chapter, we will finish the Snake game and make it fully playable. We will put what we learned about ArrayList and enum to good use and we will properly see the benefit of encapsulating all the object-specific drawing code into the object itself. Furthermore, we will learn how to manipulate Bitmaps so that we can rotate and invert them to face any way that we need them to.
Chapter 18, Introduction to Design Patterns and Much More!, Since the second project, we have been using objects. You might have noticed that many of the objects have things in common. Things like variables for speed and direction, a RectF for handling collisions and more besides.
As our objects have more in common we should start taking advantage of OOP, inheritance, polymorphism and a concept we will now introduce design patterns.
Inheritance, polymorphism and design patterns will enable us to fashion a suitable hierarchy to try and avoid writing duplicate code and avoid sprawling classes with hundreds of lines. This type of dissorganised code is hard to read, debug or extend. The bigger the game project and the more object types, the more of a problem this would become.
This project and the next will explore many ways that we can structure our Java code to make our code efficient, reusable and less buggy. When we write code to a specific, previously devised solution/structure we are using a design pattern.
Don't worry, in the remaining chapters we will also be finding out about more game development techniques to write better, more advanced games. In this chapter, we will start the Scrolling Shooter project.
Chapter 19, Listening with the Observer Pattern, Multitouch, and Building a Particle System, In this chapter we will get to code and use our first design pattern. The Observer pattern is exactly what it sounds like. We will code some classes that will indeed observe another class. We will use this pattern to allow the GameEngine class to inform other classes when they need to handle user input. This way individual classes can handle different aspects of user input.
In addition, we will code a particle system. A particle system comprises of hundreds or even thousands of graphical objects that are used to create an effect. Our particle system will look like an explosion.
Chapter 20, More Patterns, a Scrolling Background, and Building the Player- Ship, This is one of the longest chapters and we have quite a bit of work as well as theory to get through before we can see the results of it on our device/emulator. However, what you will learn about and then implement will give you the techniques to dramatically increase the complexity of the games you are able to build. Once you understand what an entity-component system is and how to construct game objects using the Factory pattern you will be able to add almost any game object you can imagine to your games. If you bought this book not just to learn Java but because you want to design and develop your own video games, then this part of the book is for you.
Chapter 21, Completing the Scrolling Shooter Game, In this chapter we will complete the Scrolling Shooter game. We will achieve this by coding the remaining component classes which represent the three different types of alien and their lasers that they can shoot at the player. Once we have completed the component classes we will make minor modifications to the GameEngine, Level and GameObjectFactory classes to accommodate these newly completed entities.The final step to complete the game is the collision detection that we will add to the PhysicsEngine class.
Chapter 22, Exploring More Patterns and Planning the Platformer Project, Welcome to the start of the final project. Over the next four chapters we will build a platform game packed full of features like parallax effect scrolling, animated controllable character, multiple different and challenging levels and much more (keep reading for more details.) During this project we will discover more Java patterns like the Singleton, another Java data class, the HashMap and explore the gaming concepts of a controllable camera and an animator. At the same time, we will reinforce all the Java concepts we have already learned including aiding our understanding of and improving upon the entity-component/factory patterns we used in the previous project.
Chapter 23, The Singleton Pattern, Java HashMap, Storing Bitmaps Efficiently, and Designing Levels, This is going to be a very busy and varied chapter. We will learn the theory of the Singleton design pattern. We will be introduced to another of the classes of the Java Collections, HashMap in which we will see how we can more efficiently store and make available the wide variety of bitmaps that are required for this project. We will also get started on our new and improved Transform class, code the first of the component-based classes, code the all-new Camera class and make a significant start on some of the more familiar classes, GameState, PhysicsEngine, Renderer, GameEngine and more besides.
Chapter 24, Sprite Sheet Animations, the Controllable Player, and Parallax Scrolling Backgrounds, In this chapter we will look at how basic animation occurs by "flipping" through different images to create a moving effect. This is the same technique used to make a simple cartoon. Of course, we will then need to code a solution to achieve this simple animation in our game objects and will do so by coding an Animator class and adding one to any graphics-related component class that needs it. We will also implement another scrolling background but slightly differently to the scrolling background in the previous project because this time it will need to be positioned both horizontally and vertically, each frame, relative to the position of the camera.
Chapter 25, Intelligent Platforms and Advanced Collision Detection, This chapter is the final chapter of the final project and shorter than most. We will however, add quite a bit to the game. First, we will code an intelligent platform- one that moves up and down of its own accord. This greatly increases the potential for interesting level designs and looks good too. The final thing we will add is the collision detection. This will be more advanced than in any of the other projects as we will need to respond differently depending on which collider of the player collide with various different game objects. In addition, the collision code will need to communicate with the movement code to make the whole system behave as needed.
Chapter 26, What next?, We are just about done with our journey. This chapter is just a few ideas and pointers that you might like to look at before rushing off and making your own games.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Java-by-Building-Android-Games-Second-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/LearningJavabyBuildingAndroidGamesSecondEdition_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example; "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
Bold: Indicates a new term, an important word, or words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this. For example: "Select System info from the Administration panel."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome.
General feedback: Email [email protected], and mention the book's title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book we would be grateful if you would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
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:
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.
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.
Plus, you get to blow stuff up!
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, 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.
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.
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 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.
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.
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.
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.
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 is quite straightforward if a little lengthy. Grab some refreshment and get started with the following steps.
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.
Write down a note of where you choose
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 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.
Notice that there is no space between the words Android and Projects and that the first letter of both words is capitalized.
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:
If you are prompted to Import Studio settings from:, choose Do not import settings.
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.
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
