dimanche 19 mai 2019

Reactjs - Changing an item in randomized array via button

It's me again with the same card game as my last question. I have been doing some progress but this time i want to fix the code so that one card in the randomized "hand", is switched with another random card that must not be an already used card. This is done by pressing the second button under randomizer button. In the code i have made the changing button does the same as the randomization button, but i intend to change it.

function replace() {
  var res = str.replace(this.state.cards, this.state.replacecards);
}
     // what i intend to be the function that is used to replace the item

     class App extends React.Component {
  constructor(props) {
      super(props);
      this.state = { 
        cards: ["A♥", "A♠", "A♦", "A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "K♣", "Q♣", "J♣", "2♦", "3♦", "4♦", "5♦", "6♦", "7♦", "8♦", "9♦", "10♦", "K♦", "Q♦", "J♦", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥", "10♥", "K♥", "Q♥", "J♥", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "K♠", "Q♠", "J♠"],
        hand: [] 
      }

       this.handleClick = this.handleClick.bind(this)

  }

  handleClick() {
    const cards = this.state.cards

    const newHand = []


    function in_array(array, el) {
    for (var i = 0; i < array.length; i++)
        if (array[i] == el) return true;
    return false;
}

    function get_rand(array) {
      var rand = array[Math.floor(Math.random() * array.length)];

      if (!in_array(newHand, rand)) {
        newHand.push(rand);
        return rand;
    }
    }
    function sortcards(a, b) {
     return a > b ? 1 : b > a ? -1 : 0;
    }


    for (var i = 0; i < 5; i++) {
       get_rand(cards);

    }

    this.setState({
      hand: newHand
    })
    newHand.sort(sortcards);


  }

  render() {
    const { hand } = this.state
      return (
        <div>
          { hand ? (hand.map((card) => {
            return <p>{card}</p>
           })) : (
            null
          )}
          <button onClick={this.handleClick}>Randomize
          </button>
          <br></br>
          <button onClick={this.handleClick}>Change the first card
          </button>
        </div>
      );
  }
}




Aucun commentaire:

Enregistrer un commentaire