如何将.rank转换为整数值?

时间:2014-12-09 04:42:22

标签: java loops

尝试用Java创建一个Blackjack游戏,无法理解如何从数组中获取数值。

这是我的牌组代码:

//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张黑桃杰克等等)一个整数值,用于确定玩家有多少分?

抱歉,如果这令人困惑,英语不是我的第一语言。

提前致谢!

-John

2 个答案:

答案 0 :(得分:0)

如果你有一个0到51之间的整数n,你可以将它转换为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代表卡片,那么您必须决定是否要将该订单设为俱乐部王牌,钻石王牌,心脏王牌,锹王牌,俱乐部-2 ,钻石-2等......或者俱乐部 - 王牌,俱乐部-2,俱乐部-3,俱乐部-4 ......俱乐部国王,钻石王牌,钻石-2,......

答案 1 :(得分:0)

只需创建一个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];