小言_互联网的博客

顺序表实现简单的【扑克牌】

321人阅读  评论(0)

目录

1. 准备一张牌

2. 拿一副牌出来

3.洗牌(打乱牌的顺序)

4.开始发牌


代码gitee链接   20220711/src · 雷晓恒/Java - 码云 - 开源中国 (gitee.com)

1. 准备一张牌

一张扑克牌里面有点数和花色,


  
  1. class Card {
  2. public int rank; //点数
  3. public String suit; //花色
  4. public Card (int rank, String suit) {
  5. this.rank = rank;
  6. this.suit = suit;
  7. }
  8. @Override
  9. public String toString () {
  10. return suit+ " "+rank;
  11. }
  12. }

2. 拿一副牌出来

先搞一个数组存放牌的花色

    public static final String [] suits = {"♥", "♠", "♣", "♦"};

再循环一副牌出来


  
  1. public List<Card> buyDeskCard () {
  2. List<Card> cards = new ArrayList<>();
  3. for ( int i = 1; i <= 13; i++) {
  4. for ( int j = 0; j < 4; j++) {
  5. Card card = new Card(i,suits[j]);
  6. cards.add(card);
  7. }
  8. }
  9. return cards;
  10. }

试着打印看一下


  
  1. public static void main (String[] args) {
  2. CardDemo cardDemo = new CardDemo();
  3. List<Card> ret = cardDemo.buyDeskCard();
  4. System.out.println(ret);
  5. }

3.洗牌(打乱牌的顺序)

循环 让 i 存这个牌的数组从后到前开始循环,让 i 从 0 到 i-1 的某一个数组下标的牌交换,交换完成后i-- ,一直循环完成后,洗牌也就完成了、

洗牌


  
  1. public void shuffle (List<Card> cards) {
  2. for ( int i = cards.size()- 1; i > 0; i--) {
  3. //产生随机数
  4. Random random = new Random();
  5. int index = random.nextInt(i);
  6. //交换
  7. swap(cards,index,i);
  8. }
  9. }

 交换


  
  1. private void swap (List<Card> cards, int i, int j) {
  2. Card tmp = cards.get(i);
  3. cards.set(i,cards.get(j));
  4. cards.set(j,tmp);
  5. }

洗牌的方法写好了,我们试着调用一下


  
  1. public static void main (String[] args) {
  2. CardDemo cardDemo = new CardDemo();
  3. List<Card> ret = cardDemo.buyDeskCard();
  4. cardDemo.shuffle(ret);
  5. System.out.println(ret);
  6. }

4.开始发牌

如果是三个人每个人拿五张牌,这样发牌的话

发牌也就是将洗好的牌从数组中删除

而且发牌也要考虑,这张牌发给了谁,要能对应上


  
  1. public List<List<Card>> test (List<Card> cards) {
  2. //new三个人出来
  3. List<Card> hand1 = new ArrayList<>();
  4. List<Card> hand2 = new ArrayList<>();
  5. List<Card> hand3 = new ArrayList<>();
  6. List<List<Card>> hands = new ArrayList<>();
  7. hands.add(hand1);
  8. hands.add(hand2);
  9. hands.add(hand3);
  10. //轮流拿五张牌
  11. for ( int i = 0; i < 5; i++) {
  12. for ( int j = 0; j < 3; j++) {
  13. Card card = cards.remove( 0);
  14. hands.get(j).add(card);
  15. }
  16. }
  17. return hands;
  18. }

 写好发牌的方法,试着调用一下


  
  1. public static void main (String[] args) {
  2. CardDemo cardDemo = new CardDemo();
  3. List<Card> ret = cardDemo.buyDeskCard();
  4. System.out.println(ret);
  5. System.out.println( "洗牌:");
  6. cardDemo.shuffle(ret);
  7. System.out.println(ret);
  8. System.out.println( "发牌:");
  9. List<List<Card>> ret2 = cardDemo.test(ret);
  10. for ( int i = 0; i < ret2.size(); i++) {
  11. System.out.println( "第"+i+ "个人的牌:"+ ret2.get(i));
  12. }
  13. System.out.println( "剩余的牌:");
  14. System.out.println(ret);
  15. }



转载:https://blog.csdn.net/m0_58761900/article/details/125720830
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场