使用java对一副扑克牌建模
本文实例为大家分享了java对一副扑克牌建模的具体代码,供大家参考,具体内容如下
第一步:使用枚举法对一副扑克牌(52张牌,不包括大小王)进行建模:一副扑克牌共有四种花色分别是:黑桃,方块,梅花,红心;而每种花色的牌一共有13张;
importjava.util.EnumMap; importjava.util.EnumSet; publicclassEnumSetTest{ //枚举类型Suit enumSuit{"HEART","SPADE","DIAMOND","CLUB"}; enumRank{"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; }
第二步:创建2个枚举类型包含这两类实例。
每张扑克牌Card对象都会有这两个属性,创建一个带有这两个枚举类型属性的类Card
`packagecom.Cards.model; packagecom.Cards.model; /** *@authorRockLee *@version2012-10-2116:51:49 *@seeCardSetting.java *@proposalBuildAClassContainAlltheinfoforONECardinthepoker *@fix2012-12-1213:01:04 **/ publicclassCard { privateStringcolor=null; privateStringnum=null; privatebooleanvisible=false; privatebooleanred=false; publicCard(Stringcolor,Stringnum) { this.color=color; this.num=num; //ifthecolorisdiamondorheart,thenredistrue,elsefalse if(color.equals(CardSetting.COLOR[CardSetting.INDEX_HEART]) ||color.equals(CardSetting.COLOR[CardSetting.INDEX_DIAMOND])) this.red=true; else this.red=false; } /* *若花色,牌面大小相同,则认为是同一张牌 **/ publicbooleanequals(Objectobj) { CardanotherCard=(Card)obj; returnthis.color.equals((anotherCard.color)) &&this.num.equals(anotherCard.num); } publicvoidsetVisiable(booleanvisible) { this.visible=visible; } publicbooleanisVisible() { returnvisible; } publicbooleanisRed() { returnred; } publicStringtoString() { if(this==null) return"EMPTY"; else { if(this.isVisible()) { return(color+""+num+""); } else return"███"; } } publicStringgetColor() { returncolor; } /*以数字的方式,返回牌面的大小*/ publicintgetNum() { charch=num.charAt(0); switch(ch) { case'A': return1; case'J': return11; case'Q': return12; case'K': return13; default: returnInteger.parseInt(num); } } /*以String的方式,返回牌面的大小*/ publicStringgetNumInString() { returnnum; } }
第三步:初始化扑克牌排列顺序
publicclassCardHeap { privateVectorvector=null; publicCardHeap() { this.initialize(); } /*初始化13*4=52张牌*/ publicvoidinitialize() { vector=newVector (); Cardtmp=null; for(inti=0;i<13;i++)//13cardsinColorHeart { tmp=newCard(CardSetting.COLOR[CardSetting.INDEX_HEART],CardSetting.NUM[i]); tmp.setVisiable(false); vector.add(tmp); } for(inti=0;i<13;i++)//13cardsinColorSPADE { tmp=newCard(CardSetting.COLOR[CardSetting.INDEX_SPADE],CardSetting.NUM[i]); tmp.setVisiable(false); vector.add(tmp); } for(inti=0;i<13;i++)//13cardsinColorDIAMOND { tmp=newCard(CardSetting.COLOR[CardSetting.INDEX_DIAMOND],CardSetting.NUM[i]); tmp.setVisiable(false); vector.add(tmp); } for(inti=0;i<13;i++)//13cardsinColorCLUB { tmp=newCard(CardSetting.COLOR[CardSetting.INDEX_CLUB],CardSetting.NUM[i]); tmp.setVisiable(false); vector.add(tmp); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。