Java集合框架(5)--简单的扑克牌游戏练习(1)
程序员文章站
2022-04-02 17:45:31
...
说明:1.文件包含Card类,Color类,CardList类,Player类以及PraticeDemo类
2.主要实现两个玩家扑克牌比大小的功能
运行结果:
Card:纸牌类
package com.PraticeDemo;
/*
* Card:纸牌类
* 1.实现了Comparator接口用来比较纸牌大小*/
public class Card implements Comparable<Card>{
private int priority;//大小
private String name;//牌号
private Color color;//花色
public Card(int priority,String name,Color color) {
// TODO Auto-generated constructor stub
this.priority = priority;
this.name = name;
this.color = color;
}
public String getName() {
return this.color.getName()+this.name;
}
public Color getColor() {
return color;
}
public int getPriority(){
return this.priority;
}
//重写compareTo方法
@Override
public int compareTo(Card o) {
// TODO Auto-generated method stub
if(this.priority>o.priority) return 1;//当前扑克大
else
if(this.priority==o.priority){//扑克等大比花色
if(this.color.getPriority()>o.getColor().getPriority()) return 1;//花色大
else //花色相等
if(this.color.getPriority()==o.getColor().getPriority()) return 0;
else //花色小
return -1;
}
else return -1;//当前扑克小
}
}
Color:枚举四种花色
package com.PraticeDemo;
/*
* Color:枚举扑克牌四种花色,并设定名称以及大小
* */
public enum Color {
HX("红心",3),FP("方片",1),HT("黑桃",4),MH("梅花",2);
private String name;
private int priority;//花色的优先级大小,HT>HX>MH>FP
private Color(String name,int priority) {
// TODO Auto-generated constructor stub
this.name = name;
this.priority = priority;
}
public String getName(){
return this.name;
}
public int getPriority() {
return priority;
}
}
CardList:纸牌集合
package com.PraticeDemo;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/*
* CardList:扑克集合
* 1.CreatCard(),创建扑克牌
* 2.WashCard(),利用hashSet的无序性洗牌,感觉不太严谨,可以还有一个想法是用Random类实现随机发牌,没有写
* 3.printAll(),打印扑克*/
public class CardList {
List<Card> cards;
public CardList() {
// TOD{O Auto-generated constructor stub
cards = new ArrayList<Card>();
CreatCards();
}
//创建扑克
public void CreatCards(){
String name = null;
int priority;
for(int i=1;i<=13;i++){
priority = i;
if(i==1){
priority=14;
name = "A";
}
else if(i>1&&i<11) name = i+"";
else if(i==11) name = "J";
else if(i==12) name = "Q";
else if(i==13) name = "K";
//添加四种花色
cards.add(new Card(priority,name,Color.FP));
cards.add(new Card(priority,name,Color.HT));
cards.add(new Card(priority,name,Color.HX));
cards.add(new Card(priority,name,Color.MH));
}
}
//洗牌,利用hashSet的无序性洗牌
public Set<Card> WashCard(){
Set<Card> cards = new HashSet<Card>();
for(Card card:this.cards){
cards.add(card);
}
return cards;
}
//打印所有扑克
public void printAll(){
for(Card c:cards){
System.out.print(c.getName()+" ");
}
System.out.println();
}
// public static void main(String[] args) {
// CardList cd = new CardList();
// cd.CreatCards();
// cd.printAll();
// }
}
上一篇: ASP.NET MVC入门