第四天:用数组方式写一个扑克牌案例(创建,洗牌,发牌)

根据以前老师讲过的方法创建一副扑克牌:

玩牌的规则需要用到线程,暂不讨论了

第一步:创建一张牌

public class Card {  //定义常量  public  static final String[] color={"红桃","黑桃","梅花","方块","King","Quee"};  public  static final String[] num={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};  //定义属性  private  int suit;  private  int rank;  //getset方法  public int getSuit() {   return suit;  }  public void setSuit(int suit) {   this.suit = suit;  }  public int getRank() {   return rank;  }  public void setRank(int rank) {   this.rank = rank;  }  //构造器  public Card() {   super();   // TODO Auto-generated constructor stub  }  public Card(int suit, int rank) {   super();   this.suit = suit;   this.rank = rank;  }    //重新hashcode,toString,equal  @Override  public int hashCode() {   final int prime = 31;   int result = 1;   result = prime * result + rank;   result = prime * result + suit;   return result;  }  @Override  public boolean equals(Object obj) {   if (this == obj)    return true;   if (obj == null)    return false;   if (getClass() != obj.getClass())    return false;   Card other = (Card) obj;   if (rank != other.rank)    return false;   if (suit != other.suit)    return false;   return true;  }  @Override  public String toString() {   return  suit<4?color[suit]+""+num[rank]:color[suit] ;  } }

第二步   创建一副牌


public class Cards extends Card{
	//创建牌并且洗牌的方法
	public static Card[] createCards(){
		Random r=new Random();
		Card[] cards=new Card[54];
		int index = 0;
		Card card=null;
		for(int i=0;i<13;i++){
			cards[index++]=new Card(0,i);
			cards[index++]=new Card(1,i);
			cards[index++]=new Card(2,i);
			cards[index++]=new Card(3,i);
		}
		cards[index++]=new Card(4,0);
		cards[index++]=new Card(5,0);
		for(int i=0;i<54;i++){
			index=r.nextInt(cards.length);
			card=cards[i];
			cards[i]=cards[index];
			cards[index]=card;
		}	
		return cards;
	}
	
}

 
  
第三步创建玩家


public class Person {
	//属性
	private String name;
	Card[] pcards;
	public void add(Card card){
		pcards=Arrays.copyOf(pcards,pcards.length+1);
		pcards[pcards.length-1]=card;
	}
	//构造器
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name) {
		this.name = name;
		 pcards=new Card[0];
	}
	//get,set方法
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

第四步发牌



public class test {
	public static void main(String[] args) {
		Card[] card=Cards.createCards();
		Person[] p=new Person[3];
		p[0]=new Person("张三");
		p[1]=new Person("李四");
		p[2]=new Person("王五");
		for(int i=0;i<54;i++){
			p[i%3].add(card[i]);
		}
		for(int i=0;i



 

 
  
 
 

你可能感兴趣的:(java_基础)