理解很好理解,關鍵是思路
按照斗地主的規則,完成洗牌發牌的動作:
具體規則:
1. 組裝54張撲克牌
2. 將54張牌順序打亂
3. 三個玩家參與游戲,三人交替摸牌,每人17張牌,最后三張留作底牌。
4. 查看三人各自手中的牌(按照牌的大小排序)、底牌
手中撲克牌從大到小的擺放順序:大王,小王,2,A,K,Q,J,10,9,8,7,6,5,4,3
package com.oracle.demo01; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class Doudizhu { public static void main(String[] args) { //1.創建撲克牌Map Map<Integer,String> pooker=new HashMap<Integer,String>(); //創建所有key所在的容器 ArrayList<Integer> pookerNum=new ArrayList<Integer>(); //創建花色數組 String[] color={"♠","♣","♥","♦"}; //創建牌號數組 String[] number={"2","A","K","Q","J","10","9","8","7","6","5","4","3"}; //造牌並存進map集合 int index=2; for(String n:number){ for(String c:color){ //向map中存數據 pooker.put(index,c+n); //向所有key所在的容器存數據 pookerNum.add(index); index++; } } //存大小王 pooker.put(0, "大王"); pookerNum.add(0); pooker.put(1, "小王"); pookerNum.add(1); //洗牌 Collections.shuffle(pookerNum); //System.out.println(pookerNum); //發牌 //創建四個容器 ArrayList<Integer> bottom=new ArrayList<>(); ArrayList<Integer> player1=new ArrayList<>(); ArrayList<Integer> player2=new ArrayList<>(); ArrayList<Integer> player3=new ArrayList<>(); //開始發牌 for(int i=0;i<pookerNum.size();i++){ //將前三張給底牌 if(i<3){ bottom.add(pookerNum.get(i)); }else if(i%3==0){ player1.add(pookerNum.get(i)); }else if(i%3==1){ player2.add(pookerNum.get(i)); }else if(i%3==2){ player3.add(pookerNum.get(i)); } } //排序(key升序 牌從大到小) Collections.sort(bottom); Collections.sort(player1); Collections.sort(player2); Collections.sort(player3); //看牌(調用方法) look("劉德華",player1,pooker); look("張家輝",player2,pooker); look("周潤發",player3,pooker); look("底牌",bottom,pooker); } //看牌的方法(傳參為 玩家姓名,玩家的牌即鍵,所有牌的鍵值對) public static void look( String name,ArrayList<Integer> player,Map<Integer,String> pooker){ //打印玩家姓名 System.out.print(name+":"); //遍歷所有牌號 for(int num:player){ System.out.print(pooker.get(num)+" "); } System.out.println(); } }