[英]How to convert .rank into an integer value?
试图用Java创建二十一点游戏,却无法理解如何从数组事物中获取数值。
这是我的纸牌代码:
//Represent a playing card
public class Card
{
//Instance variables:
int suit; //0=clubs, 1=diamonds, 2=hearts, 3=spades
int rank; //1=ace, 2=2,..., 10=10, 11=J, 12=Q, 13=K
//Constructor:
public Card (int theSuit, int theRank)
{
suit = theSuit;
rank = theRank;
}
//Print the card in a human-readable form:
public void printCard()
{
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"narf", "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
System.out.print(ranks[rank] + " of " + suits[suit]);
}
}
请参阅我已经使用过Card cardOne = deck.cards [(int)(Math.random()* 52)]; 以获得玩家可以看到的第一张和第二张纸牌,但是我正在努力找出如何将纸牌的价值(4张红心中的4张,黑桃杰克中的10张等)保存为整数用来确定玩家获得多少分的价值?
抱歉,如果这令人困惑,英语不是我的母语。
提前致谢!
-约翰
如果您的整数n
在0到51之间(含0和51),则可以将其转换为0-3和0-12范围内的两个数字,如下所示:
suit = n / 13; // will be in range 0 to 3
rank = n % 13; // will be in range 0 to 12
要么
rank = n / 4; // will be in range 0 to 12
suit = n % 4; // will be in range 0 to 3
除非您打算使用n
进行其他操作,否则选择哪一个都不重要。 如果您确实打算使用n
来代表一张牌,则必须决定是否要使订单成为Club-ace,diamond-ace,heart-ace,spade-ace,club-2,diamond-2等。 ...或club-ace,club-2,club-3,club-4 ... club-king,diamond-ace,diamond-2,...
只需创建一个int[]
数组,该数组具有点值,索引与ranks
数组对齐。
String[] ranks = {"narf", "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
int[] points = {0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 10, 10, 10};
然后,当您的随机数生成一个int
值(我们将其称为index
)时,您可以执行以下操作:
String rank = ranks[index];
int numberOfPoints = points[index];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.