1

I am creating a word game where the user can drag letter tiles into placeholders and evaluate it to see if they have made the correct word. I need to scramble the letter tile so that they don't spell out the word.

Currently I am placing the letter tiles in the correct order and then adding a few letters. I then want to scramble the letter tiles. when I place the letters and extra letters I push the x positions into an array.

Is there a way that I can then cycle though the array and position the letter tiles so that they do not overlap each other? Math.floor(Math.random) often produces duplicates so the letter tiles are placed on top of one another as illustrated below.


var arr = [0,30,60,90];

for(i=0;i<arr.length;i++){
 var num = Math.floor(Math.random()*arr.length);
 var bmp = new createjs.Bitmap("image");
 stage.addChild(bmp);

 bmp.x = arr[num];

stage.update();
}

Is there a way to only use each value in the array once but by choosing a random position each time?

Volkan Ulukut
  • 4,230
  • 1
  • 20
  • 38
nontechguy
  • 751
  • 5
  • 21

3 Answers3

0

Consider making a tile letter object.

Within this object keep track of its position. Then add a check for collisions and keep track of all the positions of the objects.

Also consider the shuffle method for the array.

Help Links:

Community
  • 1
  • 1
Josef E.
  • 2,179
  • 4
  • 15
  • 30
0

It sounds like you just want to shuffle the array. If so, this solution might help you.

Community
  • 1
  • 1
cohenadair
  • 2,072
  • 1
  • 22
  • 38
0

One easy way to do this is with a Knuth shuffle on arr:

var arr = [0,30,60,90];

for(var i=0;i<arr.length;i++){
 var num = Math.floor(Math.random()*i);
 var x = arr[i];
 arr[i] = arr[num];
 arr[num] = x;
}

for(var i=0;i<arr.length;i++) {
 var bmp = new createjs.Bitmap("image");
 stage.addChild(bmp);

 bmp.x = arr[i];

 stage.update();
}
Fabricator
  • 12,722
  • 2
  • 27
  • 40