SlideShare a Scribd company logo
/*
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
all this classes will be in the package "highscores"/*
//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 {
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 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();
}
}
/*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 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) 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 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() + "tt" +
scores.get(i).getScore() + " ";
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. /*
Solution
/*
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
all this classes will be in the package "highscores"/*
//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 {
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 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();
}
}
/*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 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) 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 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() + "tt" +
scores.get(i).getScore() + " ";
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. /*

More Related Content

ODT
Java practical
PPTX
Computer programming 2 -lesson 4
PDF
Object Oriented Solved Practice Programs C++ Exams
PPTX
Java Programs
PDF
Change the code in Writer.java only to get it working. Must contain .pdf
PPTX
Introduction of Object Oriented Programming Language using Java. .pptx
DOCX
2. Create a Java class called EmployeeMain within the same project Pr.docx
PDF
Laporan Resmi Algoritma dan Struktur Data :
Java practical
Computer programming 2 -lesson 4
Object Oriented Solved Practice Programs C++ Exams
Java Programs
Change the code in Writer.java only to get it working. Must contain .pdf
Introduction of Object Oriented Programming Language using Java. .pptx
2. Create a Java class called EmployeeMain within the same project Pr.docx
Laporan Resmi Algoritma dan Struktur Data :

Similar to We will be making 4 classes Main - for testing the code Hi.pdf (20)

PPTX
Tutorial on developing a Solr search component plugin
PPT
Java Generics
PPTX
Inheritance
PDF
Manual tecnic sergi_subirats
DOCX
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PPTX
object oriented programming in PHP & Functions
PDF
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
PDF
Java 5 and 6 New Features
PPSX
Java session4
DOCX
----------Evaluator-java---------------- package evaluator- import j.docx
ODP
Bring the fun back to java
PDF
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
PDF
spring-tutorial
PPTX
Pragmatic unittestingwithj unit
PPT
3 j unit
PDF
Lect 1-java object-classes
PDF
Use arrays to store data for analysis. Use functions to perform the .pdf
PPTX
Object Oriented Programming Concepts
DOCX
You can look at the Java programs in the text book to see how commen
PPT
Class loader basic
Tutorial on developing a Solr search component plugin
Java Generics
Inheritance
Manual tecnic sergi_subirats
PAGE 1Input output for a file tutorialStreams and File IOI.docx
object oriented programming in PHP & Functions
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
Java 5 and 6 New Features
Java session4
----------Evaluator-java---------------- package evaluator- import j.docx
Bring the fun back to java
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
spring-tutorial
Pragmatic unittestingwithj unit
3 j unit
Lect 1-java object-classes
Use arrays to store data for analysis. Use functions to perform the .pdf
Object Oriented Programming Concepts
You can look at the Java programs in the text book to see how commen
Class loader basic
Ad

More from anithareadymade (20)

PDF
#include stdio.hint main() {     int count;     FILE myFi.pdf
PDF
MgO = 2416 = 1.5 .pdf
PDF
ITs both by the way... it depends on the situatio.pdf
PDF
I believe you are correct. The phase transfer cat.pdf
PDF
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
PDF
The correct statements are1. the oxygen atom has a greater attrac.pdf
PDF
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
PDF
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
PDF
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
PDF
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
PDF
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
PDF
import java.util.; public class DecimalToBinary { public stat.pdf
PDF
i did not get itSolutioni did not get it.pdf
PDF
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
PDF
Here is the code for youimport java.util.Scanner; import java.u.pdf
PDF
Following are the changes mentioned in bold in order to obtain the r.pdf
PDF
During meiosis, each member of a pair of genes tends to be randomly .pdf
PDF
B parents marital statusSolutionB parents marital status.pdf
PDF
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
PDF
Array- Arrays is a collection of data items with same data type and.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf
MgO = 2416 = 1.5 .pdf
ITs both by the way... it depends on the situatio.pdf
I believe you are correct. The phase transfer cat.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
import java.util.; public class DecimalToBinary { public stat.pdf
i did not get itSolutioni did not get it.pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
Following are the changes mentioned in bold in order to obtain the r.pdf
During meiosis, each member of a pair of genes tends to be randomly .pdf
B parents marital statusSolutionB parents marital status.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
Array- Arrays is a collection of data items with same data type and.pdf
Ad

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
GDM (1) (1).pptx small presentation for students
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Cell Structure & Organelles in detailed.
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Types and Its function , kingdom of life
Microbial diseases, their pathogenesis and prophylaxis
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Final Presentation General Medicine 03-08-2024.pptx
Microbial disease of the cardiovascular and lymphatic systems
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
GDM (1) (1).pptx small presentation for students
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
VCE English Exam - Section C Student Revision Booklet
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
human mycosis Human fungal infections are called human mycosis..pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Cell Structure & Organelles in detailed.
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
102 student loan defaulters named and shamed – Is someone you know on the list?
STATICS OF THE RIGID BODIES Hibbelers.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Types and Its function , kingdom of life

We will be making 4 classes Main - for testing the code Hi.pdf

  • 1. /* 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 all this classes will be in the package "highscores"/* //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 { public int compare(Score score1, Score score2) { int sc1 = score1.getScore(); int sc2 = score2.getScore(); if (sc1 > sc2){ return -1;
  • 2. }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 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(); } } /*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./*
  • 3. public ArrayList 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) 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 {
  • 4. 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./*
  • 5. public String getHighscoreString() { String highscoreString = ""; Static int max = 10; ArrayList 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() + "tt" + scores.get(i).getScore() + " "; 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());
  • 6. } } /*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. /* Solution /* 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 all this classes will be in the package "highscores"/* //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;
  • 7. } }/*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 { 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 scores; // The name of the file where the highscores will be saved private static final String HIGHSCORE_FILE = "scores.dat";
  • 8. //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(); } } /*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 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.
  • 9. 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) 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());
  • 10. } 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 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() + "tt" + scores.get(i).getScore() + " "; 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./*
  • 11. /*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. /*