我正在尝试创建一个简单的纸牌游戏,其中两个玩家接收随机卡。我决定使用构造函数使其简单并占用更少的空间。有人可以帮助我解释如何从我的Card课程中在我的主程序中生成随机卡。
public class clsCard {
private int value;
private int rank, suit;
private final int MaxFaceValue= 10;
private static String[] suits = {"Joker","hearts","spades","diamond","clubs"};
private static String[] ranks = {"Joker","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
public clsCard(int suit, int rank)
{
this.rank= (int)(Math.random()*ranks.length);
this.suit= (int)(Math.random()*suits.length);
}
public @Override String toString()
{
if(ranks[rank].equals("Joker") || suits[suit].equals("Joker"))
return "Joker";
else
return ranks[rank] + " of " + suits[suit];
}
public int getRank()
{
return rank;
}
public int getSuit()
{
return suit;
}
}
答案 0 :(得分:0)
首先,您需要所有卡片,然后随机选择。您可能需要一些基本类来执行此操作。这只是一种方法 - 创建一个套牌,如:
import java.util.ArrayList;
public class Deck {
private ArrayList cards;
public enum Suit {Joker, Spade, Club, Heart, Diamond};
public Deck() {
cards = new ArrayList<Card>();
// Add all appropriate cards
for(int i = 1; i < 14; i++) {
cards.add(new Card(i, Suit.Spade));
cards.add(new Card(i, Suit.Club));
cards.add(new Card(i, Suit.Heart));
cards.add(new Card(i, Suit.Diamond));
}
cards.add(new Card(0, Suit.Joker));
cards.add(new Card(0, Suit.Joker));
}
public Card dealRandomCard() {
int random = (int)(Math.random()*cards.size());
Card c = cards.get(random)
cards.remove(random);
return c;
}
}
这也是一个Card类,展开:
public class Card {
public Card(int i, Suit s) {
}
}
然后你可以从那里建立。