[英]How do I get a certain number of objects from one arrayList in one class to an arraylist in another class?
我正在尝试制作纸牌游戏,它具有游戏,纸牌,玩家,牌组和手牌类。 我要它模拟现实生活,从甲板上到手抓5张牌
我有班级播放器,将所有卡添加到称为卡的Deck阵列中。 像这样:
public Player(String name) {
this.name = name;
this.deck = new Deck();
this.deck.addCard(new Card("c1",20, "fire"));
this.deck.addCard(new Card("c2",30, "fire"));
this.deck.addCard(new Card("c3",10,"water")); //etc list goes on
并将其传递给我的班级Deck:
public class Deck {
private List<Card> cards;
public Deck() {
this.cards = new ArrayList<>();
}
public void addCard(Card card) {
this.cards.add(card);
}
我在Hand类中创建了一个手数组列表,称为hand:
public class Hand {
Deck deck;
private List<Card> hand;
public Hand() {
this.hand = new ArrayList<>();
}
如何将我的牌组arraylist中的5个随机纸牌对象添加到我的手arrayList中?
首先,您需要使Deck足够智能以随机抽取所需数量的卡。 甲板代码应如下所示:
public class Deck {
private List<Card> cards;
public Deck() {
this.cards = new ArrayList<>();
}
public void addCard(Card card) {
this.cards.add(card);
}
public List<Card> getCards(final int amount) {
ArrayList<Card> result = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < amount; i++) {
int randomIndex = random.nextInt(cards.size());
result.add(cards.remove(randomIndex));
}
return result;
}
}
在第二步中,使Hand进入Deck,为此任务Deck应该位于Hand类中,如下所示:
public class Hand {
private final Deck deck;
private final int cardsAmount;
private List<Card> cardsInHand;
public Hand(Deck deck, int cardsAmount) {
this.deck = deck;
this.cardsAmount = cardsAmount;
}
public List<Card> cards() {
if(cardsInHand == null) cardsInHand = deck.getCards(cardsAmount);
return cards;
}
}
在现实生活中,玩家根据游戏规则知道应该从套牌中获得多少张牌,因此我们将数量的牌传递给Hand构造器。 当手空时,我们应该从卡组中拿出卡,当手满时,简单地归还所提供的卡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.