关于java:Java集合练习斗地主发牌

44次阅读

共计 1842 个字符,预计需要花费 5 分钟才能阅读完成。

思路
  • 创立一个 HashMap 汇合用于记录 54 张牌

    • {0=♥2, 1=♦2, 2=♣2, 3=♠2, 4=♥3, 5=♦3, … , 50=♣A, 51=♠A, 52= 大王, 53= 小王}
  • HashMap 汇合的 key 值记录 54 张牌的程序
  • 创立一个一般 ArrayList 汇合用于记录 54 个数字,对应 HashMap 的 54 个 Key 值
  • 打乱整个 ArrayList 汇合(洗牌)
  • 创立四个 TreeSet 汇合(三个玩家汇合和底牌汇合),依照一人一张的程序别离将张牌的 Key 值存入三个玩家汇合中,最初三张非凡解决存入底牌汇合。

    • 应用 TreeSet 汇合存牌的起因是因为 TreeSet 汇合自带排序功能。
  • 依据四个 TreeSet 汇合记录的 Key 值获取 HashM 汇合中映射的 value 值
代码
package com.collection;

import java.util.*;

public class PokerTest {public static void main(String[] args) {String decor[] = {"♥", "♦", "♣", "♠"};
        String number[] = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
        HashMap<Integer, String> cards = new HashMap<Integer, String>();
        int num = 0;
        for (int j = 0; j < number.length; j++) {for (int i = 0; i < decor.length; i++) {cards.put(num++, decor[i] + number[j]);
            }
        }
        cards.put(52, "大王");
        cards.put(53, "小王");
        ArrayList<Integer> cards_index = new ArrayList<>();
        for (int i = 0; i < 54; i++) {cards_index.add(i);
        }

        Collections.shuffle(cards_index);

        TreeSet<Integer> player1 = new TreeSet<Integer>();
        TreeSet<Integer> player2 = new TreeSet<Integer>();
        TreeSet<Integer> player3 = new TreeSet<Integer>();
        TreeSet<Integer> hole_cards = new TreeSet<Integer>();
        for (int i = 0; i < cards_index.size(); i++) {if (i >= 51) {hole_cards.add(cards_index.get(i));
            } else if (i % 3 == 0) {player1.add(cards_index.get(i));
            } else if (i % 3 == 1) {player2.add(cards_index.get(i));
            } else if (i % 3 == 2) {player3.add(cards_index.get(i));
            }
        }

        System.out.println("Player1--------");
        for (Integer i1 : player1) {System.out.print(cards.get(i1) + "\t");
        }
        System.out.println("\nPlayer2--------");
        for (Integer i2 : player2) {System.out.print(cards.get(i2) + "\t");
        }
        System.out.println("\nPlayer3--------");
        for (Integer i3 : player3) {System.out.print(cards.get(i3) + "\t");
        }
        System.out.println("\nHole Cards--------");
        for (Integer i4 : hole_cards) {System.out.print(cards.get(i4) + "\t");
        }
    }
}

/*
    Player1--------
    ♠2    ♣3    ♥4    ♣6    ♣7    ♠7    ♥8    ♠8    ♣9    ♥10    ♣10    ♣J    ♥Q    ♦Q    ♥K    ♥A    ♦A    
    Player2--------
    ♦3    ♣4    ♦5    ♣5    ♥6    ♦6    ♠6    ♦7    ♣8    ♥9    ♦9    ♥J    ♠J    ♣K    ♠A    大王    小王    
    Player3--------
    ♥2    ♣2    ♥3    ♠3    ♦4    ♠4    ♥5    ♦8    ♠9    ♦10    ♠10    ♦J    ♣Q    ♠Q    ♦K    ♠K    ♣A    
    Hole Cards--------
    ♦2    ♠5    ♥7    
*/

正文完
 0