Name in an Highscore

Hi, I’m new to this forum, but I had to create a game using Processing and now I’m trying to add an Highscore, in which I’d like to put both name and score. I managed to add the score and I used ControlP5 to write the name, but I don’t really know how to pair name and score and how to create a sort of ‘name score’.
I thought that maybe I could create a Class with the name and the score so as to pair them…but I’m not sure…Thank you !!

Here is my code: (I didn’t share HighScore.txt and ScoreNames but you can create them yourself :).
If you can’t read it please tell me

int[] Record = new int[5];
int score, lines;
String [] RecordPoints, RecordNames; 
import controlP5.*; 
ControlP5 control;
Button Submit;
Textfield NameText;
String name;
int temp=0;
void setup() {
  size(600, 600);
  textSize(30);
  control= new ControlP5(this);
  RecordNames=loadStrings("ScoreNames.txt");
  RecordPoints=loadStrings("HighScore.txt");
  Record=int(RecordPoints);
  NameText=control.addTextfield("Name").setPosition(350, 460).setSize(100, 30).setAutoClear(false);//TextField classe di control credo, Name nome, setAutoClear per essere sicuri non si cancelli da solo
  Submit=control.addButton("Submit").setPosition(350, 500).setSize(100, 25); //bottone da cliccare 
  NameText.setColorForeground(color(#ABACB4)).setColorBackground(color(#71727E));
  Submit.setColorForeground(color(#ABACB4)).setColorActive(color(#AFB0D3)).setColorBackground(color(#71727E));
}

void draw() {
  background(0);
  for (lines=0; lines<RecordNames.length; lines++)
    text(RecordNames[lines], 250, 120+60*lines);
  for (int i=0; i<Record.length; i++) {
    text(Record[i], 50, 120+60*i);
  }
  if (Submit.isPressed()) {
    name=NameText.getText();
    temp=1;
  }
  if (temp==1)
    text(name, 500, 200);

  text(score, 180, 120);
}


void addNewScore(int score) {
  for (int i=0; i<Record.length; i++) {
    if (score>=Record[i]) {
      for (int j=Record.length-1; j>i; j--) {
        Record[j] = Record[j-1];
      }
      Record[i] = score;
      break;
    }
  }
}

void keyPressed() {
  score = int(random(1000));
  addNewScore(score);
  if (key==CODED) {
    if (keyCode==UP) {
      RecordPoints= str(Record);
      saveStrings(dataPath("HighScore.txt"), RecordPoints);
      saveStrings(dataPath("Scorenames.txt"), RecordPoints);
    }
  }
}

1 Like

Can you please use the “format this like code” button so we can read your code.

1 Like

If you need a class for mixed data types (like numbers and strings) that you plan to save to / load from a text file, use Table and TableRow.

https://processing.org/reference/Table.html
https://processing.org/reference/TableRow.html

Then you can loadStable and saveTable rather than using saveStrings.

table = new Table();
  
table.addColumn("name", Table.STRING);
table.addColumn("score", Table.INT);
  
// ...

TableRow row = table.addRow();
row.setString("name", name);
row.setInt("score", score);

// ...

saveTable(table, "scores.csv");