You can use my code as much as you want, notifying me in this topic if you used it will be appreciated.
We will be making 4 classes:
- Main - for testing the code
- HighscoreManager - to manage the high-scores
- HighscoreComparator - I will explain this when we get there
- Score - also this I will explain later
The Score Class
package highscores;
import java.io.Serializable;
public class Score implements Serializable {
private int score;
private String naam;
public int getScore() {
return score;
}
public String getNaam() {
return naam;
}
public Score(String naam, int score) {
this.score = score;
this.naam = naam;
}
}
This class makes us able to make an object (an arraylist in our case) of the type Score that contains the name and score of a player.We implement serializable to be able to sort this type.
The ScoreComparator Class
package highscores;
import java.util.Comparator;
public class ScoreComparator implements Comparator<Score> {
public int compare(Score score1, Score score2) {
int sc1 = score1.getScore();
int sc2 = score2.getScore();
if (sc1 > sc2){
return -1;
}else if (sc1 < sc2){
return +1;
}else{
return 0;
}
}
} This class is used to tell Java how it needs to compare 2 objects of the type score.
-1 means the first score is greater than the 2nd one, +1 (or you can just put 1) means it's smaller and 0 means it's equal.
The HighscoreManager Class
First we will be making the HighscoreManager Class, this class will do the most important part of the high-score system.
We will be using this as our base for the class:
package highscores;
import java.util.*;
import java.io.*;
public class HighscoreManager {
// An arraylist of the type "score" we will use to work with the scores inside the class
private ArrayList<Score> scores;
// The name of the file where the highscores will be saved
private static final String HIGHSCORE_FILE = "scores.dat";
//Initialising an in and outputStream for working with the file
ObjectOutputStream outputStream = null;
ObjectInputStream inputStream = null;
public HighscoreManager() {
//initialising the scores-arraylist
scores = new ArrayList<Score>();
}
}
I have added comments to explain what's already in the class.We will be using a binary file to keep the high-scores in, this will avoid cheating.
To work with the scores we will use an arraylist. An arraylist is one of the great things that java has and it's much better to use in this case than a regular array.
Now we will add some methods and functions.
public ArrayList<Score> getScores() {
loadScoreFile();
sort();
return scores;
}
This is a function that will return an arraylist with the scores in it. It contains calls to the function loadScoreFile() and sort(), these functions will make sure you have the scores from your high-score file in a sorted order. We will be writing these functions later on.
private void sort() {
ScoreComparator comparator = new ScoreComparator();
Collections.sort(scores, comparator);
}
This function will create a new object "comparator" from the class ScoreComparator.the Collections.sort() function is in the Java Collections Class (a part of java.util). It allows you to sort the arraylist "scores" with help of "comparator".
public void addScore(String name, int score) {
loadScoreFile();
scores.add(new Score(name, score));
updateScoreFile();
}
This method is to add scores to the scorefile.Parameters "name" and "score" are given, these are the name of the player and the score he had.
First the scores that are allready in the high-score file are loaded into the "scores"-arraylist.
Afther that the new scores are added to the arraylist and the high-score file is updated with it.
public void loadScoreFile() {
try {
inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE));
scores = (ArrayList<Score>) inputStream.readObject();
} catch (FileNotFoundException e) {
System.out.println("[Laad] FNF Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("[Laad] CNF Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
}
}
}
This function will load the arraylist that is in the high-score file and will put it in the "scores"-arraylist.The try-catch structure will avoid that your program crashes when there is something wrong while loading the file (like when the file is corrupted or doesn't exist).
public void updateScoreFile() {
try {
outputStream = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE));
outputStream.writeObject(scores);
} catch (FileNotFoundException e) {
System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and make a new file");
} catch (IOException e) {
System.out.println("[Update] IO Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("[Update] Error: " + e.getMessage());
}
}
}
This is about the same as loadScoreFile(), but instead of reading the file it will be writing the "score"-arraylist to the file.
public String getHighscoreString() {
String highscoreString = "";
Static int max = 10;
ArrayList<Score> scores;
scores = getScores();
int i = 0;
int x = scores.size();
if (x > max) {
x = max;
}
while (i < x) {
highscoreString += (i + 1) + ".\t" + scores.get(i).getNaam() + "\t\t" + scores.get(i).getScore() + "\n";
i++;
}
return highscoreString;
}
Depending on how you want to display your highscores this function can be either usefull or not usefull. But I have put it in here anyway.It can be used for both console and GUI (in GUI you can put the high-score string into a label).
The function will only have the top 10 players but you can adjust the variable "max" to change that.
The Main Class
This class is just to test out the code and it shows you how you can implement it into your own game.
package highscores;
public class Main {
public static void main(String[] args) {
HighscoreManager hm = new HighscoreManager();
hm.addScore("Bart",240);
hm.addScore("Marge",300);
hm.addScore("Maggie",220);
hm.addScore("Homer",100);
hm.addScore("Lisa",270);
System.out.print(hm.getHighscoreString());
}
}
First you have to create an object from the HighscoreManager class, we will call it "hm" in here.Afther that you can add scores by using the .addScore() method. The first parameter has to be the name of your player and the 2nd one is the highscore (as an int).
You can print the getHighscoreString function to get the highscore in String-format and display them on the console with System.out.print()
Note: the first time you run you will get a "FNF Error", this means that the program hasn't found the highscore-file, this is logical because we haven't created that, but you don't have to worry, Java will create one itself, so afther the first time you won't have the error anymore.
Edited by Shaddix, 02 October 2009 - 09:56 AM.


Sign In
Create Account


Back to top









