我正在用Java做二十一点游戏,做了一个创建纸牌的方法,然后是一个洗牌的方法。我还需要纸牌的数组列表以及其他功能,例如绘制纸牌的方法,但是每次我调用该方法时,它都会打乱新牌组。我想避免这种情况,但是我不知道如何...
这些方法定义并洗牌:
public static String[] kortlek() {
String suit[] = { "S", "D", "C", "H" };
String rank[] = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J",
"Q", "K", "A" };
String[] deck = new String[52];
String[] shuffledDeck = new String[deck.length];
int i = 0;
for (i = 0; i < deck.length; i++) {
deck[i] = rank[i % 13] + suit[i / 13];
} // End of for loop
deck = shuffledDeck(deck);
return deck;
}
public static String[] shuffledDeck(String [] shuffledDeck) {
for (int i = 0; i < shuffledDeck.length; i++) {
int index = (int) (Math.random() * shuffledDeck.length);
String temp = shuffledDeck[i];
shuffledDeck[i] = shuffledDeck[index];
shuffledDeck[index] = temp;
} // End of loop
for (int i = 0; i < shuffledDeck.length; i++) {
System.out.println(shuffledDeck[i]);
}
return shuffledDeck;
}
这个带有按钮actionListener方法的方法会抓一张牌:
public static String drawCard(int wichCard) {
String[] deck = kortlek();
String drawnCard = deck[0 + wichCard];
System.out.println("The drawn card is: " + drawnCard);
return drawnCard;
}
actionListener:
if (event.getSource() == drawCard) {
counter++;
String drawnCard = cardDeck.drawCard(counter);
player.setText("The drawn card is: " + drawnCard);
}
输出将是:
first draw:
1 2 3 4 5
drawn card = 1
2nd draw:
5 3 2 1 4
drawn card = 3
3rd draw:
5 2 4 1 3
drawn card = 4
我希望每次抽卡时,列表都不会随机化。怎么样?
谢谢!