简体   繁体   中英

How do I get a certain number of objects from one arrayList in one class to an arraylist in another class?

I'm trying to make a card game and it has classes of Game, Card, Player, Deck and hand. I want it to simulate real life where you draw 5 cards from a deck to your hand

I have my class Player adding all the cards to an Deck array called cards. Like this:

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

which passes it to my class Deck:

public class Deck {
    private List<Card> cards;

    public Deck() {
        this.cards = new ArrayList<>(); 
    }

    public void addCard(Card card) {
        this.cards.add(card);           
    }

I created a hand arraylist in class Hand called hand:

public class Hand {
       Deck deck;

       private List<Card> hand;

       public Hand() {
            this.hand = new ArrayList<>();
        }

How do I add 5 random card objects from my deck arraylist to my hand arrayList?

First you need to make Deck smart enough to withdraw cards randomly and with demanded amount. Deck code should be like this:

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;
    }
}

In the second step make Hand access to Deck, for this task Deck should be inside of the Hand class like this:

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;
       }

}

In real life player knows how many cards he should get from deck according to game rules, so we pass amount of cards to Hand constructor. When hand is empty we should get cards from deck, when hand is full simple return presented cards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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