I am creating the game Snake and I would like it so that when I click on the high scores button you are able to see the top five scores. In order for this to happen I need the game to be able to save every score permanently and then display the top 5. I am told I have to use File i/o to create this. Please help! Here is the code I have so far.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.io.*;
import java.util.ArrayList;
/**
* Write a description of class HighScoresButton here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class HighScoresButton extends Actor
{
ArrayList<String> highScores = new ArrayList();
/**
* Act - do whatever the HighScoresButton wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
if (Greenfoot.mouseClicked(this))
{
Greenfoot.setWorld(new HighScores());
try
{
createFile();
readFile();
}
catch(IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
public void createFile() throws IOException
{
FileWriter fw = new FileWriter("High Scores.txt", true);
String highscore = Integer.toString(GameOver.finalScore.getValue());
for (int x=0; x < highscore.length(); x++)
{
fw.write(highscore.charAt(x));
}
fw.close();
}
public void readFile() throws IOException
{
FileReader fr = new FileReader("High Scores.txt");
char [] a = new char [50];
fr.read(a);
for (char c : a)
{
System.out.print(c);
}
fr.close();
}
}
