模拟斗地主,完成洗牌发牌操作
Iterator迭代器
Iterator接口
在程序开发中,经常需要遍历集合中的所有元素。针对这种需求,JDK专门提供了一个接口java.util.Iterator。Iterator接口也是Java集合中的一员,但它与Collection、Map接口有所不同,Collection接口与Map接口主要用于存储元素,而Iterator主要用于迭代访问(即遍历)Collection中的元素,因此Iterator对象也被称为迭代器。
迭代
即Collection集合元素的通用获取方式。在取元素之前先要判断集合中有没有元素,如果有,就把这个元素取出来,继续在判断,如果还有就再取出出来。一直把集合中的所有元素全部取出。这种取出方式专业术语称为迭代。
Iterator接口的常用方法如下:
- public E next():返回迭代的下一个元素。
- public boolean hasNext():如果仍有元素可以迭代,则返回 true。
迭代器的实现原理
- 遍历集合时,首先通过调用t集合的iterator()方法获得迭代器对象,然后使用hashNext()方法判断集合中是否存在下一个元素,如果存在,则调用next()方法将元素取出,否则说明已到达了集合末尾,停止遍历元素。
- Iterator迭代器对象在遍历集合时,内部采用指针的方式来跟踪集合中的元素,为了让初学者能更好地理解迭代器的工作原理,接下来通过一个图例来演示Iterator对象迭代元素的过程:
增强for
- 增强for循环(也称for each循环)是高级for循环,专门用来遍历数组和集合的。它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。
- 格式:
for(元素的数据类型 变量 : Collection集合or数组){
** 按照斗地主的规则,完成洗牌发牌的动作。 具体规则:
使用54张牌打乱顺序,三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。**
实现代码
public class Poker {
public static void main(String[] args) {
/**
* 1:准备牌
*/
//创建牌的完成体
ArrayList<String> pokerBox=new ArrayList<>();
//创建牌的数字
ArrayList<String> nums=new ArrayList<>();
//创建牌的花色
ArrayList<String> colors=new ArrayList<>();
//添加数字2-10
for(int i=2;i<11;i++){
nums.add(i+"");
}
//添加数字A,J,Q,K
nums.add("A");
nums.add("J");
nums.add("Q");
nums.add("K");
//给花色数组添加元素
colors.add("红桃");
colors.add("方块");
colors.add("黑桃");
colors.add("梅花");
//创造牌 把数字和花色拼接起来
//增强for循环
for (String color:colors){
for (String num:nums){
String card=color+num;
pokerBox.add(card);
}
}
//添加大小王
pokerBox.add("大王");
pokerBox.add("小王");
/**
* 洗牌
* 把牌打乱
*/
Collections.shuffle(pokerBox);
/**
* 发牌
*/
//创建三个玩家,和底牌集合
ArrayList<String> player1=new ArrayList<>();
ArrayList<String> player2=new ArrayList<>();
ArrayList<String> player3=new ArrayList<>();
ArrayList<String> dipai=new ArrayList<>();
//遍历
for(int i=0;i<pokerBox.size();i++){
//获取牌面
String card=pokerBox.get(i);
//把牌分给三个玩家
if(i<51){
if (i%3==0){
player1.add(card);
}else if (i%3==1){
player2.add(card);
}else {
player3.add(card);
}
}else { //添加三张底牌到底牌集合
dipai.add(card);
}
}
/**
* 看牌
*/
System.out.println("玩家1:"+player1);
System.out.println("玩家2:"+player2);
System.out.println("玩家3:"+player3);
System.out.println("底 牌:"+dipai);
}
}