One of the thing I\u2019ve had to do commonly over the years in making games is to be able to generate a random string. Now lot of times I do this on the server side of code to be able to generate a none, one time use code. But there are times where I have had to do it on the client side maybe to generate a password would be a common use of this, or it could be having to guess what the random letters are in a mastermind type of game. It’s a very simple thing to do.
\nAll we need to do is to define a set of letters or symbols characters for the program to pick from. We decide on a word length and then loop through that many times pick a random index from the length of the set and then concat a string with that.<\/p>\n
Here’s the outline of the code.<\/p>\n
Here is the full code<\/p>\n
var StateMain = {\r\n preload: function() {\r\n game.load.image(\"button\", \"images\/btnGenerate.png\");\r\n },\r\n create: function() {\r\n console.log(\"Ready!\");\r\n var btnGet = game.add.sprite(game.world.centerX, game.world.centerY, \"button\");\r\n this.text1 = game.add.text(game.world.centerX, game.height \/ 3, \"\");\r\n this.text1.fill = \"#ffffff\";\r\n btnGet.anchor.set(0.5, 0.5);\r\n this.text1.anchor.set(0.5, 0.5);\r\n btnGet.inputEnabled = true;\r\n btnGet.events.onInputDown.add(this.getWord, this);\r\n },\r\n getWord: function() {\r\n var word = this.makeRandomString();\r\n this.text1.text = word;\r\n },\r\n makeRandomString: function() {\r\n var letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*#%&!\";\r\n var word = \"\";\r\n \r\n var wordLen = 10;\r\n for (var i = 0; i < wordLen; i++) {\r\n var index = Math.floor(Math.random() * letters.length);\r\n word += letters.charAt(index);\r\n }\r\n return word;\r\n },\r\n update: function() {}\r\n}<\/pre>\n<\/p>\n
And Here is the result<\/p>\n