Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 game - how to protect against modification of variables

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?

like image 298
Sekhmet Avatar asked Oct 28 '12 10:10

Sekhmet


4 Answers

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.

like image 99
Philipp Avatar answered Sep 21 '22 22:09

Philipp


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.

like image 24
ComFreek Avatar answered Sep 19 '22 22:09

ComFreek


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.

like image 40
Guffa Avatar answered Sep 21 '22 22:09

Guffa


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.

like image 25
Lauri Avatar answered Sep 20 '22 22:09

Lauri