一分析:
1:创建扑克牌
CreatePlayingCards();
2:洗牌
AntomaticLicensing();
3:给三名玩家进行发牌
DealCards();
采用集合:
HashMap<Integer,String>map;
ArrayListcards
相关API信息:
Collections.shuffle(cards);
-
Collections.sort(user);
-
二:代码详情
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class PlayingCard {
//创建扑克牌
private static HashMap<Integer,String>map;
//洗牌编号
private static ArrayList<Integer>cards;
public static void main(String[] args) {
//创建扑克牌
CreatePlayingCards();
//洗牌
AntomaticLicensing();
//给三名玩家进行发牌,并打印发牌情况
DealCards();
}
//【1】创建扑克牌
private static void CreatePlayingCards(){
//定义花色和数字
String [] color={"♠","♥","♣","♦"};
String[]nums={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
//将花色和数字组合
int index=0;
map=new HashMap<Integer,String>();
for(String numStr:nums){
for(String colorStr:color){
map.put(index++, colorStr+numStr);
}
}
//加入大小王
map.put(index, "小王");
map.put(index+1, "大王");
}
//【2】洗牌
private static void AntomaticLicensing() {
//定义一个集合,用来表示一副54张牌的编号,ArrayList里边为0-53的数的编号
cards=new ArrayList<Integer>();
for(int i=0;i<=53;i++){
cards.add(i);
}
//洗牌,使用Collections工具类的Shuffle()类
Collections.shuffle(cards);
}
//【3】给三名玩家发牌,并打印发牌情况
private static void DealCards() {
//创建三个玩家和底牌
ArrayList<Integer>iplayer1=new ArrayList<Integer>();
ArrayList<Integer>iplayer2=new ArrayList<Integer>();
ArrayList<Integer>iplayer3=new ArrayList<Integer>();
//底牌
ArrayList<Integer>iSecretCards=new ArrayList<Integer>();
//遍历这幅洗好的牌,遍历过程中,将牌发到三个玩家和底牌中
//这里采用的算法是 底牌>=51的数字 小王:i%3==0 小强:i%3==1 卢本伟:除了上面情况之外的牌
for (int i = 0; i < cards.size(); i++) {
if (i>=51) {
iSecretCards.add(cards.get(i));
}else if (i%3==0) {
//与3取余为0的发给玩家1
iplayer1.add(cards.get(i));
}else if (i%3==1) {
iplayer2.add(cards.get(i));
}else {
iplayer3.add(cards.get(i));
}
}
//打印最后结果
System.out.print("小王:");
Ponint(iplayer1);
System.out.print("小强:");
Ponint(iplayer2);
System.out.print("卢本伟:");
Ponint(iplayer3);
System.out.print("底牌:");
Ponint(iSecretCards);
}
//打印
public static void Ponint(ArrayList<Integer> user){
Collections.sort(user);
for(int count:user){
System.out.print(" "+map.get(count)+" ");
}
System.out.println("");
}
}