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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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(); } } |