java中如何实现一副扑克牌洗牌的功能。如果无法书写完整的代码,可以用文字描述出自己的实现思路

2022-04-13 社会 66阅读
1.定义牌类
publicclassCard{
publicintid;//牌大小
publicStringnumber;//牌值名称
publicStringcolor;//花色
}

2.定义牌组,用ArrayList存放所有牌
ArrayListcardGroup=newArrayList();

3.定义花色枚举
publicstaticfinalString[]COLORS=newString[]{"方块","梅花","红桃","黑桃"};

4.定义牌值大小枚举
publicstaticfinaString[]CARDVALUES=newString[]{"A","1","2","3",
"4","5","6","7","8","9","10","J","Q","K","King_Small","King_Big"};

5.初始化牌组,这就是一副新牌,没切过,己经排好序的
publicvoidinitCardGroup(){
//加入A~K
for(inti=0;i<13;i++){
for(intj=0;j<4;j++){
//生成一张牌的对象
Cardcard=newCard();
card.id=i;
card.color=COLORS[j];
card.munber=CARDVALUES[i];
//将对象加入牌组
cardGroup.add(card);
}
}
//加入大小王
Cardcard_k1=newCard();
card_k1.id=13;
card_k1.color="King_Small";
card_k1.number="King_Small";
cardGroup.add(card_k1);
Cardcard_k2=newCard();
card_k2.id=14;
card_k2.color="King_big";
card_k2.number="King_big";
cardGroup.add(card_k2);

}

6.洗牌,将原牌组打乱,得到新的牌组
publicArrayListflushCardsGroup(ArrayListsrc){
ArrayListresult=newArrayList();
while(src.size>0){
intsize=src.size();
//以size为限,生成0~size之间的随机数
Randomr=newRandom();
intindex=r.nextInt(size);
//对index做个检查
if(index>0){index=0;}
if(index>size-1){index=size-1;}
//index就是捡出来的牌,加到新的数组中,从原来数组中删除
Cardcard=src.get(index);
result.add(card);
card.remove(index);
}
returnresult;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com