我对这个网站xD
很新我试图用Java创建一个纸牌游戏,但我有一些问题,以创建一个卡片图像的牌组。我创建了两个类:Deck和Card。在Card类中,我输入以下代码
public static final int SPADE = 4;
public static final int HEART = 3;
public static final int CLUB = 2;
public static final int DIAMOND = 1;
private static final String[] Suit = { "*", "d", "c", "h", "s"};
private static final String[] Rank = { "*", "A", "2", "3", "4",
"5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
private int cardValue;
public Card( int suit, int rank)
{
if ( rank == 1 )
cardValue = 14*10 + suit; // Give Ace the rank 14
else
cardValue = rank*10 + suit;
}
在Deck类中,我把构造函数创建了52张卡片组:
private Card[] deckOfCards;
public static final int NCARDS = 52;
public Deck( )
{
deckOfCards = new Card[NCARDS];
int i=0;
for ( int suit = Card.DIAMOND; suit <= Card.SPADE; suit++ ) {
for ( int rank = 1; rank <= 13; rank++,i++ ){
deckOfCards[i] = new Card(suit, rank);
}
}
}
我还创建了洗牌和处理牌的方法,但我无法设法将deckOfCards与每张牌的相关图像联系起来。有人可以帮帮我吗? :)
提前致谢!
答案 0 :(得分:1)
另一种选择是使用Unicode characters depicting playing cards。这样你只需使用一个字符串来存储代表卡的字符,并显示它,只要你使用支持它的字体。
答案 1 :(得分:0)
有许多方法可以在Java中添加图像。这只是其中一种方式(可能不是最好的方式),但它可以让您了解如何将图像与对象相关联。
//Create Objects
CardClass[] cardObj = new CardClass[52];
//Interface definition
String path = "your path name";
ImageIcon image = new ImageIcon();
JLabel label = new JLabel();
JPanel card = new JPanel();
image = new ImageIcon (path + cardObj[0].strImage); //where strImage is attribute of CardClass
label = new JLabel (image);
card.add(label);
注意:您无法粘贴我的所有代码并希望它能够神奇地运行。在这里,我试图解释如何关联对象的属性并在插入图像时使用它。