I am wondering how easy it is for a user/browser to manipulate or execute Javascript code manually.
The reason I ask is that I am planning on making a browser-based game. I am using Javascript instead of Java because I want to make it accessible to as many platforms as possible.
Here is a general example of what I mean: the user might go to a game page. Several variables would be stored in JS such as, say, the player’s health and strength values. The player might choose to attack a monster and the outcome is determined from several stored variables and a couple which were generated during the battle.
So would a player be able to manipulate the stored variables or call one of my JS functions (such as one which leads to an AJAX call being made)?
If so then how could I guard against it? I could verify each action with the server but that is bandwidth-intensive.
Hit F12, open the Console, hack away.
Anything in the global scope is vulnerable to modification.
However, by enclosing your game logic in a closure it becomes a LOT harder to access.
So:
This will prevent access to local variables. Just make sure you declare them all properly with
var.Also, make sure you obfuscate the code to make it harder to modify, and take special care when accepting communications such as highscore submissions. I like to encrypt mine with a made-up-on-the-spot method (such as converting from base 10 to base 42).
As much as possible, send the player’s actions to the server and make sure they are valid. If you can, keep a state of the game on the server side – partly to check if the player is playing by the rules, but also as a side-effect you can resume the game if the user reloads the page.
All in all, you can’t stop cheaters, but you can make it really hard for them.