82 lines
2.1 KiB
Java
Raw Normal View History

package inf112.fiasko.roborally.objects;
import java.util.ArrayList;
2020-03-03 14:13:11 +01:00
import java.util.List;
import java.util.Random;
2020-03-03 04:46:03 +01:00
/**
* This class represents a deck of cards
*/
2020-03-03 14:13:11 +01:00
public abstract class Deck<T> implements IDeck<T> {
private final List<T> cardList;
2020-03-03 04:46:03 +01:00
/**
* Initializes the deck with cards
2020-03-03 14:13:11 +01:00
* @param cardList list of cards
2020-03-03 04:46:03 +01:00
*/
public Deck (List<T> cardList) {
this.cardList = new ArrayList<>(cardList);
}
2020-03-03 14:13:11 +01:00
@Override
public void shuffle() {
Random randomGenerator = new Random();
int deckSize = cardList.size();
int halfDeckSize = deckSize / 2;
int timesToShuffle = 30 * deckSize;
for (int i = 0; i < timesToShuffle; i++) {
int oldPosition = randomGenerator.nextInt(halfDeckSize);
int newPosition = randomGenerator.nextInt(deckSize - halfDeckSize) + halfDeckSize;
cardList.add(newPosition, cardList.remove(oldPosition));
}
}
2020-03-03 04:46:03 +01:00
2020-03-03 14:13:11 +01:00
@Override
public void draw(IDeck<T> other) {
Deck<T> otherDeck = (Deck<T>) other;
cardList.add(otherDeck.cardList.remove(0));
}
2020-03-03 04:46:03 +01:00
2020-03-03 14:13:11 +01:00
@Override
public void draw(IDeck<T> other, int n) {
Deck<T> otherDeck = (Deck<T>) other;
if (n < 1 || n > otherDeck.size()) {
throw new IllegalArgumentException("n can't be below 1 or over the size of the other card deck");
2020-03-03 04:33:58 +01:00
}
for (int i = 0; i < n; i++) {
draw(other);
2020-03-03 04:33:58 +01:00
}
}
2020-03-03 14:13:11 +01:00
@Override
public void emptyInto(IDeck<T> other) {
Deck<T> otherDeck = (Deck<T>) other;
otherDeck.draw(this, this.size());
2020-03-03 04:33:58 +01:00
}
2020-03-03 14:13:11 +01:00
@Override
public boolean isEmpty() {
return cardList.isEmpty();
2020-03-03 04:33:58 +01:00
}
2020-03-03 04:46:03 +01:00
2020-03-03 14:13:11 +01:00
@Override
public int size() {
return cardList.size();
2020-03-03 04:33:58 +01:00
}
2020-03-03 14:13:11 +01:00
@Override
public List<T> getCards() {
return new ArrayList<>(cardList);
2020-03-03 14:13:11 +01:00
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (T card : cardList) {
builder.append(card.toString()).append("\n");
}
return builder.toString();
}
}