Highscores save and load.

Hello, I have a question. I want to save the highscorelist in my game. Could you help me save and load the highscores? I have not found anything here that would solve my problem. Here is my code.

int[] scores = new int[5];

int score;

void setup() {

      size(1260, 720);
      for (int i=0; i<scores.length; i++){
      scores[i] = 0;
      }

 }

void draw() {

      background(0);
      textSize(80);
      fill(255, 0, 0, 255);
      text("Highscores ", 300, 160);
      for (int i=0; i<scores.length; i++) {
      textSize(60);  
      text(scores[i], 570, 300+80*i);
      }
}

 void keyPressed() {

      score = int(random(100));
      addNewScore(score);

 }

 void addNewScore(int score) {

      for (int i=0; i<scores.length; i++) {
        if (score>=scores[i]) {
          for (int j=scores.length-1; j>=max(i,1); j--) {
            scores[j] = scores[j-1];
          }
          scores[i] = score;
          break;
        }
      }

 }

Answers

  • edited July 2017

    I would be very happy about help. :)

  • Look at loadStrings and saveStrings in the reference please

  • edited July 2017

    @Chrisir I tried to use save and loadStrings, but it doesn't work. If you know how it works, please show me how to implement this to my code. I'm new in processing and I tried for 2 weeks to save and load the Strings. Sorry, but your answer is crap. My code is about 20 lines. if you know how, then please show me ;)

  • edited July 2017

    @kfrajer Do you really think, that your post help? There is nothing that can solve my problem in that post. Absolutely nothing. If you are able to do that, why you did not show me? My code is about 20 lines, please show me Einstein...

  • I think that you both are not able to do that and try to advise me to other topics. You want to answer my question with crap posts but you wouldn't help me. I postet my code to show you my problem but you don't look at it or tried to understand my problem. load and saveStrings doesn't work for me. If you really want to help, show me how to implement this into my code and please don't answer if you don't know how...

  • @MigiModo

    I have not found anything here that would solve my problem

    You get feedback based on the information you provide in your post. The information you provided is vague as you **didn't describe your problem. Since we don't know what your problem is, then you get redirected to the reference so you can read it and learn how to properly use the functions provided by Processing.

    I check the post I provided to you. It is the second or third link that provides a working example in java storing highscores: https://forum.processing.org/two/discussion/17222/highscores-after-exiting/p1

    The search engine in the forum is not optimized but it works if you ask the right question.

    Please, be polite to the people in the forum. Most people (all people?) here are volunteers.

    Kf

  • edited July 2017

    @kfrajer I told you, that this example doesn't work for me. If you really want to help, show me how to implement this in my code and not redirecting me in examples they didn't work for me. You see in my code, that I didn't use any Strings and I don't know how to implement this to save. I asked for help and you send me to other links were are no solutions for my problem. That ist no help. I ask 2 times to told me how to implement this. If you are unable to do this, then please let other people help me. Sorry for my bad english. how can I save my int arrays in my highscorelist and how can I load them. That is the question. I'm not able to do this and ask for help. Is that too heavy to understand? save and loadStrings doesn't work in my code yet. I don't know how to implement this. I'm 14 years of age and I'm new in processing. Redirecting to links were are no solutions is not help in my opinion. please show me how to use save and loadStrings in my code...

  • I give all informations you need to help me. But you redirecting me to other therms and topics they don't help me. You see my code. Can you help me to save and load this or not? Which information do you need???

  • @kfrajer I did not use Android... I tried to save my own highscorelist in my code and load this in java. You understand me or not? I don't know how to use save and loadStrings in my code. I read all the preferences in processing but I don't find any working examples. And in this whole forum there is no solution for my problem. Then please don't redirecting me to crap that doesn't work for me. I only need a little help to save the scores in my code. I did not know that this is too heavy for this forum...

  • edited July 2017

    @GoToLoop very funny, very funny... How old are you guys? I'm 14 years of age and I think I'm smarter than you guys. I think nobody here is able to help me with my code and you want to kidding me with your crap links they doesn't help me... I'm here in questions about code and not in questions about links.. I answered a question and I was very precisely in my opinion. very funny, to make fun about an 14 year old guy he's tryin' to figure out a thing. Wow. Is it to heavy to answer for my code? nobody have to or is forced to help me, but kidding is not funny. I say it 3 times and every time I was satisfied about an answer... It is a crap link. thanks for nothing... I search for a german forum with smart guys...

  • @MigiModo as much as you would like to, you cannot force someone to help you by yelling at them or being rude. I know it can be frustrating to receive short answers, but the truth is, that ALOT of the users that post questions haven't even looked at the reference or tried to solve the question themselves, which means that the same questions get postet time after time, and when you've been on this forum for a while, you get quite tired of the same old questions.

    Now, I will try to help you with your problem if you can manage to not yell me out. If you still want, that is.

    Personally, I would use a table rather than loadString(), mostly because I am more familiar with that, but also because you might want to save more details along with the highscore later. And using a table, you can easily add that at a later stage.

    Here is example I found in the reference on Table:

    Table table;
    
    void setup() {
    
      table = new Table();
    
      table.addColumn("id");
      table.addColumn("species");
      table.addColumn("name");
    
      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());
      newRow.setString("species", "Panthera leo");
      newRow.setString("name", "Lion");
    
      saveTable(table, "data/new.csv");
    }
    

    Line 7-9 names the columns of the table, which can be quite useful for later use. You can see that in line 12-14, we use these names to decide which column we want to add data to. The first argument is the name of the column, the second argument is data we want to store in that column. But how do we know which row we are storing this in? Well, we know, that we are storing it in a new row below the previous because of line 11, where we add a row.

    So, how do you implement this into your sketch?

    1. organize the data you want to store
    2. create the base of the new table in setup() or in a new function
    3. make a function that adds your data to the table
    4. for(every piece of data in your array) run the function that adds the data

    You are already pretty much done with the first step, because you already have an array with your highscores. step 2 and 3 is mostly copy and paste and you seem to be quite known with for-loops, so I think you will figure this out.

    If you have any difficulties, just @mention me

  • I forgot to say that when you save a table, you have to specify what kind of table you want it to be. Most commonly used are csv, which stands for comma separated value, and tsv, which is short for tab separated value. As you can imagine, csv seperates the values with a comma, and tsv separates the values with a tab.

    This means that you can crate your own table by opening up textEditor write your table (a new row in the editor is a new row in the table) separate you values with either commas or tabs. When you are done with your table, you can save it as a csv og tsv, depending on how you separated the values. And then you can load that into your sketch with loadTable();

  • @Eeyorelife first of all, thanks for your answer. I don't yelling at anybody. I asked a clear question about code and got links to other topics where are no solutions. I said 3 times that I don't want to get links because they don't help me and they thought it was funny to spam me full with links. I tried to implement your idea in my sketch, but I'm not able to do that. I got no plan which value of which array is beeing used. By the way I got trouble to understand all the things in English. thanks for your help and I will try it now a few times more. :) Maybe I can do it by my own.

  • Ok, I think, nobody in this Forum ist able to implement this to my code. Everybody posted links or examples but nobody tries to help me to implement this to my code. How should I learn something, when nobody teaches me the right way. No teacher in the world gives you examples without an explaination. If anyone is able to help me, then I would be glad if you show me how to implement this in my code. Thank you...

  • edited July 2017

    If I were the best programmer in the world and can implement every example without asking other people, then I don't have to ask for help. Think about it...

  • The support of this program is very bad and I think that this program is to complicated to start learning.

  • I am sorry, I am on holiday away from home and only on my iPhone. Therefore I cannot really help you.

    Looking at your code in your original post: does the code in itself work?

    Is the addNewScore adding a new score so that the list stays sorted?

    Did you try saveStrings (scores, "score.txt");

    or so? What happened?

    Most people here help by giving hints instead of providing full code solutions so people can find out on their own. I can understand this is frustrating at times.

    Best, Chrisir ;-)

  • If I were the best programmer in the world and can implement every example without asking other people, then I don't have to ask for help. Think about it...

    You would be surprised to know how many people ask for solutions without ever trying to search for an example before asking. Besides, you don't have to be the best programmer in the world to be able to implement an example.

    Ok, so they key to being able to implement any exapmle into your code is to understand the example. So for a moment, you should forget your own code and just play around with the example. Try to modify it until you are sure you understand how it works. Because then you can pull it apart and put it back together again, which is useful when you want to implement it into your code.

    Here is what we start with (the example):

    Table table; 
    
    void setup() {
    
      table = new Table(); 
    
      table.addColumn("id");
      table.addColumn("species");
      table.addColumn("name");
    
      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());
      newRow.setString("species", "Panthera leo");
      newRow.setString("name", "Lion");
    
      saveTable(table, "data/new.csv");
    }
    

    And we want to be able to modify it so that we can use it for our purpose. I want to be able to add new rows to the table more dynamically. Because as the code is now, I am only adding the data I have predetermined. Which is quite boring. So I am going to make a function addData(); Which will create a new row and then add some data to that row. But if we want to be able to store this information for longer than the duration of the sketch, we have to save this table. So we want another function saveT(); which will just save the table. But kind of data do we want to add? For now, let's just add the location of the mouse when I press the leftt-button and save the table when I press right-button. Here is a pseudocode:

    void setup(){
    //setup the base of the table like before
    }
    
    void draw(){
    //we need draw to be running to be able to test for mouseclicks, but we won't put anything in it
    }
    
    void mouseClicked(){
    //if(left-click) add data
    // else save the table
    }
    
    void addData(){
    //add some data to the table
    }
    
    void saveT(){
    //save the table
    }
    

    So now, we can just take all the code from the example and place paste it into this structure. I don't want to change anything other than the structure just yet, I want to be sure we don't have any errors. Now it looks like this:

    Table table;
    
    void setup() {
      //setup the base of the table like before
      table = new Table(); 
    
      table.addColumn("id");
      table.addColumn("species");
      table.addColumn("name");
    }
    
    void draw() {
      //we need draw to be running to be able to test for mouseclicks, but we won't put anything in it
    }
    
    void mouseClicked() {
      //if(left-click) add data
      // else save the table
      if (mouseButton == LEFT) addData();
      else saveT();
    }
    
    void addData() {
      //add some data to the table
      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());
      newRow.setString("species", "Panthera leo");
      newRow.setString("name", "Lion");
    }
    
    void saveT() {
      //save the table
      saveTable(table, "data/new.csv");
    }
    

    Remember: you have to save this sketch in order to check if it works. So if you save the file, then run it and press the mousebutton a couple of times, then go to open up the .csv file in the data folder, you will see something like this:

    id,species,name
    0,Panthera leo,Lion
    1,Panthera leo,Lion
    

    So we know it works, now we just have to modify it a little bit so we it does what we want it to do. In setup() we change the names of the columns to id, x, y. We want addData() to be able to receive the x and y location of the mouse so we do this:

    void addData(float x, float y) {
      //add some data to the table
      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());
      newRow.setInt("x", int(x));
      newRow.setInt("y", int(y));
      println(x + " " + y);
    }
    

    Note that I changed line 5 and 6 from newRow.setString() to newRow.setInt(), because we want numbers, not words. And lastly, in mouseClicked we pass the mouse positions to addData() Here is the result:

    Table table; 
    
    void setup() {
      //setup the base of the table like before
      table = new Table(); 
    
      table.addColumn("id");
      table.addColumn("x");
      table.addColumn("y");
    }
    
    void draw() {
      //we need draw to be running to be able to test for mouseclicks, but we won't put anything in it
    }
    
    void mouseClicked() {
      //if(left-click) add data
      // else save the table
      if (mouseButton == LEFT) addData(mouseX, mouseY);
      else saveT();
    }
    
    
    void addData(float x, float y) {
      //add some data to the table
      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());
      newRow.setInt("x", int(x));
      newRow.setInt("y", int(y));
      println(x + " " + y);
    }
    
    void saveT() {
      //save the table
      saveTable(table, "data/new.csv");
      println("done");
    }
    

    Now, I feel like I really understand the code. I know what it does and I know why it acts like it does. I have really gotten to know the Table class and I feel like I am ready to implement it into your code. If you feel the same way you should not look at what comes next. If you feel like you understand the code you should try to do this last step for yourself. Maybe even if you don't feel like you fully undersand. Because you will learn a whole lot more if you actually fo it yourself, than if you just copy my result. My result might not even be the best one. You know your own code best, so you know how to should behave. But yeah, here is my solution:

    int[] scores = new int[5];
    
    int score;
    Table table; 
    
    void setup() {
      size(1260, 720);
      for (int i=0; i<scores.length; i++) {
        scores[i] = 0;
      }
    
      //setup the base of the table like before
      table = new Table(); 
      table.addColumn("id");
      table.addColumn("HighScore");
    }
    
    void draw() {
      background(0);
      textSize(80);
      fill(255, 0, 0, 255);
      text("Highscores ", 300, 160);
      for (int i=0; i<scores.length; i++) {
        textSize(60);  
        text(scores[i], 570, 300+80*i);
      }
    }
    
    
    
    void keyPressed() {
      score = int(random(100));
      addNewScore(score);
    }
    
    void addNewScore(int score) {
      for (int i=0; i<scores.length; i++) {
        if (score>=scores[i]) {
          for (int j=scores.length-1; j>=max(i, 1); j--) {
            scores[j] = scores[j-1];
          }
          scores[i] = score;
          break;
        }
      }
    }
    
    void mouseClicked() {
      //if(left-click) add data
      // else save the table
      if (mouseButton == LEFT) {
        for (int i = 0; i<scores.length; i++) {
          addData(scores[i]);
        }
      } else saveT();
    }
    
    void addData(int HighScore) {
      //add some data to the table
      TableRow newRow = table.addRow();
      newRow.setInt("id", table.lastRowIndex());
      newRow.setInt("HighScore", HighScore);
    }
    
    void saveT() {
      //save the table
      saveTable(table, "data/new.csv");
    }
    
  • Ok, first thank you for your continued efforts. My game works completely. My only problem is that I want to save my highscores so that they are loaded automatically at startup. I tried everything, but it doesn't want to succeed. I would like to show you my whole game, so you can see that I have given myself efforts and being not a fool. @Eeyorelife your code do not work. I tried it in 3 different ways, but it doesn't work. Excuse me for being so rude, but it is very frustrating when you get such difficulties in the end. Thanks for your help.

  • edited July 2017

    Here can you download my game and can see what is my problem. My highscore system works very fine, but it doesn't save or load the highscores after I close the program. Maybe you have to play it before you understand my problem and can help me better. :)

    https://www.dropbox.com/sh/99c7ksmltcgfq5d/AABTYMKApMoJJdXZTSiGjMrfa?dl=0

    you have to download the complete application folder on the top right and then direct download.

  • edited July 2017

    your code do not work

    How so? Does the sketch not run? Do you get an error? I don't think you are a fool. If you explain what the problem is, then we might be able to fix it.

    I tried it in 3 different ways, but it doesn't work

    This doesn't help me in helping you. I don't know what you tried or what went wrong. If you post the code that didn't work for you, someone will likely be able to point out why it isn't working and how you can improve it.

    If you look at my final sketch you may notice that I am saving the table, but not loading it. Which means that the sketch do not receive any information from the table, it only writes to it. Is that your problem? If so, you can either create a .csv file manually and load it with your sketch. Or you can try to load a .csv file and if it doesn't excist, then you create a new one.

  • edited July 2017

    Your sketch run, but the scores are not loading when I start the sketch. It saves an .csv file into the data folder but it doesn't work to save the scores correctly and load them by starting the sketch. For today I got a blackout and will not try it again, before I destroy my PC. Why is such a simple function so complicated? I think it should be easier to save and load values. I'm 14 years of age, live in Germany, my English is limited and I'm no college student or something. I started with 0% of knowledge. I gave my very best into my game and all ends with saving and loading the scores... It is ridiculous :) I made this for my internship in August. I want to become a programmer in the future, but this program make me cry. I really have to think about my future plans. :)

  • edited July 2017

    Originally, I wanted to enter a name for the highscores, but that was too complicated for me. There is too little help or support for this program on the Internet. But I understand, that this is for college students and not for school boys. I can not describe my problem better than I do it before. I just want to save and load the scores. Very simple, but a very hard challenge in Processing.

  • The next thing that will be posted here is "use loadTable"...... if anyone want to post this, please show me in my code, because I don't know how to use this function and I only can learn from running systems and not broken parts. Thanks for your help and for your time. I appreciate this.

  • Anyone can learn how to code, but a small mistake can be a huge pain in the ass. I can help you tomorrow as I am busy today. Sometimes it is good to take a breake and come bakc to the code later.

  • Answer ✓

    Hello,

    back from holidays.

    Here is my version with loadStrings based on your very first post above.

    Best, Chrisir ;-)

    int[] scores = new int[5];
    String fileName = "score1.txt"; 
    
    // --------------------------------------------------------
    // processing core functions: setup and draw  
    
    void setup() {
      size(1260, 720);
      initHighscore();
    }//func
    
    void draw() {
      background(0);
      showHighscore();
      // show help text (white line of text) 
      textAlign(CENTER);
      fill(255); 
      textSize(17);
      text("Press space bar to add a score; q to save and quit", width/2, 200);
      textAlign(LEFT);
    }//func
    
    // ----------------------------------------------------------------
    // functions called from setup()  
    
    void initHighscore() {
    
      // define high score: either use a empty list or 
      // load from hard drive if a file is there. 
    
      // pre-init 
      for (int i=0; i<scores.length; i++) {
        scores[i] = 0;
      }
    
      // we try to load 
      String[] scoresAsStrings=null;
      scoresAsStrings = loadStrings(fileName);
    
      // Did we find a file? 
      if (scoresAsStrings!=null) {
        // load was successful
        for (int i=0; i<scores.length; i++) {
          // put strings into scores as int 
          scores[i] = int(scoresAsStrings[i]);
        }
      } else {
        // No file existed. 
        println("New Score initialized - first run\n");
      }
    } // func
    
    // -------------------------------------------------------
    // All Input functions 
    
    void keyPressed() {
      // keyboard input 
      if (key==' ') {
        // add one element to high scores
        int score;
        score = int(random(100));
        println(score); 
        addNewScore(score);
      } // if 
      // ---------------
      else if (key=='q') {
        // save and quit 
        // convert to string array
        String[] scoresAsStrings = new String[scores.length];
        for (int i=0; i<scores.length; i++) {
          scoresAsStrings[i]=str(scores[i]);
        }
        // save
        saveStrings(fileName, scoresAsStrings);
        // quit program
        exit();
      }//else if
    }//func
    
    // --------------------------------------------------------
    // functions called from draw() 
    
    void showHighscore() {
      // displays the high score 
      textSize(80);
      fill(255, 0, 0, 255);
      textAlign(CENTER);
      text("Highscores ", width/2, 160);
      for (int i=0; i<scores.length; i++) {
        textSize(60);  
        text(scores[i], width/2, 300+80*i);
      }
      textAlign(LEFT);
    } // func
    
    void addNewScore(int score) {
      // adds element when its high enough and sorts high score list. 
      for (int i=0; i<scores.length; i++) {
        if (score>=scores[i]) {
          for (int j=scores.length-1; j>=max(i, 1); j--) {
            scores[j] = scores[j-1];
          }
          scores[i] = score;
          break;
        }
      }
    } //func
    //
    
  • Answer ✓

    New Version with Name Input - unfortunately more complicate than I thought.

    Better stick with the previous version without names...

    Chrisir

    // high score: New Version with Name Input
    
    String[] scores = new String[5]; // high score = list of Strings (number plus name) 
    String fileName = "score1.txt"; // file name 
    String score;  // a new score to add 
    
    // the Input Box 
    TextBox tbox;
    
    // states of a program - necessary for the Input Box 
    final int stateNormal   = 0;
    final int stateInputBox = 1;
    final int stateAfterInputBox = 2;
    int state=stateNormal; 
    
    // the user name (result of the Input Box)
    String result="/"; 
    
    // --------------------------------------------------------
    // processing core functions: setup and draw  
    
    void setup() {
      size(1260, 720);
    
      // init highscore 
      initHighscore();
    
      // init the input box for the name 
      instantiateBox();
      tbox.isFocused = true;
    }//func
    
    void draw() {
      // state tells how the program works: 
      if (state==stateNormal) {
        // normal state = show high score 
        background(0);
        showHighscore();
        // show help text (white line of text) 
        textAlign(CENTER);
        fill(255); 
        textSize(17);
        text("Press space bar to add a score; q to save and quit", width/2, 200);
        textAlign(LEFT);
      } 
      // -------------------
      else  if (state==stateInputBox) {
        // state for the Input Box 
        background(0);
        tbox.display();
      }// else if
      // ------------------
      else if (state==stateAfterInputBox) {
        // state After the Input Box
        score += " "+result; 
        println(score); 
        result="/";
        addNewScore(score);
        saveHighscore();
        state=stateNormal;
      }
    }//func
    
    // ----------------------------------------------------------------
    // functions called from setup()  
    
    void initHighscore() {
    
      // define high score: either use a empty list or 
      // load from hard drive if a file is there. 
    
      // pre-init 
      for (int i=0; i<scores.length; i++) {
        scores[i] = str(0);
      }
    
      // we try to load 
      String[] scoresAsStrings=null;
      scoresAsStrings = loadStrings(fileName);
    
      // Did we find a file? 
      if (scoresAsStrings!=null) {
        // load was successful
        for (int i=0; i<scores.length; i++) {
          // put strings into scores as int 
          scores[i] = (scoresAsStrings[i]);
        }
      } else {
        // No file existed. 
        println("New Score initialized - first run\n");
      }
    } // func
    
    void instantiateBox() {
      // init the Input Box 
      tbox = new TextBox(
        "Please enter your name: ", 
        width/2-width/3, height/4 + height/16, // x, y
        width/3, height/2 - height/4 - height/8, // w, h
        215, // lim
        0300 << 030, color(-1, 040), // textC, baseC
        color(-1, 0100), color(#FF00FF, 0200)); // bordC, slctC
    }//func 
    
    // -------------------------------------------------------
    // All Input functions 
    
    void keyPressed() {
      if (state==stateNormal) {
        //
        keyPressedForStateNormal();
      } else if (state==stateInputBox) {
        //
        tbox.tKeyPressed();
      }
    }//func
    
    void keyPressedForStateNormal() {
      // keyboard input 
      if (key==' ') {
        // add one element to high scores
        score = str(int(random(100)));
        println(score); 
        if (highEnoughForHighScore(score)) {
          state=stateInputBox;
        }
      } // if 
      // ---------------
      else if (key=='q') {
        // save and quit 
        saveHighscore();
        // quit program
        exit();
      }//else if
      else if (key==ESC) {
        key=0; // kill esc
      }
    }//func
    
    void keyTyped() {
      if (state==stateNormal) {
        // do nothing
      } else if (state==stateInputBox) {
        //
        tbox.tKeyTyped();
      }
    }//func 
    
    // --------------------------------------------------------
    // functions called from draw() or other functions 
    
    void showHighscore() {
      // displays the high score 
      textSize(80);
      fill(255, 0, 0, 255);
      textAlign(CENTER);
      text("Highscores ", width/2, 160);
      for (int i=0; i<scores.length; i++) {
        textSize(60);  
        text(scores[i], width/2, 300+80*i);
      }
      textAlign(LEFT);
    }//func
    
    void addNewScore(String score) {
      // adds element when its high enough and sorts high score list. 
      for (int i=0; i<scores.length; i++) {
        if (score.compareTo(scores[i])>0) {
          for (int j=scores.length-1; j>=max(i, 1); j--) {
            scores[j] = scores[j-1];
          }
          scores[i] = score;
          break;
        }//if
      }//for
    } //func
    
    void saveHighscore() {
      // convert to string array
      String[] scoresAsStrings = new String[scores.length];
      for (int i=0; i<scores.length; i++) {
        scoresAsStrings[i]=(scores[i]);
      }
      // save
      saveStrings(fileName, scoresAsStrings);
    }//func
    
    boolean highEnoughForHighScore(String score) {
      // test whether new score is high enough to get into the highscore 
      for (int i=0; i<scores.length; i++) {
        if (score.compareTo(scores[i])>0) {
          return true; // high enough
        }//if
      }//for
      return false; // NOT high enough
    } //func
    
    // ===================================================
    // classes 
    
    class TextBox { // credit gotoloop
    
      // demands rectMode(CORNER)
    
      color textC, baseC, bordC, slctC;
      short x, y, w, h, xw, yh, lim;
    
      boolean isFocused = true;
      String txt = "";
      String title = "";
    
      boolean blinkIsOn=true; 
    
      // construrctor
      TextBox(
        String tt, 
        int xx, int yy, 
        int ww, int hh, 
        int li, 
        color te, color ba, color bo, color se) {
    
        title=tt;
    
        x = (short) xx;
        y = (short) yy;
        w = (short) ww;
        h = (short) hh;
    
        lim = (short) li;
    
        xw = (short) (xx + ww);
        yh = (short) (yy + hh);
    
        textC = te;
        baseC = ba;
        bordC = bo;
        slctC = se;
      } // construrctor
    
      void display() {
        stroke(isFocused? slctC : bordC);
    
        // outer 
        fill(baseC);
        rect(x-10, y-90, w+20, h+100);
    
        fill(0); 
        text(title, x, y-90+20);
    
        // main / inner
        fill(baseC);
        rect(x, y, w, h);
    
    
        fill(textC);
        text(txt + blinkChar(), x, y, w, h);
      }
    
      void tKeyTyped() {
    
        char k = key;
    
        if (k == ESC) {
          // println("esc 2");
          // state=stateNormal; 
          key=0;
          return;
        } 
    
        if (k == CODED)  return;
    
        final int len = txt.length();
    
        if (k == BACKSPACE)  
          txt = txt.substring(0, max(0, len-1));
        else if (len >= lim)  
          return;
        else if (k == ENTER || k == RETURN) {
          // this ends the entering 
          println("RETURN ");
          state  = stateAfterInputBox; // close input box 
          result = txt;
          txt="";
        } else if (k == TAB & len < lim-3)  txt += "    ";
        else if (k == DELETE)  txt = "";
        else if (k >= ' ')     txt += str(k);
      }
    
      void tKeyPressed() {
        if (key == ESC) {
          // println("esc pressed");
          // state=stateNormal;
          key=0;
        }
    
        if (key != CODED)  
          return;
    
        final int k = keyCode;
    
        final int len = txt.length();
    
        if (k == LEFT) 
          txt = txt.substring(0, max(0, len-1));
        else if (k == RIGHT & len < lim-3) 
          txt += "    ";
      }
    
      String blinkChar() {
        if (frameCount%12==0)
          blinkIsOn=!blinkIsOn; 
    
        if (!isFocused) 
          return ""; 
    
        if (blinkIsOn) 
          return "|";
        else return "";
      }
    
      boolean checkFocus() {
        return isFocused = 
          mouseX > x & mouseX < xw & 
          mouseY > y & mouseY < yh;
      }//method
    }//class 
    //
    
  • Better stick with the previous version without names...

    Or use table() ?

  • Yes, I think table would be more elegant; the code gets complicated though because of entering a name....

  • Answer ✓

    Here is my suggestion without names:

    int[] scores = new int[5];
    
    int score;
    Table table; 
    
    String fileName = "new.csv";
    
    void setup() {
      size(1260, 720);
      for (int i=0; i<scores.length; i++) {
        scores[i] = 0;
      }
    
    ///////////////I stole this part from Chrisir//////////////////
      table = null;
      table = loadTable(fileName, "header");
    
      if (table!=null) { //If a table already exist, we just use that
     ///////////////I stole this part from Chrisir//////////////////
        for (TableRow row : table.rows()) { //For every row in table
          int id = row.getInt("id");
          scores[id] = row.getInt("HighScore");
        }
      } else { //If a file cannot be found, we create one!
        table = new Table();  //This is the same setup as before.
        table.addColumn("id"); //You can easily add a column called "name" and display store that as well.
        table.addColumn("HighScore");
        for (int i = 0; i<scores.length; i++) {  //This makes sure the length of the table is same as array
          TableRow newRow = table.addRow();      // But it adds nothing if array is empty
          newRow.setInt("id", table.lastRowIndex());
          newRow.setInt("HighScore", scores[i]);
        }
      }
    }
    
    void draw() {
      background(0);
      textSize(80);
      fill(255, 0, 0, 255);
      text("Highscores ", 300, 160);
      for (int i=0; i<scores.length; i++) {
        textSize(60);  
        text(scores[i], 570, 300+80*i);
      }
    }
    
    
    void addNewScore(int score) {
      for (int i=0; i<scores.length; i++) {
        if (score>=scores[i]) {
          for (int j=scores.length-1; j>=max(i, 1); j--) {
            scores[j] = scores[j-1];
          }
          scores[i] = score;
          break;
        }
      }
    }
    
    void mouseClicked() {
      if (mouseButton == LEFT) {
        score = int(random(100));   //moved this to mouseClicked()
        addNewScore(score); 
        addData();  //When a new number is generated, we want to add it to the table as well, I think.
      } else saveT(); //if you right-click the file gets saved
    }
    
    void addData() {  //This function should now really be called "updateTable" or something
      for (TableRow row : table.rows()) {  //For every row, update the content from the array
        int id = row.getInt("id");
        table.setInt(id, "HighScore", scores[id]);
      }
    }
    
    void saveT() {
      //save the table
      saveTable(table, "data/new.csv");
    }
    

    And here is my suggestion with names:

    int[] scores = new int[5];
    String[] names = new String[scores.length];
    String[] AvailableNames = {"george", "mary", "ferdinand", "jude", "harry", "hermione", "ron", "luna", "albus", "minerva"};
    
    int score;
    Table table; 
    
    String fileName = "new.csv";
    
    void setup() {
      size(1260, 720);
      for (int i=0; i<scores.length; i++) {
        scores[i] = 0;
      }
    
    ///////////////I stole this part from Chrisir//////////////////
      table = null;
      table = loadTable(fileName, "header");
    
      if (table!=null) { //If a table already exist, we just use that
     ///////////////I stole this part from Chrisir//////////////////
    
        for (TableRow row : table.rows()) { //For every row in table
          int id = row.getInt("id");
          names[id] = row.getString("name");
          scores[id] = row.getInt("HighScore");
        }
      } else { //If a file cannot be found, we create one!
        table = new Table();  //This is the same setup as before.
        table.addColumn("id"); //You can easily add a column called "name" and display store that as well.
        table.addColumn("name");
        table.addColumn("HighScore");
    
        for (int i = 0; i<scores.length; i++) {  //This makes sure the length of the table is same as array
          TableRow newRow = table.addRow();      // But it adds nothing if array is empty
          newRow.setInt("id", table.lastRowIndex());
          newRow.setString("name", names[i]);
          newRow.setInt("HighScore", scores[i]);
        }
      }
    }
    
    void draw() {
      background(0);
      textSize(80);
      fill(255, 0, 0, 255);
      text("Highscores ", 300, 160);
      for (int i=0; i<scores.length; i++) {
        textSize(60);  
        text(scores[i], 570, 300+80*i);
        if(names[i] != null) text(names[i], 170, 300+80*i);
      }
    }
    
    
    void addNewScore(int score) {
      for (int i=0; i<scores.length; i++) {
        if (score>=scores[i]) {
          for (int j=scores.length-1; j>=max(i, 1); j--) {
            scores[j] = scores[j-1];
            names[j] = names[j-1];
          }
          scores[i] = score;
          int namePickr = int(random(10));
          names[i] = AvailableNames[namePickr];
          break;
        }
      }
    }
    
    void mouseClicked() {
      if (mouseButton == LEFT) {
        score = int(random(100));   //moved this to mouseClicked()
        addNewScore(score); 
        addData();  //When a new number is generated, we want to add it to the table as well, I think.
      } else saveT(); //if you right-click the file gets saved
    }
    
    void addData() {  //This function should now really be called "updateTable" or something
      for (TableRow row : table.rows()) {  //For every row, update the content from the array
        int id = row.getInt("id");
        table.setString(id, "name", names[id]);
        table.setInt(id, "HighScore", scores[id]);
      }
    }
    
    void saveT() {
      //save the table
      saveTable(table, "data/new.csv");
    }
    

    My code is maybe a bit messy, so I apolagize for that, but if something is unclear, just ask and I will reply.

  • @Chrisir I hope you enjoyed your holidays. both of your new codes to save my scores do work perfectly and are very good explained. Thanks @Chrisir and thanks @Eeyorelife for your efforts. The methods for the name input are not that what I imagined. I try to make a code and show you guys what I mean. I'm so thankful.

  • in my first version there are no names, in my 2nd version the player can enter his or her name and end the input with return

    of course you can change the design of the input box or place it on the screen

    glad you like it!

    Chrisir

  • For everyone who had the same problems like me. Here is the code to save scores without names. :) thanks to Chrisir and Eeyorelife!!

    int[] scores = new int[5];
    int score;
    
    Table table;
    String savegame = "savescore.csv";
    
    
    void setup(){
    
     size(1260, 720);
     for (int i=0; i<scores.length; i++){
      scores[i] = 0;
     }
     table = null;
     table = loadTable(savegame, "header");
     if(table!=null){ 
      for(TableRow row : table.rows()){ 
       int id = row.getInt("id");
       scores[id] = row.getInt("savedata");
      }
     }else{ 
      table = new Table();  
      table.addColumn("id"); 
      table.addColumn("savedata");
      for(int i = 0; i<scores.length; i++){  
       TableRow newRow = table.addRow();     
       newRow.setInt("id", table.lastRowIndex());
       newRow.setInt("savedata", scores[i]);
      }
     }
    
    }
    
    void draw(){
    
     background(0);
     textSize(80);
     fill(255, 0, 0, 255);
     text("Highscores ", 300, 160);
     for (int i=0; i<scores.length; i++) {
      textSize(60);  
      text(scores[i], 570, 300+80*i);
     }
    
    }
    
    void keyPressed(){
    
     score = int(random(100));
     addNewScore(score);
     updateTable();
     saveScores();
    
    }
    
    void addNewScore(int score){
    
     for(int i=0; i<scores.length; i++){
      if(score>=scores[i]){
       for(int j=scores.length-1; j>=max(i,1); j--){
        scores[j] = scores[j-1];
       }
        scores[i] = score;
    
        break;
      }
     }
    
    }
    
    void updateTable(){  
    
     for(TableRow row : table.rows()){  
      int id = row.getInt("id");
      table.setInt(id, "savedata", scores[id]);
     }
    
    }
    
    void saveScores(){
    
     saveTable(table, "data/savescore.csv");
    
    }
    
Sign In or Register to comment.