我有这个洗牌牌,我应该做它,以便它发出5张牌给四名玩家。我像个白痴一样坐在这里好几个小时,我被困住了。
public class Deck {
public static void main(String[] args)
{
String[] SUITS = {
"Clubs", "Diamonds", "Hearts", "Spades"
};
String[] RANKS = {
"2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"
};
// initialize deck
int n = SUITS.length * RANKS.length;
String[] deck = new String[n];
for (int i = 0; i < RANKS.length; i++) {
for (int j = 0; j < SUITS.length; j++) {
deck[SUITS.length*i + j] = RANKS[i] + " of " + SUITS[j];
}
}
// shuffle
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n-i));
String temp = deck[r];
deck[r] = deck[i];
deck[i] = temp;
}
// print shuffled deck
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++)
System.out.println(deck[i])
}
}最后那部分我被困住了。我为四位玩家准备了五张类似的卡片。看起来是这样的:
如果我的意图是给四位玩家发五张不同的牌,我该怎么做呢?
我正在用Java编写代码,做数组,我不能使用任何java实用程序。
发布于 2017-01-02 21:05:00
这只是打印结果时的一个错误。使用
// print shuffled deck
for (int i = 0; i < 4; i++) {
System.out.println("** Person " + (i + 1) + " **");
for (int j = 0; j < 5; j++) {
System.out.println(deck[i + j * 4] + " (Card " + (i + j * 4) + ")");
}
}(增加Sysouts以演示卡的分发)
示例输出:
**人1 ** 2.会社(第0卡) 4颗钻石(卡片4) 9颗钻石(卡片8) 10颗心脏(卡片12) 9.会社(第16卡) **人2 ** 6颗心脏(卡片1) 8颗钻石(卡片5) 黑桃九(第九卡) 心脏千斤顶(卡片13) 钻石千斤顶(卡片17) **人3 ** 会社皇后(卡片2) 钻石王牌(卡片6) 红心之王(卡片10) 8.会社(第14卡) 黑桃5(第18卡) **人4 ** 黑桃10 (第3卡) 10个会社(第7卡) 黑桃杰克(第11卡) 10颗钻石(卡片15) 会社王牌(卡片19)
发布于 2017-01-02 21:00:58
Math.random() * (n-i)是biased,但您可以使用shuffle
Collections.shuffle(deck, new Random())我不知道这是否算"java utils“,因为我不确定您是否指包java.utils。
现在谈谈你的问题。数组不能很好地表示一副牌。堆栈或队列会更好,因为它们都允许您每次从一张牌中取一张牌。使用数组,你可以看到一个索引,这不是我们在现实生活中玩扑克牌的方式。理想情况下,交易的行为是将一张牌从一张牌转移到一位玩家的手上,保持牌位排列将使它很难保持跟踪。
发布于 2017-01-02 21:08:38
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++)
System.out.println(deck[i])
}在这里,您循环使用相同的卡deck[i],因为不考虑j。此外,即使您考虑了j,它也无法解决您的问题,因为当外部循环迭代时,嵌入循环总是以索引j=0作为初始化开始。
您应该从上一张处理过的卡片的索引开始第二个循环。
你的循环应该首先考虑玩家的数量,然后考虑每个玩家要处理的牌数。
所以我建议你们两个循环:一个和另一个嵌入。
我建议你用常量来声明玩家的数量和卡片的数量,而不是硬编码,以便有一个更易读的代码。
如果以后这些数据可能发生变化,则可以通过方法参数中的变量替换常量,例如。
public class Deck {
...
private static final int NB_PLAYER = 4;
private static final int NB_CARD_BY_PLAYER = 5;
...
int playerNumber = 1;
// you loop as much as the number of players
// your increment step is the number of cards to deal by player
// your end condition is the number of cards you have to
// deal for all players
for (int i = 0; i < NB_PLAYER * NB_CARD_BY_PLAYER; i = i + NB_CARD_BY_PLAYER) {
System.out.println("player " + playerNumber + ", cards =");
// you loop as much as the number of cards to deal by player
// your start from the last dealed card
// your increment step is 1 as you want to deal card by card from the deck
// your end condition is the number of cards to deal by player
for (int j = i; j < i+NB_CARD_BY_PLAYER; j++) {
System.out.println(deck[j]);
}
playerNumber++;
}
}https://stackoverflow.com/questions/41433147
复制相似问题