我正在尝试创建一副有两种变体的牌:一种可以从标准的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张牌,不重复。
有人有什么想法或什么东西可以为我指明正确的方向吗?
无限牌组中的每张牌都是唯一的,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);
}
}
这个怎么样?
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.
}
您可以在开始时洗牌,以便随机选择可用的卡:
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 + ":rn Pulling card :rn"+infinite_deck.getCard());
}
System.out.println("Pulling cards from finite/limited deck:");
for(int i=0; i<100; i++)
{
System.out.println("FiniteDeck " + i + ":rn Pulling card :rn"+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{rnttype:" + type + ",rntnumber:" + number+"rn}";
}
}
}