Highscore-List for Games

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Did this highscore-list help you?

Poll ended at Fri Jan 08, 2010 12:47 am

yes
1
50%
no
1
50%
 
Total votes : 2

Highscore-List for Games

Postby masrlinu » Fri Jan 08, 2010 12:47 am

Hi!

If you want to have a Highscore-List in your games, I have a class for you, which saves names and score in the right position in the highscore-list.

You create a new instance of it like this:

Highscore highscore = new Highscore(this); //"this" is the Context

You can add a Score to the Highscore-List with this command:
highscore.addScore("Martin", Global.score);
You do not need to test, if the score is in the Highscore-List. This command automatically puts it in the right position, if the score is in the Highscore-List.

If you want to test, if the score is in the Highscore-List, you can do it like this:
highscore.inHighscore(score);
It is helpful, to see, if the player is in the highscore-list. Because if he is not, you do not need to ask for his name.

You get the name of the x-th position in the Highscore like this:
highscore.getName(x);

The same for the score:
getScore(x);



Here is the Highscore-Class:


public class Highscore {
private SharedPreferences preferences;
private String names[];
private long score[];

public Highscore(Context context)
{
preferences = context.getSharedPreferences("Highscore", 0);
names = new String[10];
score = new long[10];

for (int x=0; x<10; x++)
{
names[x] = preferences.getString("name"+x, "-");
score[x] = preferences.getLong("score"+x, 0);
}

}

public String getName(int x)
{
//get the name of the x-th position in the Highscore-List
return names[x];
}

public long getScore(int x)
{
//get the score of the x-th position in the Highscore-List
return score[x];
}

public boolean inHighscore(long score)
{
//test, if the score is in the Highscore-List
int position;
for (position=0; position<10&&this.score[position]>score; position++);

if (position==10) return false;
return true;
}

public boolean addScore(String name, long score)
{
//add the score with the name to the Highscore-List
int position;
for (position=0; position<10&&this.score[position]>score; position++);

if (position==10) return false;

for (int x=9; x>position; x--)
{
names[x]=names[x-1];
this.score[x]=this.score[x-1];
}

this.names[position] = new String(name);
this.score[position] = score;

SharedPreferences.Editor editor = preferences.edit();
for (int x=0; x<10; x++)
{
editor.putString("name"+x, this.names[x]);
editor.putLong("score"+x, this.score[x]);
}
editor.commit();
return true;

}

}
masrlinu
Freshman
Freshman
 
Posts: 2
Joined: Thu Jan 07, 2010 10:44 pm

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests