用Java集合模拟斗地主发牌的例子

之前学集合的时候看到了一个很有意思的例子,于是觉得可以用集合来存储牌型来模拟斗地主的发牌模式,将一副54张的扑克牌随机分发给三个玩家手中,保留三张作为底牌,每个玩家手中有17张牌。

public class Testpoker {
	
	public static void main(String[] args) {
		
		ArrayList color = new ArrayList();	
		
		String[] nums={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
		Collections.addAll(color,"♠","♥","♦","♣" );
		
		HashMap cards = new HashMap();
		int index = 1;
		for (String flower : nums) {
			for(String poker : color){
				cards.put(index++, poker+flower);
			}
		}
		cards.put(index++,"小王");
		cards.put(index++,"大王");
		
// 		System.out.println(cards);
// 		System.out.println(cards.size());
		
		ArrayList cards_order = new ArrayList();
		for(int i=1;i<55;i++){
		cards_order.add(i);
		}
		
		Collections.shuffle(cards_order); 
//  		System.out.println(cards_order);
		
		 ArrayList base_key = new ArrayList();
		 ArrayList player1_key = new ArrayList();
		 ArrayList player2_key = new ArrayList();
		 ArrayList player3_key = new ArrayList();
		
		for(int i=0;i<54;i++){
			if(i>50){
				base_key.add(cards_order.get(i));
			}
			else{
				if(i%3==0){
					player3_key.add(cards_order.get(i));
				}
				else if(i%2==0){
					player2_key.add(cards_order.get(i));
				}
				else{
					player1_key.add(cards_order.get(i));
				}
			}
		}
//		System.out.println(base_key);
//		System.out.println(player3_key);
//		System.out.println(player2_key);
//		System.out.println(player1_key);
		Collections.sort(player1_key);
		Collections.sort(player2_key);
		Collections.sort(player3_key);

		
		ArrayList base_list = new ArrayList();
		for (Integer i: base_key) {
			base_list.add(cards.get(i));
		}
		ArrayList p1_list = new ArrayList();
		for (Integer i: player1_key) {
			p1_list.add(cards.get(i));
		}
		ArrayList p2_list = new ArrayList();
		for(Integer i: player2_key){
			p2_list.add(cards.get(i));
		}
		ArrayList p3_list = new ArrayList();
		for(Integer i: player3_key){
			p3_list.add(cards.get(i));
		}
		
		
		System.out.println("底牌:"+base_list);
		System.out.println("玩家一手牌:"+p1_list);
		System.out.println("玩家二手牌:"+p2_list);
		System.out.println("玩家三手牌:"+p3_list);
		
		int ra = (int)(Math.random()*10);
 		while(ra==0){
 			ra = (int)(Math.random()*10);
 		}
 		if(ra%3==0){
 			System.out.println("玩家三先抢地主");
 		}
 		else if (ra%2==0){
			System.out.println("玩家二先抢地主");
		}
 		else {
			System.out.println("玩家一先抢地主");
		}
		//System.out.println(ra);
	}
}

 

你可能感兴趣的:(Java)