简单的Java卡游戏 - 麻烦洗牌(阵列)

时间:2014-01-24 12:28:14

标签: java

我是Java新手,我无法理解如何改组数组(或我的套牌阵列)。我已经尝试过使用Random类了,但它并没有为我做这件事。无论如何,这里是我创建的课程:

CardGame

import java.util.Random;

public class CardGame {

    public static void main(String[] args) {

        // final int SPADES = 0, HEARTS = 1, DIAMONS = 2, CLUBS = 3;
        final int ACE = 1, TWO = 2, THREE = 3, FOUR = 4, FIVE = 5, SIX = 6, SEVEN = 7, EIGHT = 8;
        final int NINE = 9, TEN = 10, JACK = 11, QUEEN = 12, KING = 13;

        Random rand = new Random();

        int[][] deck = {
                { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING },

                player1.setHand(deck[i][randIndex]);
                player2.setHand(deck[i][randIndex]);
                player3.setHand(deck[i][randIndex]);
            }
        }

        System.out.println(player1.getHand());
        System.out.println(player2.getHand());
        System.out.println(player3.getHand());
    }
}

播放器

public class Player {

    final int MAX_HAND = 6;

    private String playerName;
    private int playerHand[] = new int[MAX_HAND];

    public Player(String name) {
        playerName = name;
    }

    public void setHand(int card) {

        int currentLength = playerHand.length;

        if (currentLength == MAX_HAND) {
            return;
        }

        playerHand[currentLength] = card;
    }

    public String getHand() {

        String cardN
                case 8:     cardNames += "Eight";   break;
                case 9:     cardNames += "Nine";    break;
                case 10:    cardNames += "Ten";     break;
                case 11:    cardNames += "Jack";    break;
                case 12:    cardNames += "Queen";   break;
                case 13:    cardNames += "King";    break;
            }

            if (i < playerHand.length - 2) {
                cardNames += ", ";
            }

        }

        return playerName + " has " + cardNames + " on his hand.";
    }
}

结果总是:

  

Name1手上有Ace,Two,Three,Four和Five。
Name2有Ace,   他手上有两个,三个,四个和五个。
Name3有Ace,Two,Three,Four   他手上有五个人。

deck的内部数组生成随机索引,我做错了什么?

谢谢。

2 个答案:

答案 0 :(得分:1)

switch (i)方法中将switch (playerHand[i])替换为getHand(),并在每次迭代时为每个玩家调用nextInt()

setHand()更改为


int index = 0;
public void addCard(int card) {
  if (index == MAX_HAND) {
            return;
  }
  playerHand[index++] = card;
}

答案 1 :(得分:0)

每次设置卡片后都需要调用rand.nextInt。

                player1.setHand(deck[i][rand.nextInt(deck[i].length)]);
                player2.setHand(deck[i][rand.nextInt(deck[i].length)]);
                player3.setHand(deck[i][rand.nextInt(deck[i].length)]);