模拟斗地主洗牌和发牌,牌没有排序
import java.util.ArrayList;
import java.util.Collections;
public class i {
/**
* *
* 模拟斗地主洗牌和发牌,牌没有排序
*
* 分析:
* 1,买一副扑克,其实就是自己创建一个集合对象,将扑克牌存储进去
* 2,洗牌
* 3,发牌
* 4,看牌
*/
public static void main(String[] args) {
//1,买一副扑克,其实就是自己创建一个集合对象,将扑克牌存储进去
String[] num = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] color = {"红桃","黑桃","方片","梅花"};
ArrayList puke = new ArrayList<>();
//拼接花色和数字
for(String s1 : color) {
for(String s2 : num) {
puke.add(s1.concat(s2)); //concat连接两个字符串
}
}
puke.add("小王");
puke.add("大王");
//2,洗牌
Collections.shuffle(puke);
//3,发牌
ArrayList frist = new ArrayList<>();
ArrayList second = new ArrayList<>();
ArrayList me = new ArrayList<>();
ArrayList dipai = new ArrayList<>();
for(int i = 0; i < puke.size(); i++) {
if(i >= puke.size() - 3) {
dipai.add(puke.get(i)); //将三张底牌存储在底牌集合中
} else if(i % 3 == 0) {
frist.add(puke.get(i));
} else if(i % 3 == 1) {
second.add(puke.get(i));
} else {
me.add(puke.get(i));
}
}
//4,看牌
System.out.println(frist);
System.out.println(second);
System.out.println(me);
System.out.println(dipai);
}
}
模拟斗地主洗牌和发牌并对牌进行排序的代码实现
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
public class j {
/**
* 模拟斗地主洗牌和发牌并对牌进行排序的代码实现
*
* 分析:
* 1,买一副扑克,其实就是自己创建一个集合对象,将扑克牌存储进去
* 2,洗牌
* 3,发牌
* 4,看牌
*/
public static void main(String[] args) {
//1,买一副扑克,其实就是自己创建一个集合对象,将扑克牌存储进去
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color = {"红桃","黑桃","方片","梅花"};
HashMap hm = new HashMap<>();//存储索引和扑克牌
ArrayList list = new ArrayList<>(); //存储索引
int index = 0;
//拼接扑克牌并索引和扑克牌存储在hm中
for(String s1 : num) { //获取数字
for(String s2 : color) { //获取颜色
hm.put(index, s2.concat(s1));
list.add(index); //将索引0到51添加到list集合中
index++;
}
}
//将小王添加到双列集合中
hm.put(index, "小王");
list.add(index); //将52索引添加到集合中
index++;
hm.put(index, "大王");
list.add(index); //将52索引添加到集合中
System.out.println(hm);
System.out.println(list);
//2,洗牌
Collections.shuffle(list);
//3,发牌
TreeSet frist = new TreeSet<>();
TreeSet second = new TreeSet<>();
TreeSet me = new TreeSet<>();
TreeSet dipai = new TreeSet<>();
//将各牌索引分别存储在TreeSet集合中
for(int i = 0; i < list.size(); i++) {
if(i >= list.size() - 3) {
dipai.add(list.get(i)); //将三张底牌存储在底牌集合中
}else if(i % 3 == 0) {
frist.add(list.get(i));
}else if(i % 3 == 1) {
second.add(list.get(i));
}else {
me.add(list.get(i));
}
}
//看牌
lookPoker(hm, frist, "frist");
lookPoker(hm, second, "second");
lookPoker(hm, me, "me");
lookPoker(hm, dipai, "底牌");
}
/*
* 看牌
* 1,返回值类型void
* 2,参数列表HashMap,TreeSet,String name
*/
public static void lookPoker(HashMap hm,TreeSet ts ,String name) {
System.out.print(name + "的牌是:");
for(Integer i : ts) { //i代表双列集合中的每一个键
System.out.print(hm.get(i) + " ");
}
System.out.println();
}
}