One of the thing I’ve 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.
All 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.
Here’s the outline of the code.
- make a random string of letters
var letters = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*#%&!”; - we set up a variable called word set to blank
var word = “”; - Pick a random place in the string
var index = Math.floor(Math.random() * letters.length); - Concat the character at the place in the letters string to a string called word
word += letters.charAt(index); - Do that for the number of times that we want the word length to be
var wordLen = 10;
for (var i = 0; i < wordLen; i++) {} - Return that value
Return word
Here is the full code
var StateMain = { preload: function() { game.load.image("button", "images/btnGenerate.png"); }, create: function() { console.log("Ready!"); var btnGet = game.add.sprite(game.world.centerX, game.world.centerY, "button"); this.text1 = game.add.text(game.world.centerX, game.height / 3, ""); this.text1.fill = "#ffffff"; btnGet.anchor.set(0.5, 0.5); this.text1.anchor.set(0.5, 0.5); btnGet.inputEnabled = true; btnGet.events.onInputDown.add(this.getWord, this); }, getWord: function() { var word = this.makeRandomString(); this.text1.text = word; }, makeRandomString: function() { var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*#%&!"; var word = ""; var wordLen = 10; for (var i = 0; i < wordLen; i++) { var index = Math.floor(Math.random() * letters.length); word += letters.charAt(index); } return word; }, update: function() {} }
And Here is the result