我正在制作纸牌游戏,并希望 playCard 在数组中包含先前的纸牌和附加的纸牌。目前,当我尝试使用玩家手上的 pop 或 splice 时,它会从玩家手数组中取出这些卡并将它们放入 playCard 数组中,但是当player2 尝试添加到 playCard 数组时,它会覆盖它并且里面只有player2 卡。这就是我创建卡片并发牌的方式:
this.state = {
deck: [],
player1: [],
player2: [],
player3: [],
player4: [],
playCard: [],
}
this.makeCards();
this.shuffle();
}
makeCards = () => {
const suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds']
const values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
for (let suit in suits){
for (let value in values) {
this.state.deck.push(<span className='cards' key={value+suit}>{values[value]}</span>);
}
}
return this.deck
}
deal = () => {
this.setState({ player1: this.state.deck.filter((cards, index) => {
return index < 13 ? cards : null
})
})
this.setState({ player2: this.state.deck.filter((cards, index) => {
return index >= 13 && index < 26 ? cards : null
})
})
this.setState({ player3: this.state.deck.filter((cards, index) => {
return index >= 26 && index < 39 ? cards : null
})
})
this.setState({ player4: this.state.deck.filter((cards, index) => {
return index >= 39 && index <= 52 ? cards : null
})
})
}
chooseCard函数将player1数组中的第一张牌放入playCard,但是当player2turn发生时,它会更改为player2数组中的一张牌。
choseCard(){
this.setState(() => ({playCard: this.state.player1.splice(0,1)}))
}
player2turn() {
this.setState(() => ({playCard: this.state.player2.splice(0,1)}))
//I need to filter player2 array to find card value in playCard
//if it has that then push to this.state.playCard
//Player 3 sorts through array to find card etc....
}
我知道现在没有发生任何过滤,我只想将player2添加到playCard数组中。我该如何做到这一点,同时仍然从玩家阵列中取出卡牌?
最佳答案
this.setState(({ playCard, player2 }) => {
return {
playCard: [...playCard, ...player2.slice(0, 1)],
player2: [...player2.slice(1, player2.length - 1)],
};
});
将先前的状态与新的状态结合起来,并且不要改变它。如果您还需要更改player2,只需根据上一个状态创建一个新数组,而不需要第一张卡。
关于javascript - 如何通过状态传递数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58884409/