在游戏中的牌的等级 [英] Rank of Cards in a Game
问题描述
我是一个初学Java学生。所以任何帮助将非常感谢!
I'm a beginner Java student. So any help will be much appreciated!
我设计了一个类卡片和类Deck,我将在我创建的游戏中使用它。到目前为止,我的游戏似乎工作得很好,但我的问题在于我的卡牌类。我想使用我的getRank()方法作为一种方式来积累玩家的牌(不管是西装)的点数。
I've designed a class Cards and class Deck that I will use in a game that I've created. So far, my game seems to be working very well, but the problem I have lies in my Cards class. I'd like to utilize my getRank() method as a way to accumulate points for the cards a player has (regardless of suit).
例如,如果他们画一个2的钻石,它会值得2点,3的心3点...等等。我创建了一个 String []
调用 ranks
尝试这样做, em>这是它的作用。然而,我想所有的面孔卡(如国王,皇后...)的值为10.但不是所有这些卡都位于索引10在我的数组。我可以有一些指导如何去调整这个?
For example, if they draw a 2 of Diamonds, it will be worth 2 points, 3 of hearts 3 points...ect. I've created a String[]
called ranks
to try to do this, and I think that's what it does. However, I'd like all face cards (like king, queen...) to have a value of 10. But not all these cards lie at index 10 in my array. Could I have some guidance as to how to go about adjusting this?
提前感谢。
int rank;
int suit;
String[]ranks = { " "," ", " " } //all 13 ranks from Ace to King
String[]suits = { " ", " ", " "} //all ranks
public Card(int rank, int suit){
this.rank = rank;
this.suit = suit;
}
public void setRank(int rank){
this.rank = rank;
}
public int getRank(){
return rank;
}
//more code for suits
public String toString(){
return ranks[rank]+" of "+suits[suit];
}
推荐答案
枚举是你的朋友。正如你已经发现的, int
是不合适的,因为它们仅适用于一些情况(从一到十),没有什么可以阻止你的用户给出非法值(负值或大于13)。枚举可以强制正确的值,也可以很容易地关联任何你喜欢的数值。
Enums are your friend. As you've discovered, int
s are not appropriate, because they work for only some of the cases (ace through ten), and there's nothing stopping your user from giving an illegal value (negative or greater than 13). Enums can both enforce correct values, and also can also easily associate any numeric value you like.
public enum CardRank {
ACE(1),
TWO(2),
THREE(3),
...
TEN(10),
JACK(10),
QUEEN(10),
KING(10);
private final int value;
CardRank(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
使用此功能, / p>
Using this, you'd set the rank with
public void Card(CardRank rank, CardSuit suit) {
this.rank = rank;
this.suit = suit;
}
public int getRankValue() {
return rank.getValue();
}
枚举的另一个好处是 - 文档功能。如果参数都是 int
s,那么,通过查看签名的类型,不清楚哪个是rank,哪个是suit。
Another benefit of enums is much clearer, self-documenting functions. If the parameters are both int
s, then, by just looking at the signature's types, it's not clear which is the rank and which is the suit. With enums, it's a non-issue.
我会离开 CardSuit
作为练习:)
更多信息:
- http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
- 枚举的用法是什么?在Java?
- 什么是枚举,为什么它们有用?
- Java类卡枚举示例。 REVISED
- http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
- What's the use of "enum" in Java?
- What are enums and why are they useful?
- Java class card enum example. REVISED
这篇关于在游戏中的牌的等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!