L
L
Lexshpin2020-05-15 18:00:50
JavaScript
Lexshpin, 2020-05-15 18:00:50

Randomizer function for displaying items on the screen. How to implement?

There is an array of objects, where each object is a playing card that is displayed on the screen when a button is pressed. Only one card can be on the screen. Accordingly, when the button is pressed, the previous one is deleted, and the new one is drawn. You need to make sure that the same cards are not displayed until all have been displayed, and then clear the data and display them again.

How to check if a card has been withdrawn? Now I do this:
createNewCard(cards[chooseCard()]);
where createNewCard draws a card and throws a random number from chooseCard into it:

function chooseCard() {
  let cardNum = Math.floor(Math.random() * cards.length);

  return cardNum;
}


There was an idea to push cardNum into an array and check if there is a number in the array, and if it is not, then return it, and if it is, then randomize again:
function chooseCard() {
  let cardNum = Math.floor(Math.random() * cards.length);
let shownCards = [];
  for (key of shownCards) {
    if (key !== cardNum) {
      shownCards.push(cardNum);
    } else {
      cardNum = Math.floor(Math.random() * cards.length);
    }

  return cardNum;
}


I understand that I have a clear flaw in the logic, but I can not figure out how to fix it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-05-15
@Lexshpin

How to check if a card has been withdrawn?

You don't need to check anything. Make a copy of the array, and get the cards from this copy.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question