1

I have 6 squares and I want to assign them 6 already defined colors, but randomly. So there should be 1 color for 1 square, and every time I click "play again" they should just mix randomly. So far I've managed to make all the squares to use one of the six colors, but as they choose them only randomly it happens pretty often that I have for example 3 gray colors, but 0 red. I am not sure how to explain this better, so if you have any questions I'll gladly answer them.

HTML:

<div id="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>

JS:

var squares = $(".square");
var colors = {
    'yellow': 'rgb(255, 255, 0)',    
    'orange': 'rgb(255, 153, 0)',
    'green': 'rgb(0, 255, 0)',
    'blue': 'rgb(0, 0, 255)',
    'gray': 'rgb(128, 128, 128)',
    'purple': 'rgb(153, 0, 255)'
};

for(var i=0; i < squares.length; i++) {
    squares[i].style.backgroundColor = randomColors();
    squares[i].style.display = "block";
}

function randomColors(ranCol) { 
    var ranCol = Object.keys(colors)[Math.floor(Math.random()*Object.keys(colors).length)];
    return ranCol;
}
Vadi
  • 3,279
  • 2
  • 13
  • 30
domagoj101
  • 25
  • 4
  • 1
    [Shuffle](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) your color array and then just assign in order? – El_Vanja Mar 08 '20 at 16:14
  • you should weight the probabilities, so that the numbers which have the less been drought have more probability to be draught – grodzi Mar 08 '20 at 16:15
  • Or remove the picked color with `delete` – Andreas Mar 08 '20 at 16:16

1 Answers1

1

You could shuffle an array of the colors, then assign them from the shuffled result:

var array = Object.keys(colors);
shuffleArray(array);
for(var i=0; i < squares.length; i++){
    squares[i].style.backgroundColor = colors[array[i]];
    squares[i].style.display = "block";
}

If you don't want to go that route, you can put them in an array and pick colors from it at random, removing the color you pick each time:

var array = Object.keys(colors);
for(var i=0; i < squares.length; i++){
    var index = Math.floor(Math.random() * array.length);
    var color = array[index];
    array.splice(index, 1); // Remove that entry
    squares[i].style.backgroundColor = colors[color];
    squares[i].style.display = "block";
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875