-1

I want to do a button to shuffle the cards but it doesn't work how would you do it? I tried to shuffle the array but I need to shuffle the colors somehow (I need to stay with the same colors I created but in different order on the screen )

this is my code

const shuffle = deck => { /* code here */ }
document.addEventListener('DOMContentLoaded', () => {
  function generateRandomColor() {
    const hexValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
    let randomNum = "";
    for (let i = 0; i < 6; i++) {
      randomNum += hexValues[Math.floor(Math.random() * 16)];
    }
    return `#${randomNum}`
  }

  var grid = document.querySelector(".grid");

  for (var i = 0; i < 50; ++i) {
    grid.innerHTML += '<div class="card"></div>';
  }

  function generateArrayOfColors() {
    var colors = [];
    for (var i = 0; i < 25; i++) {
      colors.push(generateRandomColor());
    }
    return colors;
  }

  var colorArray = generateArrayOfColors();
  var cards = document.querySelectorAll(".card");



  for (var i = 0; i < cards.length; ++i) {
    cards[i].style.backgroundColor = colorArray[i % colorArray.length];
  }


  console.log(shuffle(cards))
  const shuffleButton = document.querySelector(".shuffleButton");
  shuffleButton.onclick = shuffle(cards);

});
<div class="grid"></div>
<button class="shuffleButton">Shuffle</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Welcome to Stack Overflow! In what way is your code not working as expected? Please elaborate on the specific problem you are observing and what debugging you have done. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Mar 22 '23 at 14:31
  • maybe with this function too as shuffle function card.sort(() => Math.random() - 0.5) – ארי פיין Mar 22 '23 at 14:32
  • As a general observation... It's not clear to me from the code shown how you're modeling your data. *If it were me*, I'd create a "card" object with the properties that semantically define a card in the game, initialize a list of the known cards in a deck, and simply shuffle that array. Specifically for this question... Are you just asking how to randomize/shuffle an array in JavaScript? – David Mar 22 '23 at 14:32
  • Hi I added my code I want to shuffle the divs such as : lets say in cards[1] there was a purple color now in cards [1] will be other color from the function "generateArrayOfColors" – ארי פיין Mar 22 '23 at 14:40
  • 1
    I made you a snippet. Please add HTML and CSS to make a [mcve]. There are thousand of shuffle examples on the web – mplungjan Mar 22 '23 at 14:43
  • 1
    @אריפיין: Does this answer your question? [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/q/2450954/328193) – David Mar 22 '23 at 14:47

1 Answers1

0

It seems to me that we need to shuffle colors in your case, but not cards itself. In that case let me try to suggest you something like that:

const generateArrayOfColors = () => {
        return ["black", "red", "green", "yellow", "blue", "orange"];
      };

      const colorArray = generateArrayOfColors();
      const cards = document.querySelectorAll(".card");

      const applyColorsToCards = () => {
        cards.forEach((card, i) => {
          card.style.backgroundColor = colorArray[i % colorArray.length];
        });
      };

      applyColorsToCards();

      const shuffle = (array) => {
        let currentIndex = array.length;
        let randomIndex;

        while (currentIndex !== 0) {
          randomIndex = Math.floor(Math.random() * currentIndex);
          currentIndex--;

          [array[currentIndex], array[randomIndex]] = [
            array[randomIndex],
            array[currentIndex]
          ];
        }

        return array;
      };

      const shuffleButton = document.querySelector(".shuffleButton");
      shuffleButton.onclick = () => {
        shuffle(colorArray);
        applyColorsToCards();
      };
.card {
        display: inline-block;
        width: 100px;
        height: 100px;
        margin: 10px;
        border: 1px solid #ccc;
      }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Card Shuffle</title>
  </head>
  <body>
    <div class="cards-container">
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
      <div class="card"></div>
    </div>
    <button class="shuffleButton">Shuffle Colors</button>

  </body>
</html>

I also fixed the way of using onclick in your code. It shouldn't receive a result of a function, but a function that will be triggered after click.

piskunovim
  • 392
  • 2
  • 6