Save variable in a loop


#1

Hello,
I am a beginner in programming.
I created a simple program that shows my problem :

int A=0;

void setup () {
  size(400,400);
}

void draw () {
  background(0);
  if(mousePressed) {
    A=A+1;
  }
  text(A,200,200);
}

I would like that when I close the program, the variable A does not start from 0 but from before the closing of the program.

Thank you.


#2
  1. Processing.org/reference/loadStrings_.html
  2. Processing.org/reference/saveStrings_.html

#3

Hello,

Thank you for your answer but I don’t understand how it works and the Google translation does not help me. Is there a simpler example ?

Thank you.


#4
/**
 * Load & Save Variable (v1.0.1)
 * GoToLoop (2018/Oct/20)
 * https://Discourse.Processing.org/t/save-variable-in-a-loop/4654/4
 */

int a;

void setup() {
  size(300, 200);
  noLoop();

  fill(-1);
  textAlign(CENTER, CENTER);
  textSize(0100);

  final String[] aFile = loadStrings("a.txt");
  if (aFile != null)  a = int(aFile[0]);
}

void draw() {
  background((color) random(#000000));
  text(a, width>>1, height>>1);
}

void mousePressed() {
  ++a;
  redraw = true;
}

@Override void exit() {
  saveStrings(dataPath("a.txt"), new String[] { str(a) });
  super.exit();
}

I need help making save states for an rpg
SaveString() overwrite text in .txt file
How to save Level Progress?
#5

Thank you :slight_smile:


#6

Hello,

Thank you for your example.
I still have a question : can we encrypt the data so that the user can not change them ?

Thank you.


#7

If you save it as a .txt file, even though you could encrypt it, the User Would still be able to change it, just not make much sense out of it. I assume that you wanted to encrypt it just to make it unchangable, But if not, there should be some encryption methods available. Easiest Would probably be to search online for Java Encryption methods, or to just add +1 in each Char of the String of your file, which Would also work, But be a very Weak encryption. But if it’s only to avoid fast changes to the file, then that could also Suffice.


#8

Thank you so much :wink: