按照斗地主的规则,完成洗牌发牌的动作。
具体规则:
-
使用54张牌;
-
打乱顺序;
-
三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌;
-
手中的牌按从小到大的顺序排列
import java.util.ArrayList;import java.util.Collections;import java.util.LinkedHashMap;import java.util.Map;public class Doudizhu {public static void main(String[] args){//1.创建编号和牌对应的map集合,编号越大牌越大Map<Integer,String> map = new LinkedHashMap<Integer,String>();//2.创建牌的编号对应的ArrayList集合ArrayList<Integer> arraylist = new ArrayList<Integer>();//3.向Map,ArrayList中添加数据//编号int id = 1;//花色和数值String[] colors={"♠️","♥️","♣️","♦️"};String[] numbers={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};//生成牌for (String num:numbers) {for (String color:colors) {String card = color+num;map.put(id,card);arraylist.add(id);id++;}}map.put(id,"小王");arraylist.add(id);id++;map.put(id,"大王");arraylist.add(id);//4.洗牌Collections.shuffle(arraylist);//5.发牌ArrayList<Integer> person1Id = new ArrayList<Integer>();ArrayList<Integer> person2Id = new ArrayList<Integer>();ArrayList<Integer> person3Id = new ArrayList<Integer>();ArrayList<String> remaining = new ArrayList<String>();//给三个玩家轮流发牌for (int i=0;i<arraylist.size()-3;i++){person1Id.add(arraylist.get(i));i++;person2Id.add(arraylist.get(i));i++;person3Id.add(arraylist.get(i));}//剩下的三张底牌for (int j=arraylist.size()-3;j<arraylist.size();j++){//获取牌的编号int remainningId = arraylist.get(j);//根据牌的编号找到牌String remainingCard = map.get(remainningId);//将牌添加到ArrayList中remaining.add(remainingCard);}System.out.println("底牌:"+remaining);//6.给三个玩家手里的牌排序Collections.sort(person1Id);Collections.sort(person2Id);Collections.sort(person3Id);ArrayList<String> person1Card = new ArrayList<String>();ArrayList<String> person2Card = new ArrayList<String>();ArrayList<String> person3Card = new ArrayList<String>();//7.看牌//根据牌的编号从Map集合中获取他的牌for (int i:person1Id) {String value = map.get(i);person1Card.add(value);}for (int i:person2Id) {String value = map.get(i);person2Card.add(value);}for (int i:person3Id) {String value = map.get(i);person3Card.add(value);}System.out.println(person1Card);System.out.println(person2Card);System.out.println(person3Card);} }
结果为: