gpt4 book ai didi

javascript - 如何通过状态传递数组项

转载 作者:行者123 更新时间:2023-11-29 20:27:53 25 4
gpt4 key购买 nike

我正在制作纸牌游戏,并希望 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
})
})
}

choseCard 函数将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com