简体   繁体   English

Reactjs - 通过按钮更改随机数组中的项目

[英]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 />
        <button onClick={this.handleClick}>Change the first card</button>
      </div>
    );
  }
}

Here's what you need bigboyopiro. 这就是你需要bigboyopiro。 Its fitting that I get to answer your 2nd question as well :). 它适合我回答你的第二个问题:)。

Here's the sandbox for reference: https://codesandbox.io/s/yv93w19pkz 这是沙箱供参考: https//codesandbox.io/s/yv93w19pkz

  swapOneCard = () => {
    const currentHand = this.state.hand
    //get random card to remove from current hand
    const cardToRemove = currentHand[Math.floor(Math.random() * currentHand.length)];
    //all cards
    const allCards = this.state.cards
    //unchoosen cards to choose from
    const unchoosenCards = allCards.filter((card) => {
      return !currentHand.includes(card)
    })
    //get random card from unchoosen cards
    var cardToAdd = unchoosenCards[Math.floor(Math.random() * unchoosenCards.length)];

    const newHand = currentHand.map((card) => {
      if(card == cardToRemove){
        return cardToAdd
      } else {
        return card
      }
    })

    this.setState({
      hand: newHand
    })
  }

If I'm understanding your question and your code correctly, the button you are going to press replaces the first card in your hand with a new card that isn't already in your hand. 如果我正确理解您的问题和您的代码,您要按的按钮会用您手中尚未拿到的新卡取代手中的第一张卡。 If this is the case, you can use the following to achieve this: 如果是这种情况,您可以使用以下方法来实现此目的:

 getNewCard = () => { let { cards, hand } = this.state; let newCardIndex = Math.floor(Math.random()*cards.length); let newCard = cards[newCardIndex]; while (hand.contains(newCard)) { cards.splice(newCardIndex, 1); newCardIndex = Math.floor(Math.random()*cards.length); newCard = cards[newCardIndex]; } hand[0] = newCard; this.setState({ hand }); } 

The important part is the while loop. 重要的部分是while循环。 It will keep getting a new random card in the array until the random card we get isn't in our hand. 它将继续在阵列中获得一张新的随机卡,直到我们得到的随机卡不在我们手中。 If the random card is in our hand, we remove it from the cards array. 如果随机卡在我们手中,我们将其从卡阵列中删除。 This is to ensure that we don't randomly get the same card again. 这是为了确保我们不会再次随机获得相同的卡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM