一副扑克52张牌(没有大小王),模拟洗牌

纸牌类,代表一张纸牌:

public class Card { public CardSuit suit; //花色 public int value; //点数,1代表A,11代表J public Card(CardSuit suit, int value) { this.suit = suit; this.value = value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); switch(suit) { case SPADE: sb.append("黑桃"); break; case HEART: sb.append("红桃"); break; case DIAMOND: sb.append("方片"); break; case CLUB: sb.append("梅花"); break; } switch(value) { case 1: sb.append('A'); break; case 11: sb.append('J'); break; case 12: sb.append('Q'); break; case 13: sb.append('K'); break; default: sb.append(value); } return sb.toString(); } }

 

扑克类,代表一副扑克:

import java.util.Random; //纸牌的花色,分别是:黑桃,红心,方片,梅花 enum CardSuit {SPADE, HEART, DIAMOND, CLUB}; //52张牌,没有大小王 public class Cards { public Cards() { cards = new Card[52]; int index = 0; for(CardSuit suit:CardSuit.values()) { for(int i=1; i<=13; i++) cards[index++] = new Card(suit, i); } } public void showCards() { for(Card c:cards) { System.out.print(c); System.out.print(" "); } System.out.println(); } //洗牌 public void shuffle() { Card[] target = new Card[52]; int i = 0, j = 26, index = 0, n; Random rand = new Random(); //交错式洗牌 while(index<52) { n = rand.nextInt(3) + 1; while(n>0&&i<26) { target[index++] = cards[i++]; n--; } n = rand.nextInt(3) + 1; while(n>0&&j<52) { target[index++] = cards[j++]; n--; } } //切牌,把下半部分和上半部分互换位置 n = rand.nextInt(10)+20; for(i=0; i<52; i++) { cards[i] = target[(n+i)%52]; } } private Card[] cards; }

 

 

主函数,测试一下上面的内容:

public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Cards cards = new Cards(); cards.showCards(); cards.shuffle(); cards.shuffle(); cards.shuffle(); cards.shuffle(); cards.shuffle(); cards.showCards(); } }

你可能感兴趣的:(一副扑克52张牌(没有大小王),模拟洗牌)