Results 1 to 7 of 7
  1. #1
    Johnny22 is offline Member
    Join Date
    Jun 2011
    Posts
    31
    Rep Power
    0

    Default Implementing Highscore for an App

    I did an simulation of a game, a puzzle game.
    Now I'm trying to implement a HighScore feature for the app.

    When I open the App, the player will need to enter a name in order to continue. str variable.
    When the player will complet a game he will need to hit a button CHECK in order to validate the game, if the game is valid a mesage will display his current Score(I have different puzzle sizes with different scores). This is saved into highscore and is updated everytime a new game is validated.

    Now I want to add a menu, that when is clicked it will display the first 5 HighScores.

    When the Highscore menu is selected I want to read a file and check if the players name is allready in the file(check if str is found): if it is not found add str+highscore to the file, if it is found, check if highscore from file is bigger than actual score and update highscore of that player if true, otherwise do nothing. Finaly after writing and updating(if necesary) to the file, read the file and display the name and scores for the best 5 players.

    here is what I did till now :

    This is in the menu listener, at the HighScore menu.
    Java Code:
    try{// Create file
                                  String file = ((System.getenv("USERPROFILE"))+("\\My Documents\\"));
                                  FileWriter fwrite = new FileWriter(file+"out.txt", true);
                                  BufferedWriter writer = new BufferedWriter(fwrite);
    
    
                                  FileReader fread = new FileReader(file+"out.txt");
                                  BufferedReader reader = new BufferedReader(fread);
    
                                  writer.write(ValidateGameListener.highscore+" "+MainUI.str);
                                  writer.newLine();
                                  //Close the output stream
                                  writer.close();
    
                                  while((file = reader.readLine()) != null) {
                                    System.out.println(file);
                                    JOptionPane.showMessageDialog(gameController.view, file);
                                  } 
    
                                  }
                                catch (Exception error){//Catch exception if any
                                  System.err.println("Error: " + error.getMessage());
                                  }
    The problem that I can't solve is that I can't manage to update score for specific player, everytime a new player with the curent score is inserted into file.
    And It's displaying the file line by line(One line appears in the windows, I press ok, next line is shown, till end of file). I want to display them as a list in only one dialog window.
    Also how to separate the name from score in order to check which score is bigger ?

    Can someone help me with this and give me some ideas ?

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,902
    Rep Power
    25

    Default

    how to separate the name from score
    I'll start with the last one.
    How are the names and scores stored? If in a String, look at the String class's split method. Also maybe the StringTokenizer class could be used.

    update score for specific player, everytime a new player with the curent score is inserted into file.
    To upate a small part of a file, either rewrite the whole file or if the records for each player are the same size, you could use the RandomAccessFile to just rewrite one part of a file.

    want to display them as a list in only one dialog window
    There are Many ways to list data. What one do you want to use? As text in a text area, a pull down list, a table ???

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    I'd use a Properties object and let that object do the hard job; properties such as:

    Java Code:
    score0.value = ...
    score1.value = ...
    score2.value = ...
    score3.value = ...
    score4.value = ...
    score0.name = ...
    score1.name = ...
    score2.name = ...
    score3.name = ...
    score4.name = ...
    ... would cover it all. The Properties object itself is very well capable of reading/writing itself.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  4. #4
    Johnny22 is offline Member
    Join Date
    Jun 2011
    Posts
    31
    Rep Power
    0

    Default

    I tried using Properties, but it will overwrite the values.
    And I can't use prop1, prop2, etc.
    I will try more with ArrayList. I found a good example, and trying to make it work for me... Till now I managed to make it add value to the file(it is scripted so no-cheating), and it will display first 10 best scores top-to-bottom.
    Now I need to figure it out how to make it add only name is not found in file, and if found, update the score(for the update I thought about deleting the entire row, and add the new one to the file - but can't find how to delete it)... I will try a little more, and if I can't manage to make it work I will post the code here.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,457
    Rep Power
    20

    Default

    Scripted or encrypted?

    db

  6. #6
    Johnny22 is offline Member
    Join Date
    Jun 2011
    Posts
    31
    Rep Power
    0

    Default

    Encrypted, i think ... in the mean that it will show strange chars if opened.

    Also now I want to ADD the score even if the Player is the same, just not to add when the line is the same(to make duplicate lines)

    Also here is the code:

    HighscoreManager
    Java Code:
    package appClientModule.controller;
    
    import appClientModule.controller.listeners.ValidateGameListener;
    import appClientModule.view.MainUI;
    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
        public ArrayList<Score> 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<Score>();
        }
    
        public ArrayList<Score> getScores() {
            loadScoreFile();
            sort();
            return scores;
        }
    
        private void sort() {
            ScoreComparator comparator = new ScoreComparator();
            Collections.sort(scores, comparator);
    }
    
        public void addScore(String name, int score) {
            
            if((getNames().contains(MainUI.str))){
                 //Here I want to somehow update the score(because it will add the score even if it is already in the file- it's making duplicate)
            loadScoreFile();
            scores.add(new Score(name, score));
            updateScoreFile();
            System.out.println("INSIDE IF -> same name");
            System.out.println(MainUI.str);
            System.out.println(getNames());
            
    
            }//this was only for test
     /*       else{//MainUI.str != name
                loadScoreFile();
                scores.add(new Score(name, ValidateGameListener.highscore));
                updateScoreFile();
                System.out.println("OUTSIDE IF -> diff name");
                System.out.println(MainUI.str);
                System.out.println(getNames());
            } 
       */
            
    }
    
        public void loadScoreFile() {
            try {
                inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE));
                scores = (ArrayList<Score>) 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());
                }
            }
    }
        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());
                }
            }
    }
    
        public String getHighscoreString() {
            String highscoreString = "";
    	int max = 10;
    
            ArrayList<Score> newscores;
            newscores = getScores();
    
            int i = 0;
            int x = newscores.size();
            if (x > max) {
                x = max;
            }
            while (i < x) {
                
                highscoreString += "\n<html>"+(i + 1) + ".\t" + newscores.get(i).getNaam() + "\t\t<font size=\"4\", color=\"red\">" + newscores.get(i).getScore() + "</font></html>";
                i++;
            }
            return highscoreString;
    }
      
    //this one I made to check if the name is in the file, but now I want to check entire line and see if it's already in the file  
            public String getNames() {
            String name = "";
    	int max = 10;
    
            ArrayList<Score> newscores;
            newscores = getScores();
    
            int i = 0;
            int x = newscores.size();
            if (x > max) {
                x = max;
            }
            while (i < x) {
                
                name += newscores.get(i).getNaam()+"\n";
                i++;
            }
            return name;
    }
    
    }
    Score
    Java Code:
    package appClientModule.controller;
    
    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;
        }
    
    
    }
    ScoreComparator
    Java Code:
    package appClientModule.controller;
    
    import java.util.Comparator;
    
    public class ScoreComparator implements Comparator<Score> {
            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;
                }
            }
    }
    If you want to test you can crate a MAIN with the following code:

    Java Code:
    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());
        }
    
    
    }
    But I'm getting the data from the input or from a variable that is always updated when a game is validated:

    Here I show the result in a message window:
    Java Code:
            if (event.getSource()==gameController.view.menuHighscore){
    		    
     
                            System.out.print(ValidateGameListener.hm.getHighscoreString());
                         
                         JOptionPane.showMessageDialog(gameController.view, "<html>Hello  <i>"+MainUI.str+"</i>. Your score till now is is :  <font color=\"red\"><i>"+ValidateGameListener.highscore+"</i></font>\n"
                                 + ValidateGameListener.hm.getHighscoreString());
                         
                         
                     }
    Here I add the values into file when a game is validated :

    Java Code:
                                JOptionPane.showMessageDialog(gameController.view,"Game is valid, congratulations!!\nYour Score is: "+highscore+"\nGood job!");
    			    MainUI.button.setEnabled(false);
                                System.out.println("Your Score is: "+highscore);
    
                                hm.addScore(MainUI.str,ValidateGameListener.highscore);
                                 System.out.print(ValidateGameListener.hm.getHighscoreString());
    I found a workaround - when the Game is Validated the button will be deactivated so the player won't be able to duplicate the line in the file(the score variable is always incremented).
    But one minor defect: If same name is inserted is possible for a score to be duplicated, althought that chance is pretty small.

  7. #7
    Johnny22 is offline Member
    Join Date
    Jun 2011
    Posts
    31
    Rep Power
    0

    Default

    sorry for DP.
    Last edited by Johnny22; 06-14-2011 at 11:42 PM.

Similar Threads

  1. Implementing a pdf template
    By africanhacker in forum New To Java
    Replies: 0
    Last Post: 06-13-2011, 11:08 PM
  2. Highscore table for my game
    By richman92 in forum Java Applets
    Replies: 1
    Last Post: 02-26-2011, 06:21 AM
  3. Help in implementing XOR functions
    By Manfizy in forum New To Java
    Replies: 3
    Last Post: 04-13-2010, 03:25 AM
  4. IMplementing the DES algo
    By jkuzhuppallil in forum Advanced Java
    Replies: 3
    Last Post: 10-01-2008, 09:24 PM
  5. Help implementing JDBC
    By mooey1232003 in forum New To Java
    Replies: 6
    Last Post: 07-11-2007, 11:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •