TransWikia.com

Using a Shuffle Function for a Simple Truth or Dare Bot in Discord

Stack Overflow Asked by user14702079 on February 12, 2021

Like the title says, I’m using JavaScript to build a Discord bot that just handles picking players in a Truth or Dare game. The bot itself functions fine, but it fails to shuffle the players again at the end of a round.

This is my shuffle function

function shuffle(array) {
    var currentIndex = ping.length -1, temporaryValue, randomIndex
  
    array[0]=0
    while (0 !== currentIndex) {
      array[currentIndex] = currentIndex;
      currentIndex -= 1;
    }

    while (0 !== currentIndex) {  
      
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
       
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
  
    return array;
      console.log(xrandomindex)
  }

  function shuffleassign(array) {
    var currentIndex = array.length -1, temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = xrandomindex[currentIndex];
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
   array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
}
return array;
}

And here it is in play

else if(message.content.startsWith(`${prefix}n`))    
        if (count > 1)
            {if (countgame == count -1 ) {
              message.channel.send("The queue is being shuffled.")
              shuffle(xrandomindex)
              shuffleassign(ping)
              shuffleassign(users)
              countgame = 0 } 
          message.channel.send ((ping)[countgame] + " is currently asking " + (ping)[countgame + 1] )
          countgame = countgame +1
          msg = count - countgame 
        }
     else message.channel.send("Too few players to start the game.")

One Answer

You can shuffle items on the array using this function. You can utilize any value. Have not tested if the players need to have a unique identifier.

function shuffle(array) {
  let currentIndex = array.length, temporaryValue, randomIndex;

  // Continue to shuffle while there are items on the index
  while (0 !== currentIndex) {

    // Pick one of the remaining elements
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // Swap it with the current element
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

// Used like so
const arr = ['bob', 'billy', 'tom', 'susan'];
shuffle(arr);
console.log(arr);

Answered by Ori Alvarez on February 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP