mourning-ember / src / main / java / dev / llan / model / cards / Deck.java
Deck.java
Raw
package dev.llan.model.cards;

import java.util.ArrayList;
import java.util.List;

import static dev.llan.model.cards.Constants.MAX_HAND_CARDS;

public class Deck {
  private Card[] deck;

  private List<Card> notInHand;

  public Deck(Card[] deck) {
    this.deck = deck;
    notInHand = new ArrayList<>(List.of(deck));
  }

  public IndexedCard selectOne() {
    double selected = Math.random() * sumWeight();
    int index = -1;
    do {
      index++;
      selected -= notInHand.get(index).getWeight();
    } while (selected > 0);

    return new IndexedCard(notInHand.remove(index), index);
  }

  public IndexedCard[] selectHand() {
    IndexedCard[] hand = new IndexedCard[MAX_HAND_CARDS];
    for(int i = 0; i < MAX_HAND_CARDS; i++) {
      hand[i] = selectOne();
    }
    return hand;
  }

  public void addUnusedCard(Card card) {
    notInHand.add(card);
  }

  private double sumWeight() {
    double sum = 0;
    for(Card card : notInHand) {
      sum += card.getWeight();
    }
    return sum;
  }
}