Book Image

Android Game Programming by Example

By : John Horton
Book Image

Android Game Programming by Example

By: John Horton

Overview of this book

Table of Contents (18 chapters)
Android Game Programming by Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
7
Platformer – Guns, Life, Money, and the Enemy
Index

Adding persistence


You may have noticed that the current fastest time is zero and can therefore never be beaten. The other problem is that every time the player quits the game the high score is lost. Now, we will load a default high score from a file. When a new high score is achieved, save it to the file. It doesn't matter if the player quits the game or even switches off their phone; their high score will remain.

First we need two new objects. Declare them as members of the TDView class after the TDView class declaration. The first is a SharedPreferences object and the second is an Editor object, which actually writes to the file for us:

private SharedPreferences prefs;
private SharedPreferences.Editor editor;

We use prefs first as we just want to attempt to load a high score if one exists. We will also initialize editor ready for when we save our high score. We do this in the TDView constructor:

// Get a reference to a file called HiScores. 
// If id doesn't exist one is created
prefs = context...