使用ArrayList和Map模拟斗地主发牌

tech2024-08-10  49

使用ArrayList和Map模拟斗地主发牌

直接上代码了。。。

public class PokerPlay { public static void main(String[] args) { //准备花色 ArrayList<String> color=new ArrayList(); Collections.addAll(color,"♠","♥","♦","♣"); //准备数字 ArrayList<String> number=new ArrayList(); Collections.addAll(number,"3","4","5","6","7","8","9","10","J", "Q","K","A","2"); //定义一个map集合:将数字与每一张牌进行对应 HashMap<Integer,String> map=new HashMap(); int index=0; for (String thisNumber:number) { for (String thisColor:color) { map.put(index++,thisColor+thisNumber); } } //加入大小王 map.put(index++,"小😜"); map.put(index++,"大😜"); //一副54张的扑克牌 ArrayList里面为0-53的数的共54张新牌 ArrayList cards=new ArrayList(); for (int i = 0; i <54 ; i++) { cards.add(i); } //洗牌可以使用 Collection.shuffle()方法打乱扑克牌顺序 Collections.shuffle(cards); //接下来就是创建3位玩家牌 以及3张底牌的数组集合进行发牌 ArrayList iPlayer1=new ArrayList(); ArrayList iPlayer2=new ArrayList(); ArrayList iPlayer3=new ArrayList(); ArrayList iThreeCards=new ArrayList(); //遍历这副洗好的牌,同时将遍历好的牌发到三个玩家和底牌中去 //依次发54张牌 for (int i = 0; i <cards.size(); i++) { //3张底池牌 if (i>=51){ iThreeCards.add(cards.get(i)); }else{ //剩下的牌分别分到3名玩家的手上,用i去模3(i%3)获取玩家1,2,3 if (i%3==0){ //玩家1的牌 iPlayer1.add(cards.get(i)); }else if (i%3==1){ //玩家2的牌 iPlayer2.add(cards.get(i)); }else { //玩家3的牌 iPlayer3.add(cards.get(i)); } } } //牌已发完,接下里分别对每位玩家的牌进行从小到大排序 Collections.sort(iPlayer1); Collections.sort(iPlayer2); Collections.sort(iPlayer3); Collections.sort(iThreeCards); //再定义4个数组集合String类型用于存储3位玩家的牌和底池牌 ArrayList siPlayer1=new ArrayList(); ArrayList siPlayer2=new ArrayList(); ArrayList siPlayer3=new ArrayList(); ArrayList siThreeCards=new ArrayList(); for (Object thiskey : iPlayer1) { siPlayer1.add(map.get(thiskey)); } //这里有一个坑。。。是关于for和foreach的问题 /*for (int i = 0; i < iPlayer1.size(); i++) { siPlayer1.add(map.get(i)); }*/ for (Object thiskey : iPlayer2) { siPlayer2.add(map.get(thiskey)); } for (Object thiskey : iPlayer3) { siPlayer3.add(map.get(thiskey)); } for (Object thiskey : iThreeCards) { siThreeCards.add(map.get(thiskey)); } //打印各玩家扑克牌和底池牌 System.out.println(siPlayer1+"----"+siPlayer1.size()+"张"); System.out.println(siPlayer2+"----"+siPlayer2.size()+"张"); System.out.println(siPlayer3+"----"+siPlayer3.size()+"张"); System.out.println(siThreeCards); } }

最新回复(0)