This code will prevent memory editors from easily being able to scan for a protected value in your game
public class ProtectedInteger {
private int value;
private int key;
private static Random RND = new Random();
public ProtectedInteger(int x) {
set(x);
}
public int get() {
return (~value) ^ key;
}
public void set(int value) {
key = RND.nextInt();
this.value = (~value) ^ key;
}
public void increment() {
set(get() + 1);
}
public void decrement() {
set(get() - 1);
}
public void add(int x) {
set(get() + x);
}
public void dec(int x) {
set(get() - x);
}
}
version without java.util.Random:
public final static class ProtectedInteger {
private int value;
private int key;
private static long x = System.currentTimeMillis();
private static int rnd() {
x ^= (x << 21);
x ^= (x >>> 35);
x ^= (x << 4);
int a = (int)x;
int b = (int)(x << 16);
return a^b;
}
public ProtectedInteger(int x) {
set(x);
}
public int get() {
return (~value) ^ key;
}
public void set(int value) {
key = rnd();
this.value = (~value) ^ key;
}
public void increment() {
set(get() + 1);
}
public void decrement() {
set(get() - 1);
}
public void add(int x) {
set(get() + x);
}
public void dec(int x) {
set(get() - x);
}
}
I know its not foolproof, anyone who knows Java ASM would be able to hack through, or patching the default constructor of Random() or something, but its enough to deter noob cheaters.