I have used this html5 Snake game on my website , but problem is that it can be hacked so easily .
http://cssdeck.com/labs/classic-snake-game-with-html5-canvas
Hackers can inject scores and submit their own scores.
Is there anyway to protect score variable inside the script not to be injected by clients ?
Not as long as the game is implemented entirely on the client side. The "solution" is to implement the game rules and storage on the server side, and have the client be mostly UI, but this might be overkill for such a simple browser game.
You could make it harder by obfuscating the code, but that would only stop people who don't actually care.
If the game is deterministic you could keep a log of all game "events" and send that to the server, where the score would be calculated. This would make it more work to fake a score, but it would still be possible to fake, and it would also be a lot of work to build such a system.
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