用Java制作多副卡片
编辑:我尝试将卡添加到我的原始外观和DealDeck时出错 我想我已经知道了如何创建一副牌[如方法Decks()中所示],但我的问题是我必须创建多副牌[n副牌数量=n*52张牌数量]。我不知道如何利用n来制作同一张卡的倍数。在创建了多个牌组之后,我想我可以计算出shuffle()和reset(),但是现在获得多个牌组给我带来了问题 注意:我正在考虑创建一个n组的数组,但我甚至不知道如何开始 卡类用Java制作多副卡片,java,arraylist,poker,Java,Arraylist,Poker,编辑:我尝试将卡添加到我的原始外观和DealDeck时出错 我想我已经知道了如何创建一副牌[如方法Decks()中所示],但我的问题是我必须创建多副牌[n副牌数量=n*52张牌数量]。我不知道如何利用n来制作同一张卡的倍数。在创建了多个牌组之后,我想我可以计算出shuffle()和reset(),但是现在获得多个牌组给我带来了问题 注意:我正在考虑创建一个n组的数组,但我甚至不知道如何开始 卡类 /** class Card : for creating playing card objects
/** class Card : for creating playing card objects
* it is an immutable class.
* Rank - valid values are 1 to 13
* Suit - valid values are 0 to 3
* Do not modify this class!
*/
class Card {
/* constant suits and ranks */
static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
/* Data field of a card: rank and suit */
private int cardRank; /* values: 1-13 (see Rank[] above) */
private int cardSuit; /* values: 0-3 (see Suit[] above) */
/* Constructor to create a card */
/* throw PlayingCardException if rank or suit is invalid */
public Card(int rank, int suit) throws PlayingCardException {
if ((rank < 1) || (rank > 13))
throw new PlayingCardException("Invalid rank:"+rank);
else
cardRank = rank;
if ((suit < 0) || (suit > 3))
throw new PlayingCardException("Invalid suit:"+suit);
else
cardSuit = suit;
}
/* Accessor and toString */
/* You may impelemnt equals(), but it will not be used */
public int getRank() { return cardRank; }
public int getSuit() { return cardSuit; }
public String toString() { return Rank[cardRank] + " " + Suit[cardSuit]; }
/* Few quick tests here */
public static void main(String args[])
{
try
{
Card c1 = new Card(1,3); // A Spades
System.out.println(c1);
c1 = new Card(10,0); // 10 Clubs
System.out.println(c1);
//c1 = new Card(10,5); // generate exception here
}
catch (PlayingCardException e)
{
System.out.println("PlayingCardException: "+e.getMessage());
}
}
}
/** class Decks represents : n decks of playing cards
* Use class Card to construct n * 52 playing cards!
*
* Do not add new data fields!
* Do not modify any methods
* You may add private methods
*/
class Decks {
/* this is used to keep track of original n*52 cards */
private List<Card> originalDecks;
/* this starts with n*52 cards deck from original deck */
/* it is used to keep track of remaining cards to deal */
/* see reset(): it resets dealDecks to a full deck */
private List<Card> dealDecks;
/* number of decks in this object */
private int numberDecks;
/**
* Constructor: Creates default one deck of 52 playing cards in originalDecks and
* copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
* @throws PlayingCardException
*/
public Decks() throws PlayingCardException
{
// implement this method!
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
/**
* Constructor: Creates n decks (52 cards each deck) of playing cards in
* originalDecks and copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
* @throws PlayingCardException
*/
public Decks(int n) throws PlayingCardException
{
// implement this method!
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
/**类卡:用于创建扑克牌对象
*它是一个不可变的类。
*等级-有效值为1到13
*套装-有效值为0到3
*不要修改这个类!
*/
班级卡{
/*不变的诉讼和等级*/
静态最终字符串[]套装={“梅花”、“钻石”、“红心”、“黑桃”};
静态最终字符串[]秩={”、“A”、“2”、“3”、“4”、“5”、“6”、“7”、“8”、“9”、“10”、“J”、“Q”、“K”};
/*卡的数据字段:等级和等级*/
private int cardRank;/*值:1-13(参见上面的秩[])*/
private int cardSuit;/*值:0-3(参见上文的Suit[]*/
/*构造函数创建一张卡片*/
/*如果等级或套装无效,则抛出PlayingCardException*/
公共卡(整数等级,整数套装)抛出PlayingCardException{
如果((秩<1)| |(秩>13))
抛出新PlayingCardException(“无效等级:+等级”);
其他的
cardRank=等级;
如果((诉讼<0)| |(诉讼>3))
抛出新的PlayingCardException(“无效套装:+套装”);
其他的
cardSuit=西装;
}
/*存取器和toString*/
/*您可以强制使用equals(),但不会使用它*/
public int getRank(){return cardRank;}
public int getSuit(){return cardSuit;}
公共字符串toString(){return Rank[cardRank]+“”+Suit[cardSuit];}
/*这里有一些快速测试*/
公共静态void main(字符串参数[])
{
尝试
{
卡c1=新卡(1,3);//黑桃
系统输出打印LN(c1);
c1=新卡(10,0);//10个俱乐部
系统输出打印LN(c1);
//c1=新卡(10,5);//在此处生成异常
}
捕捉(播放卡片例外)
{
System.out.println(“PlayingCardException:+e.getMessage());
}
}
}
甲板类
/** class Card : for creating playing card objects
* it is an immutable class.
* Rank - valid values are 1 to 13
* Suit - valid values are 0 to 3
* Do not modify this class!
*/
class Card {
/* constant suits and ranks */
static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
/* Data field of a card: rank and suit */
private int cardRank; /* values: 1-13 (see Rank[] above) */
private int cardSuit; /* values: 0-3 (see Suit[] above) */
/* Constructor to create a card */
/* throw PlayingCardException if rank or suit is invalid */
public Card(int rank, int suit) throws PlayingCardException {
if ((rank < 1) || (rank > 13))
throw new PlayingCardException("Invalid rank:"+rank);
else
cardRank = rank;
if ((suit < 0) || (suit > 3))
throw new PlayingCardException("Invalid suit:"+suit);
else
cardSuit = suit;
}
/* Accessor and toString */
/* You may impelemnt equals(), but it will not be used */
public int getRank() { return cardRank; }
public int getSuit() { return cardSuit; }
public String toString() { return Rank[cardRank] + " " + Suit[cardSuit]; }
/* Few quick tests here */
public static void main(String args[])
{
try
{
Card c1 = new Card(1,3); // A Spades
System.out.println(c1);
c1 = new Card(10,0); // 10 Clubs
System.out.println(c1);
//c1 = new Card(10,5); // generate exception here
}
catch (PlayingCardException e)
{
System.out.println("PlayingCardException: "+e.getMessage());
}
}
}
/** class Decks represents : n decks of playing cards
* Use class Card to construct n * 52 playing cards!
*
* Do not add new data fields!
* Do not modify any methods
* You may add private methods
*/
class Decks {
/* this is used to keep track of original n*52 cards */
private List<Card> originalDecks;
/* this starts with n*52 cards deck from original deck */
/* it is used to keep track of remaining cards to deal */
/* see reset(): it resets dealDecks to a full deck */
private List<Card> dealDecks;
/* number of decks in this object */
private int numberDecks;
/**
* Constructor: Creates default one deck of 52 playing cards in originalDecks and
* copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
* @throws PlayingCardException
*/
public Decks() throws PlayingCardException
{
// implement this method!
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
/**
* Constructor: Creates n decks (52 cards each deck) of playing cards in
* originalDecks and copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
* @throws PlayingCardException
*/
public Decks(int n) throws PlayingCardException
{
// implement this method!
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
/**类牌组表示:n副扑克牌
*使用类卡构造n*52张扑克牌!
*
*不要添加新的数据字段!
*不要修改任何方法
*您可以添加私有方法
*/
班级甲板{
/*这用于跟踪原始n*52卡*/
私人名单原件;
/*这从原始牌组的n*52张牌组开始*/
/*它用于跟踪要处理的剩余卡*/
/*请参阅reset():它将DealDealDeck重置为全甲板*/
私人名单;
/*此对象中的甲板数*/
私人国际号码;
/**
*构造函数:创建一副默认的52张扑克牌
*将它们复制到DealDeck。
*初始化numberdocks=n
*注意:您需要从卡构造函数捕获PlayingCardException
*将ArrayList同时用于originalDecks和DealDealDeck
*@抛出PlayingCardException
*/
public Decks()抛出PlayingCardException
{
//实施这个方法!
int i,j;
for(i=0;i您应该能够多次循环创建卡片组的步骤。在for循环之前或中通过n添加另一个循环
public Decks(int n) throws PlayingCardException
{
// implement this method!
int i, j;
for (i=0;i<4;i++)
{
for(j=1;j<14;j++)
{
for(k=0;k<n;k++){
Card orcard = new Card(i,j);
originalDecks.add(orcard);
dealDecks.add(orcard);
}
}
}
}
公共甲板(int n)抛出PlayingCardException
{
//实施这个方法!
int i,j;
对于(i=0;i如果你只想要一副牌,你知道每副牌有52张牌。那么为什么不在类牌堆中创建一个52张牌的数组呢
public class Deck {
private Card[] cards;
private int dealIndex; // position of next card to deal
public Deck(int n) { // n number of decks
cards = new Card[52*n];
dealIndex = 0;
// Initialize cards here by creating instances of cards.
// Maybe write a function to initialize 1 deck of cards and call this n times with appropriate index to cards array.
}
}
另一个要考虑的是在类卡中使用枚举来表示套装和排名。
最后,实现Comparable以便能够比较卡片。您可能希望创建类手牌,并实现Comparable以便能够比较扑克牌手牌。您的思路是正确的,但将所有这些尽可能以面向对象的方式进行操作会容易得多
每张扑克牌都有一套套装
和等级
,它们是一系列预定义的值。将它们设置为每个枚举值是有意义的,如下所示:
public enum PlayingCardSuit
{
None(0),
Spades(1),
Diamonds(2),
Hearts(3),
Clubs(4);
private int suit;
private PlayingCardSuit(int suit)
{
this.suit = suit;
}
}
public enum PlayingCardRank
{
None(0),
Ace(1),
Two(2),
Three(3),
Four(4),
Five(5),
Size(6),
Seven(7),
Eight(8),
Nine(9),
Ten(10),
Jack(11),
Queen(12),
King(13);
private int rank;
private PlayingCardRank(int rank)
{
this.rank = rank;
}
}
现在,您可以有一个Card
类,它同时表示Suit
和Rank
。我还使用UUID
为每张卡分配一个随机唯一的ID值。这使得通过对UUID
进行排序来洗牌变得更容易,而不是进行一些复杂的排序
以下是玩卡
课程:
import java.util.*;
public final class PlayingCard
{
private UUID id;
private PlayingCardSuit suit;
private PlayingCardRank rank;
public PlayingCard(PlayingCardSuit suit, PlayingCardRank rank)
{
this.id = UUID.randomUUID();
this.suit = suit;
this.rank = rank;
}
public UUID id()
{
return this.id;
}
public void setId(UUID id)
{
this.id = id;
}
public PlayingCardSuit suit()
{
return this.suit;
}
public PlayingCardRank rank()
{
return this.rank;
}
public String toString()
{
return String.format("%s of %s", this.rank, this.suit);
}
}
现在,Deck
仅仅是一个围绕Card
s集合的花式包装,其方法类似于shuffle()
和drawCard()
。作为它自己的类而不是数组,您可以从内部封装所有管理,而不必担心跟踪“留下了哪些卡”。它使用堆栈
集合完成所有这一切
import java.util.*;
public final class PlayingCardDeck
{
private Stack<PlayingCard> deck;
public PlayingCardDeck()
{
initializeDeck();
shuffle();
}
private void initializeDeck()
{
deck = new Stack<PlayingCard>();
for(final PlayingCardSuit suit : EnumSet.allOf(PlayingCardSuit.class))
{
// Skip the 'None' suit.
if(suit == PlayingCardSuit.None) continue;
for(final PlayingCardRank rank : EnumSet.allOf(PlayingCardRank.class))
{
// Skip the 'None' rank card.
if(rank == PlayingCardRank.None) continue;
PlayingCard card = new PlayingCard(suit, rank);
deck.push(card);
}
}
}
public int size()
{
return deck.size();
}
public void shuffle()
{
// Generate new UUIDs to randomize.
for(final PlayingCard card : deck)
card.setId(UUID.randomUUID());
// Sort the deck based on the card UUID for randomization.
Collections.sort(deck, new Comparator<PlayingCard>()
{
public int compare(PlayingCard a, PlayingCard b)
{
UUID aID = a.id();
UUID bID = b.id();
return aID.compareTo(bID);
}
});
}
public PlayingCard drawCard()
{
return deck.pop();
}
}
和输出(随机):
这是我的实现:
public class CardsDeck {
private ArrayList<Card> mCards;
private ArrayList<Card> mPulledCards;
private Random mRandom;
public static enum Suit {
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
public static enum Rank {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE;
}
public CardsDeck() {
mRandom = new Random();
mPulledCards = new ArrayList<Card>();
mCards = new ArrayList<Card>(Suit.values().length * Rank.values().length);
reset();
}
public void reset() {
mPulledCards.clear();
mCards.clear();
/* Creating all possible cards... */
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
Card c = new Card(s, r);
mCards.add(c);
}
}
}
public static class Card {
private Suit mSuit;
private Rank mRank;
public Card(Suit suit, Rank rank) {
this.mSuit = suit;
this.mRank = rank;
}
public Suit getSuit() {
return mSuit;
}
public Rank getRank() {
return mRank;
}
public int getValue() {
return mRank.ordinal() + 2;
}
@Override
public boolean equals(Object o) {
return (o != null && o instanceof Card && ((Card) o).mRank == mRank && ((Card) o).mSuit == mSuit);
}
}
/**
* get a random card, removing it from the pack
* @return
*/
public Card pullRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.remove(randInt(0, mCards.size() - 1));
if (res != null)
mPulledCards.add(res);
return res;
}
/**
* Get a random cards, leaves it inside the pack
* @return
*/
public Card getRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.get(randInt(0, mCards.size() - 1));
return res;
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public int randInt(int min, int max) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = mRandom.nextInt((max - min) + 1) + min;
return randomNum;
}
public boolean isEmpty(){
return mCards.isEmpty();
}
}
我没有时间给出一个很长的答案,但是创建一个牌组类。你可能根本不需要牌组类,你可以使用List的一个实例。只是为了澄清一下,当我这样做时,originalDecks和dealDecks是否会在每张牌组的n倍内拥有每张牌的n倍?我担心这样做会导致每张牌的数量减少由于某种原因被覆盖。两个组中的每一个都将有n张卡的副本。因此,如果n=3,则有2H、2H、2H。是否有明显的原因导致我在尝试向组中添加orcard时出错?错误是什么?一件事,如果这是所有代码,则需要实例化这些组。类似于:this.originalDecks=new ArrayList();“错误:无效排名:0”指向“抛出新的PlayingCardExce”
public class CardsDeck {
private ArrayList<Card> mCards;
private ArrayList<Card> mPulledCards;
private Random mRandom;
public static enum Suit {
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
public static enum Rank {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE;
}
public CardsDeck() {
mRandom = new Random();
mPulledCards = new ArrayList<Card>();
mCards = new ArrayList<Card>(Suit.values().length * Rank.values().length);
reset();
}
public void reset() {
mPulledCards.clear();
mCards.clear();
/* Creating all possible cards... */
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
Card c = new Card(s, r);
mCards.add(c);
}
}
}
public static class Card {
private Suit mSuit;
private Rank mRank;
public Card(Suit suit, Rank rank) {
this.mSuit = suit;
this.mRank = rank;
}
public Suit getSuit() {
return mSuit;
}
public Rank getRank() {
return mRank;
}
public int getValue() {
return mRank.ordinal() + 2;
}
@Override
public boolean equals(Object o) {
return (o != null && o instanceof Card && ((Card) o).mRank == mRank && ((Card) o).mSuit == mSuit);
}
}
/**
* get a random card, removing it from the pack
* @return
*/
public Card pullRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.remove(randInt(0, mCards.size() - 1));
if (res != null)
mPulledCards.add(res);
return res;
}
/**
* Get a random cards, leaves it inside the pack
* @return
*/
public Card getRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.get(randInt(0, mCards.size() - 1));
return res;
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public int randInt(int min, int max) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = mRandom.nextInt((max - min) + 1) + min;
return randomNum;
}
public boolean isEmpty(){
return mCards.isEmpty();
}
}