shuffle as Pile method

master
Saša Kocić 6 years ago
parent c266d4edef
commit eeb29d96dc

@ -1,6 +1,4 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class CardGame {
public Player[] players;
@ -13,7 +11,7 @@ public class CardGame {
*/
public CardGame(int numberOfCards, int numberOfPlayers) {
Pile deck = createDeck(numberOfCards);
shuffleArray(deck);
deck.shuffle();
this.players = new Player[numberOfPlayers];
draws = new Card[numberOfPlayers];
int cardsPerPlayer = deck.size() / numberOfPlayers;
@ -78,17 +76,4 @@ public class CardGame {
}
return true;
}
/**
* Fisher-Yates shuffle()
* https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array
*/
private static void shuffleArray(Pile pile)
{
Random random = new Random();
for (int i = pile.size() - 1; i > 0; i--)
{
Collections.swap(pile, i, random.nextInt(i + 1));
}
}
}

@ -1,4 +1,6 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Pile extends ArrayList<Card> {
public void addAll(Card[] cards) {
@ -14,4 +16,17 @@ public class Pile extends ArrayList<Card> {
}
return cardsForPlayer;
}
/**
* Fisher-Yates shuffle()
* https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array
*/
public void shuffle()
{
Random random = new Random();
for (int i = this.size() - 1; i > 0; i--)
{
Collections.swap(this, i, random.nextInt(i + 1));
}
}
}

@ -26,7 +26,7 @@ public class Player {
if (getDiscardPile().isEmpty()) {
throw new NoMoreCardsException();
}
shuffle(discardPile, new Random());
discardPile.shuffle();
drawPile.addAll(discardPile);
discardPile.clear();
}

Loading…
Cancel
Save