如何为一副牌中的套装初始化一个布尔数组然后使其成为一个随机数将该套装变为真?对于初始化数组,我有
boolean[] suitsSelected = {"spades","clubs","diamonds", "hearts"};
然后声明一个随机数
Random myRandom = newRandom();
int card = myRandom.nextInt(51);
然后在选择卡后将布尔套装变为true?
spade = (card >= 0 && card < 14);
heart = (card >= 14 && card < 27);
club = (card >= 27 && card < 39);
diamond = (card >= 40 && card < 52);
答案 0 :(得分:1)
你可以用布尔语来做,比如
final int SPADES_INDEX = 0;
final int CLUBS_INDEX = 1;
final int HEARTS_INDEX = 2;
final int DIAMONDS_INDEX = 3;
final boolean[] suits = new boolean[4];
// helper function
void switchToSuit(int suitIndex) {
for(int i = 0; i < suits.length; i++) {
suits[i] = (suitIndex == i);
}
}
// later
if(card >= 0 && card <= 14) switchToSuit(SPADES_INDEX);
但那有点不稳定。如果你愿意,你可以使用int
简单得多。
final int SPADES_INDEX = 0;
final int CLUBS_INDEX = 1;
final int HEARTS_INDEX = 2;
final int DIAMONDS_INDEX = 3;
int suit = card / 13; // 0-12 are 0, 13-25 are 1, 26-38 are 2, and 39-51 are 3
更好的方法是使用enum
import java.util.*;
public class Main {
static Random rand = new Random();
static enum Suit {
SPADES,
CLUBS,
HEARTS,
DIAMONDS;
public String toString() {
return name().substring(0, 1);
}
}
static enum Rank {
ACE("A"), TWO("2"), THREE("3"), FOUR("4"),
FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"),
NINE("9"), TEN("T"), JACK("J"), QUEEN("Q"), KING("K");
final String key;
Rank(String key) {
this.key = key;
}
public String toString() {
return key;
}
}
public static void main(String[] args) {
List <String> pocket = new ArrayList<>();
List <String> board = new ArrayList<>();
int[] deck = new int[52];
for (int i = 0; i < 52; i++) {
deck[i] = i;
}
shuffleArray(deck);
for (int i = 0; i < 2; i++) {
int card = deck[i];
Suit suit = Suit.values()[card / 13];
Rank rank = Rank.values()[card % 13];
pocket.add("" + rank + suit);
}
for (int i = 0; i < 5; i++) {
int card = deck[i + 2];
Suit suit = Suit.values()[card / 13];
Rank rank = Rank.values()[card % 13];
board.add("" + rank + suit);
}
System.out.println("Hold'em pocket: " + pocket);
System.out.println("Hold'em board: " + board);
}
// Fisher–Yates shuffle - https://stackoverflow.com/a/1520212/330057
static void shuffleArray(int[] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
for (int i = ar.length - 1; i > 0; i--) {
int index = rand.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}