我们正在制作一个简单的 52 张纸牌游戏。我们在处理、洗牌和存储牌时遇到了很多麻烦。应向每位玩家发 5 张牌。该游戏类似于Hearts,但每个玩家只能获得5张牌。到目前为止,这是我们的代码:
int[] deck = new int[52];
String[] suits = { "Spades", "Hearts", "Diamonds", "Clubs" };
String[] ranks = { "A ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ",
"9 ", "10", "J ", "Q ", "K " };
// Initialize the cards
for (int i = 0; i < deck.length; i++)
deck[i] = i;
// Shuffle the cards
for (int i = 0; i < deck.length; i++) {
// Generate an index randomly
int index = (int) (Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
// Display the first five cards
System.out.println("player 1 has:");
for (int i = 0; i < 5; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
selectionSort(deck);
System.out.println("Card number " + deck[i] + " : " + rank + " of "
+ suit);
}
int player1[] = deck;
// Display the first five cards
System.out.println("\n" + "player 2 has:");
for (int i = 5; i < 10; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("Card number " + deck[i] + " : " + rank + " of "
+ suit);
}
int player2[] = deck;
// Display the first five cards
System.out.println("\n" + "player 3 has:");
for (int i = 10; i < 15; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("Card number " + deck[i] + " : " + rank + " of "
+ suit );
}
int player3[] = deck;
}
public static void selectionSort(int[] deck) {
for (int i = 52; i < deck.length - 1; i--){
int currentMax = deck[i];
int currentMaxIndex = i;
for (int j = i + 1; j < deck.length; j++) {
if (currentMax > deck[j]) {
currentMax = deck[j];
currentMaxIndex = j;
}}
if (currentMaxIndex != i) {
deck[currentMaxIndex] = deck[i];
deck[i] = currentMax;
}
}
}
}