模拟斗地主洗牌和发牌(无序版)
package org.westos.demo3;
import java.util.ArrayList;
import java.util.Collections;
public class MyTest {
public static void main(String[] args) {
// A:
// 案例演示:
// 模拟斗地主洗牌和发牌,牌没有排序
//1.创建一个牌盒子
ArrayList<String> pokerBox = new ArrayList<>();
//2.生成54张牌放进牌盒子
String[] colors={"♣","♠","♦","♥"};
String[] nums={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for (String color : colors) {
for (String num : nums) {
String poker = color.concat(num);
pokerBox.add(poker);
}
}
//手动添加大小王
pokerBox.add("🎅");
pokerBox.add("🤶");
//洗牌
Collections.shuffle(pokerBox);
Collections.shuffle(pokerBox);
Collections.shuffle(pokerBox);
// System.out.println(pokerBox);
//发牌:
//三个人有一副底牌 对应4个集合
ArrayList<String> 高进 = new ArrayList<>();
ArrayList<String> 星仔 = new ArrayList<>();
ArrayList<String> 刀仔 = new ArrayList<>();
ArrayList<String> 底牌 = new ArrayList<>();
// List<String> 高进2 = pokerBox.subList(0, 17);
//一人一张的发
/*
*
* 高进 0 3 6 9 12 %3=0
星仔 1 4 7 10 13 %3=1
刀仔 2 5 8 11 14 %3=2
*
*
* */
for (int i = 0; i < pokerBox.size(); i++) {
if(i>=pokerBox.size()-3){
底牌.add(pokerBox.get(i));
}else if(i%3==0){
高进.add(pokerBox.get(i));
}else if(i%3==1){
星仔.add(pokerBox.get(i));
}else{
刀仔.add(pokerBox.get(i));
}
}
//看牌
lookPoker("高进",高进);
lookPoker("星仔",星仔);
lookPoker("刀仔",刀仔);
lookPoker("底牌",底牌);
}
private static void lookPoker(String name, ArrayList<String> pokers) {
System.out.println(name);
for (String poker : pokers) {
System.out.print(poker+"\t");
}
System.out.println();
}
}
模拟斗地主洗牌和发牌(有序版)
package com.xawl.demo3;
import java.util.*;
import java.util.function.Consumer;
/**
* @Author:liger
* @Description:爱学Java
*/
public class Test {
public static void main(String[] args) {
//定义双列集合存储牌的索引和值
HashMap<Integer, String> pokerBox = new HashMap<>();
//定义集合存储索引
ArrayList<Integer> indexs = new ArrayList<>();
int index=0;
String[] colors={"♥","♣","♦","♠"};
String[] pokers={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for (String color : colors) {
for (String poker : pokers) {
pokerBox.put(index,color.concat(poker));
indexs.add(index);
index++;
}
}
//手动添加大小王
pokerBox.put(index,"🤴");
indexs.add(index);
index++;
pokerBox.put(index,"👸");
indexs.add(index);
//打乱牌顺序
Collections.shuffle(indexs);
//给指定人发牌
TreeSet<Integer> 高进 = new TreeSet<>();
TreeSet<Integer> 刀仔 = new TreeSet<>();
TreeSet<Integer> 星仔= new TreeSet<>();
TreeSet<Integer> 底牌 = new TreeSet<>();
for (int i = 0; i < indexs.size(); i++) {
if (i>=indexs.size()-3){
底牌.add(indexs.get(i));
}else if(i%3==0){
高进.add(indexs.get(i));
}else if(i%3==1){
刀仔.add(indexs.get(i));
}else{
星仔.add(indexs.get(i));
}
}
//看牌
lookPoker("高进",高进,pokerBox);
lookPoker("刀仔",刀仔,pokerBox);
lookPoker("星仔",星仔,pokerBox);
lookPoker("底牌",底牌,pokerBox);
}
private static void lookPoker(String name, TreeSet<Integer> set, HashMap<Integer, String> pokerBox) {
System.out.println(name);
set.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.print(pokerBox.get(integer)+" ");
}
});
System.out.println();
}
}