package com.itheima.six;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
集合模拟斗地主案例
实现步骤:
一.准备牌
1.创建List集合对象pokers,代表牌盒,用来存储54张扑克
2.创建List集合对象colors,代表花色,用来存储所有的花色
3.向代表花色集合colors中存储所有的花色
4.创建List集合对象nums,代表数字,用来存储所有的数字
5.向代表数字集合nums中存储所有的数字
6.循环嵌套遍历存储数字和花色的List集合nums和colors
7.循环内部拼接一张扑克,保存String变量poker中
8.循环内部把当前拼接的扑克poker添加到牌盒pokers中
9.循环外部向牌盒中添加小王和大王
10.输出牌盒
二.洗牌(打乱牌盒pokers中的元素的顺序)
java.util.Collections集合工具类中提供静态方法,完成打乱List集合元素顺序
public static void shuffle(List<?> list): 打乱方法参数List集合对象中的元素的顺序
三.发牌
1.创建四个List集合对象p1,p2,p3,bottom,分别代表三个玩家和一个底牌
2.遍历牌盒pokers(方式一: for + get(索引) 方式二: 迭代器 方式三: 增强for)
注意: 因为要根据索引来决定改扑克到底发给哪个具体的玩家,所以只能使用方式一遍历,因为方式二/三都是看不到索引的
2.1 获取当前扑克,保存String变量poker中
2.2 判断当前扑克的编号(索引) > 50 不参与发牌,直接留作底牌
2.3 判断当前扑克的编号(索引) <= 50 参与发牌,根据编号%3的结果发给不同的玩家
四.看牌
思考1:
每个玩家是一个对象,有玩家名称,玩家手里拿到的多张牌(List集合中)
定义玩家Player类,优化此代码
思考2:
在思考1的基础上,分别把准备牌,洗牌,发牌,看牌定义成四个方法
*/
public class Demo05PokerGame {
public static void main(String[] args) {
//一.准备牌
//1.创建List集合对象pokers,代表牌盒,用来存储54张扑克
List<String> pokers = new ArrayList<>();
//2.创建List集合对象colors,代表花色,用来存储所有的花色
List<String> colors = new ArrayList<>();
//3.向代表花色集合colors中存储所有的花色
Collections.addAll(colors, "♥", "♠", "♦", "♣");
//4.创建List集合对象nums,代表数字,用来存储所有的数字
List<String> nums = new ArrayList<>();
//5.向代表数字集合nums中存储所有的数字
Collections.addAll(nums, "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2");
//6.循环嵌套遍历存储数字和花色的List集合nums和colors
for (String num : nums) {//遍历存储数字的集合
for (String color : colors) {//遍历存储花色的集合
//7.循环内部拼接一张扑克,保存String变量poker中
String poker = color + num;
//8.循环内部把当前拼接的扑克poker添加到牌盒pokers中
pokers.add(poker);
}
}
//9.循环外部向牌盒中添加小王和大王
pokers.add("小王");
pokers.add("大王");
//10.输出牌盒
//System.out.println(pokers);
//System.out.println(pokers.size());
/*
二.洗牌(打乱牌盒pokers中的元素的顺序)
java.util.Collections集合工具类中提供静态方法,完成打乱List集合元素顺序
public static void shuffle(List<?> list): 打乱方法参数List集合对象中的元素的顺序
*/
Collections.shuffle(pokers);
//打印洗牌后的牌盒内容
//System.out.println(pokers);
//System.out.println(pokers.size());
//三.发牌
//1.创建四个List集合对象p1,p2,p3,bottom,分别代表三个玩家和一个底牌
List<String> p1 = new ArrayList<>();//玩家一
List<String> p2 = new ArrayList<>();//玩家二
List<String> p3 = new ArrayList<>();//玩家三
List<String> bottom = new ArrayList<>();//底牌
//2.遍历牌盒pokers(方式一: for + get(索引) 方式二: 迭代器 方式三: 增强for)
for (int i = 0; i < pokers.size(); i++) {
//2.1 获取当前扑克,保存String变量poker中
String poker = pokers.get(i);
//2.2 判断当前扑克的编号(索引) > 50 不参与发牌
if (i > 50) {
//直接留作底牌
bottom.add(poker);
} else {
//2.3 判断当前扑克的编号(索引) <= 50 参与发牌,根据编号%3的结果发给不同的玩家
if (i % 3 == 0) {
//发给玩家一
p1.add(poker);
} else if (i % 3 == 1) {
//发给玩家二
p2.add(poker);
} else {
//发给玩家三
p3.add(poker);
}
}
}
//四.看牌
System.out.println("玩家一: " + p1);
System.out.println("玩家二: " + p2);
System.out.println("玩家三: " + p3);
System.out.println("底牌: " + bottom);
}
}