我正在尝试创建一组有两种变体的卡片: 一个可以从标准的52副牌中选择并退回一张卡而没有卡重复的卡。 然后是另一张“无限”牌,其中可以重复牌。
public Deck(int a) {
if (a == 0) {
deckOf52();
} else {
infiniteDeck();
}
}
public void deckOf52() {
}
public void infiniteDeck() {
cards = new ArrayList<Card>(52);
for (int a = 0; a <= 3; a++) {
for (int b = 0; b <= 12; b++) {
cards.add(new Card(a, b));
}
}
}
public Card getCard() {
Random generator = new Random();
int index = generator.nextInt(cards.size());
return cards.remove(index);
}
infiniteDeck可以完全按照我的需要做,但是我不确定如何让deckOf52方法做同样的事情并且仅限于52张卡而没有重复。
有没有人有任何想法或任何指示我正确的方向?
答案 0 :(得分:1)
无限牌组中的每张牌都是独一无二的,getCard会删除它使用的每张牌,因此每张牌只会出现一次。
我不确定你要做什么,但这会满足你给我们的描述。
private int deckType;
public Deck(int a) {
this.deckType = a;
createDeck();
}
// create deck of 52 unique cards
public void createDeck() {
cards = new ArrayList<Card>(52);
for (int a = 0; a <= 3; a++) {
for (int b = 0; b <= 12; b++) {
cards.add(new Card(a, b));
}
}
}
// infinite deck never runs out of cards so do not remove card
public Card getCard() {
Random generator = new Random();
int index = generator.nextInt(cards.size());
if(this.deckType == 0){
return cards.remove(index);
} else {
return cards.get(index);
}
}
答案 1 :(得分:0)
这个怎么样?
public void deckOf52() {
// Your definition of card list.
cards = new ArrayList<Card>(52);
Random RNG = new Random();
for (int i = 0; i < 52; ++i) {
// Pick a card from 0 to position (52 - i).
int cardPicked = RNG.nextInt() % (52 - i);
// In your list swap cards at position 52 - i and cardPicked.
swapCards(cards, cardPicked, 52 - i);
}
// You'll have a shuffled deck of cards after this loop.
}
答案 2 :(得分:0)
您可以在开头随机播放收藏品,以随机选择可用的卡片:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Deck {
ArrayList<Card> cards = new ArrayList<Card>(52);
private final Random generator = new Random();
private int previous;
boolean infiniteDeck = false;
public static void main(String args[])
{
Deck infinite_deck = new Deck(true);
Deck limited_deck = new Deck(false);
System.out.println("Pulling cards from infinite deck:");
for(int i=0; i<100; i++)
{
System.out.println("InfiniteDeck " + i + ":\r\n Pulling card :\r\n"+infinite_deck.getCard());
}
System.out.println("Pulling cards from finite/limited deck:");
for(int i=0; i<100; i++)
{
System.out.println("FiniteDeck " + i + ":\r\n Pulling card :\r\n"+limited_deck.getCard());
}
}
public Deck(boolean infiniteDeck) {
this.infiniteDeck = infiniteDeck;
cards = new ArrayList<Card>(52);
for (int a = 0; a <= 3; a++) {
for (int b = 0; b <= 12; b++) {
cards.add(new Card(a, b));
}
}
if(!infiniteDeck)//Shuffle the deck randomly
Collections.shuffle(cards, new Random(100));
}
public Card getCard() {
if(infiniteDeck)
{
return cards.get(generator.nextInt(52));
}
else
{
if(cards.size() > 0)
return cards.remove(cards.size()-1);
else
return null;
}
}
class Card
{
int type, number;
public Card(int a, int b)
{
type = a;
number = b;
}
public String toString()
{
return "CARD{\r\n\ttype:" + type + ",\r\n\tnumber:" + number+"\r\n}";
}
}
}