java集合框架:斗地主案例(有序版)
斗地主案例(有序版)
- 规则:使用54张牌打乱顺序,三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌
案例分析
-
准备牌:
-
特殊牌:大王、小王
-
其他52张牌:
List<String> colors,存储4中花色♠,♥,♣,♦List<String> numbers,存储13个序号:2,A,K……3
-
循环嵌套遍历两个数组/集合,组装52张牌
-
将组装好的牌放到一个Map容器中,单独一个List集合存储牌的索引
Map<Integer,String>: key->牌的索引,value->组装好的牌

-
-
洗牌:使用集合工具类
Collectons的方法把牌的索引集合顺序打乱:-
static void shuffle(List<?> list)使用默认随机源对指定列表进行置换 -
会随机的打乱集合中的元素的顺序

-
-
发牌
- 要求:1人17张牌,剩余三张作为底牌,一人一张轮流发牌:集合的索引%3
- 索引%3:有三个值(0,1,2)
- 定义四个集合,存储3个玩家的牌和底牌
- 索引≥51,改底牌发牌
- 要求:1人17张牌,剩余三张作为底牌,一人一张轮流发牌:集合的索引%3
-
排序:把每位玩家手中的牌进行排序
- 使用集合工具类
Collectons的方法: soft(List)
- 使用集合工具类
-
看牌:可以使用查表方法
- 遍历玩家和底牌的List,获取到Map集合的key,通过key找到value值
代码实现
public class Demo01 {
public static void main(String[] args){
//1,准备牌
//Map集合,存储牌的索引和组装好的牌
HashMap<Integer,String> poker=new HashMap<>();
//存储牌的索引
ArrayList<Integer> pokerIndex=new ArrayList<>();
//存储花色和牌的序号
String[] colors={"♠","♥","♣","♦"};
String[] numbers={"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
//先存大王小王
int index=0;
poker.put(index,"大王");
pokerIndex.add(index);
index++;
poker.put(index,"小王");
pokerIndex.add(index);
index++;
//循环嵌套遍历两个数组,组装52张牌
for (String number:numbers){
for (String color:colors){
poker.put(index,color+number);
pokerIndex.add(index);
index++;
}
}
//2.洗牌 打乱牌的索引
Collections.shuffle(pokerIndex);
//3.发牌
//4个集合存储玩家的牌和底牌
ArrayList<Integer> player1=new ArrayList<>();
ArrayList<Integer> player2=new ArrayList<>();
ArrayList<Integer> player3=new ArrayList<>();
ArrayList<Integer> diPai=new ArrayList<>();
for (int i = 0; i < pokerIndex.size(); i++) {
Integer p = pokerIndex.get(i);
if(i>=51)
diPai.add(p);
else if (i % 3 == 0) {
player1.add(p);
}else if (i % 3 == 1) {
player2.add(p);
}else if (i % 3 == 2) {
player3.add(p);
}
}
//4.排序
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
Collections.sort(diPai);
//5.看牌,定义一个方法,提高代码的复用性
lookPoker("玩家1",poker,player1);
lookPoker("玩家2",poker,player2);
lookPoker("玩家3",poker,player3);
lookPoker("底牌",poker,diPai);
}
/*
定义一个看牌的方法,提高代码的复用性
参数:
String name:玩家名称
HashMap<Integer,String> poker:存储牌的poker集合
ArrayList<Integer> list :存储玩家和底牌的list集合
查表法:
遍历玩家或者底牌集合,获取牌的索引
使用牌的索引,去Map集合中,找到对应的牌
*/
public static void lookPoker(String name,HashMap<Integer,String> poker,ArrayList<Integer> list){
//输出玩家姓名
System.out.print(name+" ");
//遍历玩家或者底牌集合,获取牌的索引
for (Integer key:list){
//使用牌的索引,去Map集合中找到对应的牌
String value = poker.get(key);
System.out.print(value+", ");
}
System.out.println();//换行
}
}
//结果
//玩家1 小王, ♠A, ♣A, ♠K, ♠Q, ♦Q, ♠J, ♥J, ♠9, ♦8, ♥7, ♠6, ♥6, ♠5, ♥4, ♠3, ♣3,
//玩家2 ♠2, ♥2, ♣2, ♣K, ♦K, ♥Q, ♣Q, ♦10, ♥9, ♣9, ♥8, ♣8, ♠7, ♦7, ♣6, ♣5, ♦3,
//玩家3 ♦2, ♥A, ♦A, ♥K, ♣J, ♠10, ♥10, ♣10, ♦9, ♠8, ♣7, ♦6, ♥5, ♦5, ♠4, ♦4, ♥3,
//底牌 大王, ♦J, ♣4,

浙公网安备 33010602011771号