Table of Contents
Introduction to Mobile Game Programming
- Objectives
- Describe and apply Android/Java game programming techniques
- Develop a simple mobile game for the Android Platform
- Know the do and don'ts of Android game development
- Be familiar with the world of mobile game development
- What you will learn
- Working with the Android SDK, Eclipse IDE, ADT Plug-in
- Game-related APIs available in Android SDK
- Tips and Tricks in Android application development
- Publishing a finished Android application to the Android market
- Other Android-specific techniques/content
- What you will not learn
- Game Design
- Collision Detection
- Physics
- Artificial Intelligence
- Path-finding
- Animation
- And everything else that you have learnt before MGPG
Introduction to Mobile Games and Android
- Mobile Games - 1997
- Nokia's popular 2D Snake game
- Comes bundled into phones; cannot install/uninstall, get new games, etc.
- Mobile Games - 2001
- Lifestylers
- Wireless Pets
- Around this period...
- Mobile game developers couldn't make any money
- Original Idea: mobile games will drive up mobile usage, developers will be paid a share of this additional revenue
- Network Operators disagreed: games should be charged on top of data tarrifs
- But they didn't have the technology to do so yet
- Mobile Games - 2002
- Mobile Games - 2003
- Then, in 2003, Nokia N-Gage and Colour Screens
- A new age! Mobile phones rivalling Nintendo's portables!
- Then, in May 2003, Sony announced PSP
- N-Gage got bashed by gaming geeks
- Mobile business model still immature
- You could still start up a company and attempt to break into the top tier of the industry (assuming you have enough money)
- Mobile phones got more and more sophiscated
- First 3D game released in Japan (Ridge Racer)
- Mobile Games - 2004
- Then, in 2004, investment in the Mobile Games Industry boomed
- EA and Ubisoft went into the mobile games industry, by licensing their brand names to developers like JAMDAT and Digital Bridges
- Explosion in Driving Games
- Mobile Games - 2005
- Then, in Mar 2005, we saw the arrival of Gizmondo
- Tiger Telematics went backrupt in Feb 2006
- EA purchased JAMDAT for $680 million
- Mobile Games - 2006
- Then, in Mar 2006, we finally had consumer handsets that could actually run 3D
- Java dreamt of its "write-once, run-anywhere" philosophy
- But in mobile games, where you have to deal with over 300 different devices, there were problems
- At this point, mobile market is largely controlled by the dominant players
- Operators have the greatest control everything, content is heavily controlled
- Handset manufacturers suck up to operators
- Publishers suck up to manufacturers
- Even though it is easy to create mobile games, it is difficult to get them published/distributed/sold
- Need something to SHAKE UP THE WORLD
- Mobile Games - 2007
- 9th Jan 2007, it happened, iPhone announced
- Mobile Games - 2007/2008
- iPhone launched 5 months later
- App Store launched in July 2008
- Platform that enabled consumers to buy games as easily as they had bought MP3s via iTunes
- Developers could sell their games DIRECTLY to consumers without having to suck up to anyone (except Apple)
- Changed the mobile industry forever
- Mobile Games - 2008
- 22th Oct 2008, first Android handset was released (HTC Dream/G1)
- iPhone and Android
- Android has its followers, but it was nothing compared to the iPhone
- iPhone exploded in popularity, overtook iPods, just behind Macs
- iPhone doubles as an iPod which can make calls, and play games
- Google and Apple are still friends, Apple - Mobile, Google - Web (Maps, YouTube, Search)
- Google Apps fill iPhone screens
- Android's Growth
- Android is completely open
- Supported by Open Handset Alliance (Motorola, Nvidia, Qualcomm, Samsung, ARM Holdings, Atheros Communications, Asustek Garmin, Sony Ericsson...)
- Microsoft (Quantity) vs Apple (Quality)
- Android (Quantity) vs iPhone (Quality)
- Android is supported by a host of inbuilt Google Applications
- Apple vs Google
- July 2009 - Announcement of Chrome OS
- Google's Apps couldn't/wouldn't operate at full capacity on iPhone
- Apple App Store rejects Google Latitude
- Apple App Store rejects Google Voice
- Apple replaces Google Search with Bing
- Nov 2009 - Google Nexus One leaked
- Mar 2010 - Apple sues HTC over patents
- iPhone vs Android
- Roughly similar users
- Neck-to-Neck in functions
- iPhone more intuitive (at the beginning)
- 170,000+ Apps vs 30,000 Apps
- 1-App-at-a-time vs Multi-Tasking
- Excellent Hardware vs Very Good Hardware
- Local vs Cloud
- Objective-C vs Java/C++
- Games: Saturated vs Bare
- iPhone Games
- Android Games
- Future of Android
- Android was at GDC giving out free phones
- Acer, Sony Ericsson, Samsung, HTC, Motorola to release more than 50 Android phones in 2010
- Growing at an exponential rate
- 60,000 shipped per day
- Let's see some Games!
Android Architecture and Application Fundamentals
- Learning Objectives
- Describe the Android Architecture
- Know the four components of Android Applications
- What is Android?
-
Linux Kernel version 2.6
- Linux Kernel
- This is the Kernel and OS of our Android Platform
- Sits at the bottom layer and communicates with all the hardware
- Based on Linux
- Android Runtime
- Your main Android "Program"
- Every Android App runs its own process, with its own Dalvik Virtual Machine
- Dalvik is written so that a device can run multiple instances efficiently
- Frequently-used Tasks
- However, every Android App will have to do their own talking to the hardware
- Imagine, PowerPoint writes DirectX equivalent, Notepad writes DirectX equivalent, Crysis also...
- Android includes a list of common libraries to help developers concentrate on their thing and their thing only
- Common Libraries
- Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications
- Media Framework - support playback and recording of many popular audio and video formats, as well as static image files
- FreeType - bitmap and vector font rendering library
- SQLite - a powerful and lightweight relational database engine available to all applications
- Android Runtime sits on top of the common libraries, which sits on top of the Linux Kernel, so developers can access them
- Actually it's more like Android Runtime is on top of the libraries and beside them at the same time, as they are at the same level
- Android Core Applications
- All versions of Android are shipped with a set of core applications
- If you write an Android game/app, it's the same as one of these
- Android Application Framework
- Now, to support all these applications, Android provides a set of services and systems
- This application framework supports any Android game/application that you write, you can use them as you like/require
- Of course, the Application Framework makes use of the Core Libraries
- The Big Picture
- Application Fundamentals
- For now, all Android Applications are written in Java
- Format is .apx
- Each App runs in its own Dalvik VM, isolated from others
- Four types of Android Application Components:
- Activities
- Services
- Broadcast Receivers
- Content Providers
- Activities
- Any application that has a visible User Interface should be an Activity
- When a user selects an application from the home screen, an Activity is launched
- User engages himself in this Activity until he is done
- A Game should be an Activity
- Services
- A Service is used for programs that need to persist for a long time
- Can start Activities to handle user interactions
- Examples:
- A network monitor
- Update-checker
- Live wallpapers
- Media player
- Possible for a game: Tamagochi game as a live wallpaper
- Broadcast/Intent Receivers
- An Android component that is used specifically to handle certain events and process data
- Example of event: Text message received
- Example of application: Text message program
- Broadcast Receivers
- Can start an Activity to perform further processing and/or let user handle it
- Can use the NotificationManager to play a sound, blink a light
- An Android Application can have multiple Broadcast Receivers to handle different situations
- Content Providers
- Used to manage access to persistent data, such as an SQLite database
- Normally used when the data needs to be accessible to multiple Activities/Services/Applications
- Means of accessing the data
- Communication between Components
- In Android, components can call other components to do things for each other
- Planner Activity can start Calculator Activity to do calculations
- Music Service can start Equalizer Activity to adjust the playback
- Facebook Activity can access Contacts Content Provider
- Gmail Service's "New Email" Broadcast Receiver can start "Read Email" Activity
- How does Android handle these communications?
- Communication Classes
- Content Providers are activated by requests from ContentResolvers
- Activities, Services, Broadcast Receivers are activated by messages called Intents
- Intent objects store such information such as the action being requested, and the data to act on
- In WinMo, "I want to send Email with Outlook"
- In Android, "I want to send Email with whatever client you have" (Intent)
- Android searches for an App that can handle this Intent
- Same for MP3, SMS, Browsers, etc.
- Android Games
- Usually just ONE single Activity
- User will start the game, play it, and shut it down
- Obviously a game will have an User Interface in order to let the player control it
- Most likely will not touch on other components (but not impossible)
From C++ back to Java
- Objectives
- Distinguish the differences and similarities between Java and C++ syntax
- Write classes in Java
- Write subclasses in Java
- Override parent class methods in the subclass in Java
- Write and use interface in Java
- Java Platform
- Java compiler and tools
- Java Virtual Machine (JVM)
- Java APIs (Application Programming Interface)
- Most programming languages process code by either compiling or interpreting; Java does both
- Abstracts away underlying hardware intricacies
- Provide consistent layer between bytecode and actual machine instructions
- Bytecode is the power behind Java's "Write Once, Run Anywhere" flexibility - high portability
- And it actually runs! On all of them!
- Java in Android
- Primitive Data Types
- Primitive data types in Java are similar to C++ except for Boolean data type
- Data Types C++ Java 32-bit signed integer int int 64-bit IEEE floating-point number double double 16-bit Unicode character char char Boolean (true/false) bool boolean
- Examples
- int a = 3;
- boolean state = true;
- float myFloat = 1.5f;
- double myDouble = 1.5;
- char myInitial = 'J';
- String Data Type
- String is a reference data type and is used to represent a series of characters
- To use string in C++, need to use the directive #include
- No need to do any import that in Java
- Data Types C++ Java Series of Characters string String
- String output = "I love Java over C++ for now!";
- Programming Structure
- Any program is controlled by the combinations of the following structures:
- Sequence (line by line)
- Decision (if ... else if ... else)
- Repetition (while loop, do-while loop, for loop)
- Programming structures and syntax are the same in Java and C++
- Importing Java Packages
- Same concepts as the #include directive in C++ but import statements make reference to where the java package is located rather than include the package
- To use a particular package or class, we use:
- Example:
- import java.util.Scanner;
- import java.util.*;
- Memory Management
- In C++, the programmer is able to decide whether to use the stack memory or heap memory for primitive data as well as reference data
- int num = 6;
- Variable num on stack where 6 is stored
- int* ptrNum = new int(6);
- Pointer ptrNum on the stack pointing to the memory in the heap where 6 is stored
- Memory Management in Java
- The programmer can choose to store the integer value on the stack or on the heap
- In Java primitive data are stored on the stack and reference (object) data are stored on the heap. Loosely speaking, the programmer need not worry about what memory to use
- In C++, the programmer needs to memory manage. Otherwise memory leak will occur as the dereference heap memories not cleared will remain in memory. In Java, the programmer needs not do that. Any dereference heap memory will be cleared automatically by the GarbageCollector
- No -> operator used in Java
- Classes and Objects
- Basic structure of a class
- Class Writing in Java
- No need of any header (.h) files
- Does all implementation in one Java file
- public class GameCharacter
{
private String name;
private int hitPoint;
public GameCharacter(String name, int hitPoint)
{
this.name = name;
this.hitPoint = hitPoint;
}
public String getName() { return name; }
public int getHitPoint() { return hitPoint; }
public void setName(String name) { this.name = name; }
public void setHitPoint(int hitPoint) { this.hitPoint = hitPoint; }
public String toString() { return name + " / " + hitPoint; }
} - public class GameCharacterApp
{
public static void main(String[] args)
{
GameCharacter gc = new GameCharacter("Zelda", 200);
System.out.println(gc.toString());
}
}
- Inheritance
- "is-a" relationship between two classes
- Example: CyberMonster is-a GameCharacter
- Parent class - GameCharacter
- Subclass - CyberMonster
- Subclass has extra attributes than the Parent class
- Subclass may have extra methods
- Implementing the Subclass
- Constructor in the Subclass
- super must be the first statement in the constructor to initialise the instance variables in the super class
- super calls the parent class constructor
- Constructors in the parent class are not inherited
- Method Overriding
- toString() method is said to override the Parent Class toString() method
- Method overriding happens when the Subclass and Parent Class have the same method name, parameters and return type (same method signatures)
- With the super.toString() in the method, this is known as method overriding by refinement
- Abstract Class
- As we move up the inheritance hierarchy classes get more and more general
- At one point we have classes that become more as a framework for other classes
- Such classes become abstract classes
- It may contain method headers with no implementation
- No objects can be instantiated from these classes
- Interfaces
- Not found in C++ but in Java
- No Multiple Inheritance in Java!
- Problem with method resolution:
- Duck myDuck = new Duck();
myDuck.eat(); - Which method eat() from which class to invoke??
- Interface
- Interface describes a specialised set of behiavour
- It contains only method headers with no implementation
- No abstract keyword, only the method header
- No instance variables, but can contain only static final variables with initialised values
- Any class that "implements" the interface must provide implementation for the methods in the interface
- Re-design to avoid Multiple Inheritance
- Writing and Using Interfaces
- public interface Swimmer
{
public static final speed = 10;
public void swim();
public void otherMethod();
}
public class Duck extends Animal implements Flier, Swimmer
{
public void swim() { ... }
public void fly() { ... }
public void sound() { ... }
public void eat() { ... }
}
- A Final Example
- A duck is an animal but can fly and swim. A whale is an animal but can swim. A Navy Diver is a person working for the Navy, so he must be able to swim.
- A parent class can be seen to represent "true" parent-child relationship
- Interface can be seen to represent an "uncle-child" relationship
Multithreading in Java
- Objectives
- Explain what is multithreading
- Describe the life cycle of a thread
- Create user threads using thread job objects
- Use synchronization to prevent different threads from accessing the same object at the same time
- Multithreading
- Threads are separate parts of execution which function independently of each other
- Multithreading refers to a single process having parts of execution
- A scheduler in the operating system will give each thread a small time slice using an algorithm based on differing priorities
- Life Cycle of a Thread
- The entire functionality of the thread is defined in the run() method.
- The Thread Class
- A thread is an object represented by the Thread class
- Create an instance of a Thread object each time to start a new thread of execution
- The Thread class is found in the java.util.lang package
- The Main Thread
- Every Java application starts up a main thread - the thread that puts the main() method at the bottom of the stack
- The JVM is responsible for starting the main thread (and other threads as it chooses)
- We write codes to start other threads of our own
- The Runnable Interface
- The Runnable Interface contains only one method, public void run()
- We can create a runnable object by implementing the run() method and passing this runnable object to a thread object
- The Thread class contains the method start() which will invoke the run() method
- Illustration of Multithreading
- Creating User Thread
- Two choices when creating a user thread
- Extending from the Thread Class
- Implementing Runnable Interface
- Extending from the Thread Class
- Extend your own thread class from the Thread Class
- Override the run() method of the Thread Class
- Create an instance of the above class which is a Thread object in main()
- Call start() on the thread which will then invoke run()
- Implementing from Runnable Interface
- Implement Runnable to create a thread job for your thread
- Overrides the run() method of the Runnable interface
- Create an instance of this class which is a Runnable thread job object in main()
- Create a Thread object by passing the Runnable thread job object created above as parameter
- Call start() on the thread which will then invoke run()
- Points to Note on the Thread Class
- The Thread class from java.lang actually implements Runnable and provide an empty implementation for the run() method
- So the run() method we override in our user Thread class is actually the same run() method from the Runnable interface
- The Thread Scheduler
- The thread scheduler makes all the decisions about who runs and who doesn't
- He usually makes the threads take turns, nicely, but there is no guarantee about that
- He might let one thread run to its heart's content while the other threads 'starve'
- The Dark Side of Thread
- Threads can lead to concurrency issues
- Concurrency issues lead to race condition
Race condition leads to data corruption - Data corruption leads to fear
- Fear leads to...
- Trouble with Multithreaded Program
- Example
- A bank account has $100
- Two threads share the same BankAccount object
- Thread 1 decides to make a withdraw of $50 and obtain the balance from the bank account
- Thread 1 goes to sleep before affecting the balance
- Thread 2 decides also make a withdraw of $80 and obtain the balance from the bank account
- Thread 2 deduct the obtained balance and set the balance back to the bank account
- The bank account now has a balance of $20
- Thread 1 wakes up and deduct $50 the obtained balance before he sleeps and set the balance back to the bank account
- How much does the bank accounts has now?
- Problem: both threads are accessing the common information (bank balance) at the same time
- We have to make sure that common information accessed by multiple threads are accessed one at a time
- This is ensured through Synchronization
- Synchronization
- Synchronization places a look on an object so that the thread that places the lock can only access the information from the object
- Once done, the thread will release the lock on the object for other threads to use
- Example
- The bank account object is unlocked when nobody is using it
- Thread 1 accesses bank account object and locks it
- Thread 1 releases the lock on bank account object
- Bank account object is unlocked and other threads can access it
- Synchronized a Method on a Thread
- Use the synchronized modifier
- Can be used against a method
- public synchronized voice method (...) { ... }
- As a block
- public void method (...)
{
...
...
synchronized(