用java语言模拟斗地主的洗牌和发牌
程序员文章站
2022-07-12 09:09:09
...
斗地主的步骤
1.准备一个Map<Integer,String>
2.准备一副牌<54个编号>
3.洗牌shuffle
4.依次给三个集合发牌,留三张给底牌
5.对每个集合进行排序
6.以键找值,通过map集合
//记得导包
public static void main(String[] args) {
// 1.准备一个Map<Integer,String>
HashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
//数据
String[] colors = {"♥","♠","♣","♦"};
String[] nums = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
int index = 1;
//先遍历数字
for (String num : nums) {
//再遍历花色
for (String color : colors) {
//组合牌
String card = color+num;
//添加到map中
map.put(index,card);
index++;
}
}
//单独添加大小王
map.put(index,"小S");
index++;
map.put(index,"大S");
// 2.准备一副牌(54个编号)
ArrayList<Integer> cards = new ArrayList<Integer>();
for (int i = 1; i < 55; i++) {
cards.add(i);
}
// 3.洗牌shuffle
Collections.shuffle(cards);
// 4.依次给三个集合发牌,留三张给底牌
ArrayList<Integer> p1 = new ArrayList<Integer>();
ArrayList<Integer> p2 = new ArrayList<Integer>();
ArrayList<Integer> p3 = new ArrayList<Integer>();
ArrayList<Integer> dp = new ArrayList<Integer>();
//轮流发牌
for (int i = 0; i < cards.size() - 3; i++) {
//取出牌
Integer card = cards.get(i);
//这个card应该给谁??
if (i % 3 == 0) {
p1.add(card);
} else if (i % 3 == 1) {
p2.add(card);
} else {
p3.add(card);
}
}
//单独给底牌留三张
Integer last1 = cards.get(cards.size() - 1);
Integer last2 = cards.get(cards.size() - 2);
Integer last3 = cards.get(cards.size() - 3);
dp.add(last1);
dp.add(last2);
dp.add(last3);
// 5.对每个集合进行排序
Collections.sort(p1);
Collections.sort(p2);
Collections.sort(p3);
Collections.sort(dp);
// 6.以键找值,通过map集合
// 7.看牌
lookCards(p1,map);
lookCards(p2,map);
lookCards(p3,map);
lookCards(dp,map);
}
private static void lookCards(ArrayList<Integer> cards, HashMap<Integer, String> map) {
//遍历编号
for (Integer cardId : cards) {
//以键找值
String card = map.get(cardId);
System.out.print(card+" ");
}
System.out.println();
}