集合斗地主案例
思路:
-
1.首先准备牌
两个String数组,存花色、数字;一个ArrayList集合存储牌堆
(1)通过增强for循环来组合花色和数字构成四色卡牌
(2)再增加大小王卡牌
-
2.洗牌
通过Collections工具类的shuffle()方法来随机排列牌堆,每次排列不同
shuffle(List<?> list)
使用默认的随机源随机排列指定的列表。
-
3.发牌
定义3个玩家ArrarList集合,和一个底牌集合;因为增强for 循环没有索引,所以需要需要for循环遍历集合。通过集合的get方法获取手牌
(1)当i>=51时,为剩余底牌数;
(2)当i%3==0时,为1号玩家牌数;
(3)当i%3==1时,为2号玩家牌数;
(3)当i%3==2时,为3号玩家牌数;
-
4.看牌
打印数组
package setclass;
import java.util.ArrayList;
import java.util.Collections;
public class DouDiZhu {
public static void main(String[] args) {
//1.准备牌,两个String数组,存花色、数字,一个ArrayList集合存储牌
ArrayList<String> poker=new ArrayList<>();
String[] colors={"♠","♡","♣","♢"};
String[] numbers={"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
//将花色和数字组合成牌堆
for(String number:numbers){
for(String color:colors){
poker.add(color+number);
}
}
poker.add("大王");
poker.add("小王");
System.out.println(poker);
//2.洗牌
Collections.shuffle(poker);
//3.发牌
ArrayList<String> player01=new ArrayList<>();//3个玩家
ArrayList<String> player02=new ArrayList<>();
ArrayList<String> player03=new ArrayList<>();
ArrayList<String> diPai=new ArrayList<>();//底牌
for (int i = 0; i < poker.size(); i++) {
String p=poker.get(i);//获取牌
if (i>=51){//底牌
diPai.add(p);
}else if(i%3==0){
player01.add(p);
}else if(i%3==1){
player02.add(p);
}else if(i%3==2){
player03.add(p);
}
}
//4.看牌
System.out.println("张三:"+player01);
System.out.println("李四:"+player02);
System.out.println("王五:"+player03);
System.out.println("底牌:"+diPai);
}
}
运行结果:
[♠2, ♡2, ♣2, ♢2, ♠A, ♡A, ♣A, ♢A, ♠K, ♡K, ♣K, ♢K, ♠Q, ♡Q, ♣Q, ♢Q, ♠J, ♡J, ♣J, ♢J, ♠10, ♡10, ♣10, ♢10, ♠9, ♡9, ♣9, ♢9, ♠8, ♡8, ♣8, ♢8, ♠7, ♡7, ♣7, ♢7, ♠6, ♡6, ♣6, ♢6, ♠5, ♡5, ♣5, ♢5, ♠4, ♡4, ♣4, ♢4, ♠3, ♡3, ♣3, ♢3, 大王, 小王]
张三:[♢K, ♡5, ♣J, ♠A, 大王, ♢2, ♡9, ♠K, ♢5, ♡7, ♣7, ♢10, ♣6, ♣K, ♣A, ♡J, ♠6]
李四:[♢9, ♡10, ♣2, ♢J, ♢7, ♢6, ♢8, ♣3, ♠Q, ♠7, ♠J, ♡K, ♣5, ♡3, ♣4, ♢4, ♠2]
王五:[♢Q, ♠4, ♠5, ♣Q, ♠8, ♡6, ♢A, ♠9, ♡2, ♣8, ♠3, ♣10, ♡4, ♡8, ♣9, ♡Q, ♡A]
底牌:[♠10, ♢3, 小王]