斗地主实例+单列(JAVA集合综合案例)

1、规则:
使用54张牌打乱顺序,三个玩家参与游戏,三人交替摸牌,每人17张牌,最后3张留作底牌
2、分析

(1)、准备牌:

54张存储在一个集合中 特殊牌:大王小王 其他52张:
        定义一个数组/集合,存储4种花色;
        定义一个数组/集合,存储13个序号    
        循环遍历这两个数组/集合,组装52张牌  
          ♣2, ♣3, ♣9, ♣A......   
           ♥6,♥7,♥K,♥9.......

(2)洗牌:

     使用集合工具类collections方法
     static void shuffle(List <?> list)
     使用指定的随即源对指定列表进行置换
     会随机的打乱集合中元素的顺序  

(3)发牌:

     要求:17张/人,共3人,留3张底牌:
     一人一张轮流发牌,集合的索引(0-53)%3
     定义4个集合,存储三个玩家的牌和底牌
     索引%2有两个值(0,1)即:(0-3)%2
     索引%3有三个值(0,1,2)即:(0-3)%3
     索引>=51,改为底牌发牌

> (4)看牌:

            A、直接打印集合
            B、遍历存储玩家和底牌的牌

(5)源代码实现:


package day1;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class DouDiZhu {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//1、准备
		//定义一个存储54张牌的集合
		//定义两个数组,分别存储花色和牌序号
		ArrayList<String> poker = new ArrayList<>();
		String[] colors = {"♥","♣","♦","♠"};
		String[] numbers= {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
		//先把大王小王存储到poker集合中
		poker.add("大王");
		poker.add("小王");
		//循环嵌套遍历两个数组
		for(String number : numbers) {
			for(String color : colors) {
				//	//System.out.println(color+number);输出color+number
				//把组装好的牌存在poker种
				poker.add(color+number);
			}
		}
		//System.out.println(poker);
 		/*
 		 * 2、洗牌
 		 */
		Collections.shuffle(poker);
		//System.out.println(poker);

		/*
		 * 3、发牌
		 */
		
		ArrayList<String> player01=new ArrayList<>();
		ArrayList<String> player02=new ArrayList<>();
		ArrayList<String> player03=new ArrayList<>();
		ArrayList<String> dipai=new ArrayList<>();
		
		/*
		 * 4、遍历poker
		 */
		for(int i = 0;i< poker.size();i++) {
			//获取每一张牌
			String p = poker.get(i);
			if(i>=51) {
				dipai.add(p);
			}else if(i%3==0){
				//给玩家1发牌
				player01.add(p);
			}else if(i%3==1) {
				player02.add(p);
			}else if(i%3==2) {
				player03.add(p);
				}
		}
		//看牌
		System.out.println("我的牌:"+player01);
		System.out.println("你的牌:"+player02);
		System.out.println("他的牌:"+player03);
		System.out.println("底牌:"+dipai);
	}

}

(6)运行结果:

我的牌:[2,9, ♣J,4, ♦J, ♦Q,9, ♥J, ♠A,4,8,5,8,7,8, 大王,2]
你的牌:[6,5,10,9, ♣Q, ♦K,5,6,9, ♦A,7,4,3, ♥Q,10, ♣K, ♥A]
他的牌:[2,10,5, ♠J,2,6,4, ♥K, ♠Q, ♠K,6,7,3,7,3, 小王,10]
底牌:[8, ♣A,3]

(7)注意:
运行结果并不唯一

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章