3

I have now written high scores to a text file at gameover, and read them at game load. The problem I have now is that the txt file highscores.txt isn't found anywhere because I haven't created it. Is it possible to have the file created whenever it isn't found? Here is the relevant code:

Write highscores to file at gameover:

if(gameOver == true){
        sbg.enterState(5, new FadeOutTransition(), new FadeInTransition());
        if(score > Highscores.highscore3 && score < Highscores.highscore2){
            Highscores.highscore3 = score;
        }else if(score > Highscores.highscore2 && score < Highscores.highscore1){
            Highscores.highscore3 = Highscores.highscore2;
            Highscores.highscore2 = score;  
        }else if(score > Highscores.highscore1){
            Highscores.highscore3 = Highscores.highscore2;
            Highscores.highscore2 = Highscores.highscore1;
            Highscores.highscore1 = score;
        }else Highscores.highscore1 = score;

        //Write highscores to highscores.txt
        try{
            PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
            writer.println(String.valueOf(Highscores.highscore1));
            writer.println(String.valueOf(Highscores.highscore1));
            writer.println(String.valueOf(Highscores.highscore1));
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        gameOver = false;
        gameStart = false;
    }

Read highscores from highscores.txt at program start:

public static void main(String[] args) throws IOException{

    BufferedReader in = new BufferedReader(new FileReader("highscores.txt"));
    String line;

    while((line = in.readLine()) != null){
        System.out.println(line);
    }
    in.close();

I know that I can create a file if it doesn't exist like this:

try{
File save = new File("highscores.txt");
if (!save.exists()){
    save.createNewFile();
System.out.println("\n----------------------------------");
System.out.println("The file has been created.");
System.out.println("------------------------------------");
}

But I don't know how to do that with buffers. Please help!

Mamshmo
  • 71
  • 8

3 Answers3

1

Let me preface by saying I am not familiar with the best practices for storing game related information on a filesystem. That being said, it sounds like you are trying to learn as you develop this, so with that in mind, I would suggest starting out with writing to a simple .txt file.

The basics can actually be found on SO already:

How to create and write to a txt file: How do I create a file and write to it in Java?
How to read from a txt file: Reading and displaying data from a .txt file
And the Java tutorials for good measure: https://docs.oracle.com/javase/tutorial/essential/io/file.html

What I would do is:
1. Figure out when you want to trigger a write.
When do you want to update your high scores file? To me, it looks like this would be in your Gameplay class around ln 158, where you determine that the game has ended:

//Change to GameOverEasy state if gameOver is true
            if(gameOver == true){


2. Figure out when you need to read in your file to populate Highscores. Poking around your code in pastebin, that to me seems like something you would want to do on startup in the main method of your Blop class, before you start loading game states/looping:

        public static void main(String[] args) throws IOException{

            AppGameContainer appgc;
            try{
                    appgc = new AppGameContainer(new Blop(NAME));

                    //Window size
                    appgc.setDisplayMode(960, 640, false);
                    appgc.setShowFPS(false);
                    appgc.setAlwaysRender(true);
                    appgc.setTargetFrameRate(60);
                    appgc.setVSync(true);
                    Display.setIcon(new ByteBuffer[] {
                new ImageIOImageData().imageToByteBuffer(ImageIO.read(new File("res/images/general/Icon16.png")), false, false, null),
                new ImageIOImageData().imageToByteBuffer(ImageIO.read(new File("res/images/general/Icon32.png")), false, false, null)
                });

//TODO: Read in high scores file and populate Highscores class

                    appgc.start();
            }catch(SlickException e){
                    e.printStackTrace();
            }


3. Figure out how to format your text file. You are ordering the scores already, so you could store them that way as well. Either saving one score per line or using a delimiter like "," or "|" would work with what you currently have.


Start with the simple text file, and change to something else if it suits your needs. If this is a test/learning project, I strongly recommend you keep it simple and stick with a simple .txt file until you wrap your head around it a bit more

A few things to keep in mind:

  1. You are going to run into a lot of exception handling. When reading that file in, you will need to determine if your game should fail to start because you could not load the high scores file? On the other side, is it a critical error when you fail to write to that file?
  2. Always be closing

EDIT: Regarding your followup questions, you want to use the actual name of the file you are using. Javadocs are your friend. Regarding your second question, check out some other SO posts. It's pretty well covered.

Community
  • 1
  • 1
Nick DeFazio
  • 2,312
  • 25
  • 30
  • Thanks so much for your answer! So after looking at this http://stackoverflow.com/questions/731365/reading-and-displaying-data-from-a-txt-file I noticed this "" does this mean that I replace it by "highscores.txt"? ""? ... – Mamshmo Oct 22 '15 at 22:05
  • Last question, is there a way to create the file if it isn't in the directory yet? I know there is one for java Files: if(!file.exists()){ ... but I'm not sure I can apply it to buffers. – Mamshmo Oct 22 '15 at 22:12
0

Have the filewriter write those values into .txt file before program closes and then have filereader read and load those values into the high-score instance variables. It is not really a rocket science.

The Law
  • 385
  • 3
  • 20
  • Ok, I'm not sure how I can show you what I've done, but I've written the file, but then I'm not sure how to read it when the program loads. Could you please explain? – Mamshmo Oct 22 '15 at 21:36
0

Everything works, here is how to save high scores when the game is over, and how to load them when the program is launched.

When the first time the program is launched, it checks if there is a file called highscores.txt, if there isn't, it creates one AND PLACES 3 ZEROS IN THE FILE SO YOU DO NOT GET AN EXCEPTION THAT THE FILE IS EMPTY!:

//Read highscores from highscores.txt
    File save = new File("highscores.txt");
    if (!save.exists()){
        save.createNewFile();
        System.out.println("\n----------------------------------");
        System.out.println("The file has been created.");
        System.out.println("------------------------------------");
        //Places the default 0 values in the file for the high scores
        PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
        writer.println(String.valueOf(0));
        writer.println(String.valueOf(0));
        writer.println(String.valueOf(0));
        writer.close();
    }

When you play the game a couple times, the high scores will be written on the highscores.txt file when the game is in the "gameover" state:

//Write highscores to highscores.txt
        try{
            PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
            writer.println(String.valueOf(Highscores.highscore1));
            writer.println(String.valueOf(Highscores.highscore2));
            writer.println(String.valueOf(Highscores.highscore3));
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }

And finally, when you close the program the last values of highscore1, highscore2 and highscore3 were written on the highscores.txt file. So when you launch the program, you want to read those integers from that file. Since the file contains strings, and I want integers, I have to get the line from the file in the form of a string, convert it to integers, then assign it to the variables Highscores.highscore1 ... (this is under the "file checker" if() statement)

//Read string values of high score and convert to int to put into variables
    BufferedReader in = new BufferedReader(new FileReader("highscores.txt"));
    String line;
    line = in.readLine();
    Highscores.highscore1 = Integer.parseInt(line);
    line = in.readLine();
    Highscores.highscore2 = Integer.parseInt(line);
    line = in.readLine();
    Highscores.highscore3 = Integer.parseInt(line);

    in.close();

So when you open the program again, the last values that were written on the highscores.txt files will be put into your high score integers. And that's how you save them!

Mamshmo
  • 71
  • 8