Previous: Scenes
HighScores
//
// HighScoreDemo.java
//
//
// This program demonstrates the use of the Processing functions
// loadStrings() and saveStrings() to implement a high score list.
//
// High scores are stored in a file "high_scores.txt" as strings:
//
// DrKessner 1234
// Gadget 2345
//
// Called in setup(), the readHighScores() function reads the
// contents of "high_scores.txt" as a list of strings, one string
// per line, and then transforms this list to a list of high score
// records.
//
// The keyPressed() function demonstrates how to add a new high
// score and save the scores to the "high_scores.txt".
//
import processing.core.*;
import java.util.*;
public class HighScoreDemo extends PApplet
{
public void settings()
{
size(400, 400);
}
public void setup()
{
// read the high scores from file
readHighScores();
// print the high score records
for (HighScoreRecord r : highScoreRecords)
System.out.println(r.getName() + " " + r.getScore());
}
public void draw()
{
background(0);
}
public void keyPressed()
{
// add a new high score
highScoreRecords.add(new HighScoreRecord("Tux", 3456));
// write the high scores to file
writeHighScores();
}
private void readHighScores()
{
// call the PApplet loadStrings() function
String[] highScoreStrings = loadStrings("high_scores.txt");
// transform the list of strings into a list of high score
// records
highScoreRecords = new ArrayList<HighScoreRecord>();
for (String s : highScoreStrings)
{
// parse the line and add a new record to the list
String[] tokens = s.split(" ");
String name = tokens[0];
int score = Integer.parseInt(tokens[1]);
highScoreRecords.add(new HighScoreRecord(name, score));
}
}
private void writeHighScores()
{
String[] highScoreStrings = new String[highScoreRecords.size()];
// transform the list of high score records to a list of
// strings
for (int i=0; i<highScoreStrings.length; i++)
{
HighScoreRecord currentRecord = highScoreRecords.get(i);
highScoreStrings[i] = currentRecord.getName() + " "
+ currentRecord.getScore();
}
// call the PApplet saveStrings() function
saveStrings("high_scores.txt", highScoreStrings);
}
private ArrayList<HighScoreRecord> highScoreRecords;
public static void main(String[] args)
{
PApplet.main("HighScoreDemo");
}
}
//
// HighScoreRecord.java
//
public class HighScoreRecord
{
public HighScoreRecord(String name, int score)
{
this.name = name;
this.score = score;
}
public String getName() {return name;}
public int getScore() {return score;}
private String name;
private int score;
}
Next: Obstacles