我已经可以输出卡片值,并且我在资产中有52张卡片图像。如何将每个卡片值组合到其对应的图像中?
例如,如果我从牌组中随机输出一张牌,它将向它显示相应的图像。
下面是卡片卡片组的类:
export default class cardDeck extends React.Component{
constructor(){
super();
this.deck = [];
this.reset();
this.shuffle();
}
reset(){
this.deck = [];
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.deck.push(`${values[value]} of ${suits[suit]}`);
}
}
}
shuffle(){
const { deck } = this;
let m = deck.length, i;
while(m){
i = Math.floor(Math.random() * m--);
[deck[m], deck[i]] = [deck[i], deck[m]];
}
return this;
}
}在游戏类中,我只需调用shuffle函数,然后随机呈现数组中的一张牌,在那里,我希望它向牌显示对应的图像,而不仅仅是文本。
发布于 2020-05-06 01:40:07
好的,您可以采用的一种方法是将卡片图像命名为aceofhearts.jpg, 2ofhearts.jpg, 3ofspades.jpg等
然后,在代码中,您可以在显示图像的任何位置执行以下操作
//remove spaces - could do this in a loop to get all the cards
let card = deck[0].split(' ').join('')
//make sure to set this to your image path
let imagePath = `../assets/images/${card}.jpg`
//JSX
<Image source={require(imagePath)} />https://stackoverflow.com/questions/61617123
复制相似问题