Files
javaSE-260914/s-day04/src/com/inmind/map01/Test09.java
T
2026-10-15 16:06:38 +08:00

85 lines
3.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.inmind.map01;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/*
案例介绍
按照斗地主的规则,完成洗牌发牌的动作。(洗牌打乱Collections.shuffle()只能打乱list集合)
具体规则:
组装54张扑克牌将54张牌顺序打乱
三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。(创建4个集合,3个玩家,1个底牌)
查看三人各自手中的牌(按照牌的大小排序)、底牌【自然排序或者比较器Comparable Comparator】
规则:手中扑克牌从大到小的摆放顺序:大王,小王,2,A,K,Q,J,10,9,8,7,6,5,4,3【打印牌即可】
54键----“大王”
*/
public class Test09 {
public static void main(String[] args) {
String[] nums = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
String[] colors = {"♦", "♣", "♥", "♠"};
//定义一个集合存放我们牌对象
ArrayList<Poker> pokers = new ArrayList<>();
int index = 1;
for (String num : nums) {
for (String color : colors) {
String pokerName = color+num;
pokers.add(new Poker(pokerName,index++));
}
}
pokers.add(new Poker("小王", index++));
pokers.add(new Poker("大王", index++));
System.out.println(pokers);
//洗牌
Collections.shuffle(pokers);
System.out.println(pokers);
//(创建4个集合,3个玩家,1个底牌)
ArrayList<Poker> play1 = new ArrayList<>();
ArrayList<Poker> play2 = new ArrayList<>();
ArrayList<Poker> play3 = new ArrayList<>();
ArrayList<Poker> dipai = new ArrayList<>();
/*
玩家1 0 3 6 %3 = 0
玩家2 1 4 7 %3 = 1
玩家3 2 5 8 %3 = 2
*/
for (int i = 0; i < pokers.size(); i++) {
if (i > 50) {
dipai.add(pokers.get(i));
} else {
switch (i%3) {
case 0:
play1.add(pokers.get(i));
break;
case 1:
play2.add(pokers.get(i));
break;
case 2:
play3.add(pokers.get(i));
break;
}
}
}
//看牌之前先排序
//可以使用比较器替代自然排序
Comparator<Poker> pokerComparator = new Comparator<Poker>() {
@Override
public int compare(Poker o1, Poker o2) {
return o2.index - o1.index;
}
};
Collections.sort(play1,pokerComparator);
Collections.sort(play2,pokerComparator);
Collections.sort(play3,pokerComparator);
Collections.sort(dipai,pokerComparator);
System.out.println("玩家1:"+play1);
System.out.println("玩家2:"+play2);
System.out.println("玩家3:"+play3);
System.out.println("底牌:"+dipai);
}
}