I wrote HTML5 game based in canvas and I have a problem.
I use var like that:
var score = 0;
// another code
++score;
But user can edit that var (eg. in FireBug, or Chrome editor) - score hacked.
Any ideas?
Javascript is a executed client-sided. Anything which happens on the client can be controlled by it. There is no way around it. You can try to obfuscate your code, but that only makes it a bit harder to find out how to cheat. It can't stop someone who is determined enough.
The only way to design a game which is cheat-proof is to do all the game mechanics on the server. This is of course technically a lot more challenging, impairs the game experience when the user got a bad connection and costs you additional resources because you need much more server capacity, but it's the only way.
By the way: we got a sister site http://gamedev.stackexchange.com which is especially for questions about game development. You might get some better answers there.
You can't actually protect ANY code which runs on the client side!
Therefore, you can't protect the contents of your variables. You can only make it more difficult to hack - like Guffa said.
You can put the score variable as a local variable inside a class constructor, that way it's harder to get to:
function MyClass() {
var score = 0;
this.somethingHappened = function() {
if (someondition) {
score++;
}
}
this.getScore = function() {
return score;
}
}
It's of course still possible to hack the code, but it's not at all as simple as changing a global variable.
There isn't anything you can do to avoid this. You can make it harder by obfuscating code, but its still possible to hack the score.
One way to also make it harder is to double save the score and in loop or some function just check if it has changed outside of the game logic, this way the user needs to find both of the variables.
And if the second score value is double of another score value, its even more harder to find by comparing the current score to all variables scores.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With