0

I am a very beginner in Javascript / Jquery and my task is to make a "guess the word game"

I have no idea how to mix letters in a word and then how to put one letter of a word per button.

I have an array of words which length is 6 letters. When user clicks "start" button a random word of the whole array is being taken. This is the code of it :

var words = ["abacus", ".....", "zygote"]
$( "#start" ).on('click', function() {
var rand = Math.floor( Math.random() * words.length );
alert(words[rand]);
});

This is what I've got so far. Alert is just to check if the code is right. So the actual task for me is to mix characters in the word I've got and then spread it for 6 buttons.

I am not asking for a code, just for possible solutions but anything would be appreciated Thanks in advance,

2 Answers2

0

Shuffle the letters is described in this post: How do I shuffle the characters in a string in JavaScript?

Then iterate through all the shuffled letters with a for loop and create a button for each letter.

I have created an example for you at http://jsfiddle.net/Mz39e/

var word = "myword";
var shuffledWord = word.shuffle();

for (var i = 0; i < shuffledWord.length; i++ ) {

  createButton(shuffledWord[i]);

}


function createButton(letter) {

    $("body").append($("<button/>").html(letter).on("click", function() {

         // Here your button handling code
         alert($(this).html());

    }))    

}
Community
  • 1
  • 1
Bas van Dijk
  • 9,933
  • 10
  • 55
  • 91
0

You can look into the String.prototype.split() function, which you can use to explode that word into an array of 6 letters, and then you can look into the Array.prototype.sort() function, which you can use a random operation inside of to randomize those letters, and then you can just iterate over the array of randomized letters to assign each letter to a different button. Something like this:

var scrambledWord = words[rand].split('').sort(function () {
    var random = Math.random() * 2;
    if (random < 1) {
        return 1;
    } else if (random > 1) {
        return -1;
    } else {
        return 0;
    }
});

To assign each letter to a different button, you can use a library like jQuery to just create a new button as you loop over the array items, and inject them into a container.