斗地主相信大家都玩过,怎么来实现一个简单的斗地主功能呢?
思路:
我们可以利用双列集合来实现它。
首先把特殊牌大小王创建出来,然后创建一个集合来存储花色,另一个集合来存储A-K的牌。
利用循环来讲花色与牌组合起来。
然后打乱牌的顺序也就是洗牌过程。
再创建三个集合,分别代表三个玩家来存储手牌,用一个集合来存储底牌。
图解:
实现代码:
public static void main(String[] args) {
//1.准备牌
//创建一个Map集合,存储牌的索引和组装好的牌
HashMap
//创建一个List集合,存储牌的索引
ArrayList pokerIndex = new ArrayList<>();
//定义两个集合,存储花色和牌的序号
String[] Colors = {“♠”,“♥”,“♣”,“♦”};
String[] Numbers = {“A”,“2”,“3”,“4”,“5”,“6”,“7”,“8”,“9”,“10”,“J”,“Q”,“K”};
//把大王和小王存储到集合中
//定义一个牌的索引
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(List)
*/
Collections.shuffle(pokerIndex);
// System.out.println(pokerIndex);
/*
3.发牌
*/
//定义4个集合,存储玩家牌的索引,和底牌的索引
ArrayList player01 = new ArrayList<>();
ArrayList player02 = new ArrayList<>();
ArrayList player03 = new ArrayList<>();
ArrayList diPai = new ArrayList<>();
//遍历存储牌索引的List集合,获取每一个牌的索引
for (int i = 0; i =51){
//给底牌发牌
diPai.add(in);
}else if(i%3==0){
//给玩家1发牌
player01.add(in);
}else if(i%3==1){
//给玩家2发牌
player02.add(in);
}else if(i%3==2){
//给玩家3发牌
player03.add(in);
}
}
/*
4.排序
使用Collections中的方法sort(List)
默认是升序排序
*/
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(diPai);
/*
5.看牌
调用看牌的方法
*/
lookPoker("players1",poker,player01);
lookPoker("players2",poker,player02);
lookPoker("players3",poker,player03);
lookPoker("底牌",poker,diPai);
}
/*
定义一个看牌的方法,提高代码的复用性
参数:
String name:玩家名称
HashMap poker:存储牌的poker集合
ArrayList list:存储玩家和底牌的List集合
查表法:
遍历玩家或者底牌集合,获取牌的索引
使用牌的索引,去Map集合中,找到对应的牌
*/
public static void lookPoker(String name,HashMap poker,ArrayList list){
//输出玩家名称,不换行
System.out.print(name+":");
//遍历玩家或者底牌集合,获取牌的索引
for (Integer key : list) {
//使用牌的索引,去Map集合中,找到对应的牌
String value = poker.get(key);
System.out.print(value+" ");
}
System.out.println();//打印完每一个玩家的牌,换行
}
运行结果: