Interaction Design WikiProgramming

High Scores

The following code example uses a csv file to store high scores. If the doesn't exist already, the code creates a new .csv file to store the date.

High Score
Table table;
String file = "textfile.csv";
void setup() {
  size(200, 200);
  table = loadTable("data/"+file, "header");
  if (table == null) { 
    // if there is no file yet, create a new one
    makeFile();
  } else {
    retrieveDate();
  }
}

void draw() {
}

void saveDate() {
  // save a new score into the csv file  
  TableRow newRow = table.addRow();
  newRow.setString("Name", "Luke_"+floor(random(0, 100)));
  newRow.setString("Score", str(random(100, 300)));
  saveTable(table, "data/"+file);
  println("saved");
}

void retrieveDate() {
  // sort the date in order of best score
  table.sort("Score");
  String HighScore = "";
  for (TableRow row : table.rows()) {
    println(row.getString("Name") + ": " + row.getString("Score"));
    HighScore = row.getString("Name");
  }
  println("highest score is:"+HighScore);
}

void makeFile() {
  table = new Table();
  table.addColumn("Score");
  table.addColumn("Name");
  TableRow newRow = table.addRow();
  newRow.setString("Name", "Luke_"+floor(random(0, 100)));
  newRow.setString("Score", str(random(100, 300)));
  saveTable(table, "data/"+file);
}

void mouseClicked() {
  saveDate();
}