JAVA集合練習:鬥地主發牌

raylu666發表於2017-04-17

學完集合可以練習一個小題目: 鬥地主發牌

package test1;


import java.util.ArrayList;
import java.util.Collections;
//鬥地主發牌程式編寫
public class TestPoker {
	public static void main(String[] args) {
		//三個玩家,起名
		Player p1 = new Player("RayLu");
		Player p2 = new Player("Bleach");
		Player p3 = new Player("Tom");
		//整副撲克牌物件建立
		Poker poker = new Poker();
		//洗牌
		poker.pokerShuffle();
		//發牌
		for(int i = 0; i < poker.getPoker().size(); i++){
			if( i % 3 == 0){
				p1.getPoker().add(poker.getPoker().get(i));
			}else if( i%3==1){
				p2.getPoker().add(poker.getPoker().get(i));
			}else if(i%3 ==2){
				p3.getPoker().add(poker.getPoker().get(i));
			}
		}
		//發牌完成,遍歷每個玩家手中的牌
		for(int i = 0; i < p1.getPoker().size(); i++){
			System.out.println(p1.getName()+"手中第"+(i+1)+"張牌是:"+p1.getPoker().get(i));
		}
		for(int i = 0; i < p2.getPoker().size(); i++){
			System.out.println(p2.getName()+"手中第"+(i+1)+"張牌是:"+p2.getPoker().get(i));
		}
		for(int i = 0; i < p3.getPoker().size(); i++){
			System.out.println(p3.getName()+"手中第"+(i+1)+"張牌是:"+p3.getPoker().get(i));
		}
	}
}




class Poker{
	private String[] pokerColor = new String[]{"紅桃","黑桃","方片","梅花"};
	private String[] pokerNum = new String[]{"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
	private ArrayList<String> poker;
	
	public Poker(){
		poker = new ArrayList<String>();
		for(int i =0; i < this.pokerColor.length; i++){
			for (int j = 0; j < this.pokerNum.length; j++){
				String str = pokerColor[i] + pokerNum[j];
				poker.add(str);
			}
		}
		poker.add("大王");
		poker.add("小王");


	}
	//獲取整副撲克牌
	public ArrayList<String> getPoker(){
		return poker;
	}
	//重洗撲克牌
	public void pokerShuffle(){
		Collections.shuffle(poker);
	}
}
//鬥地主玩家
class Player{
	private String name;//玩家姓名
	private ArrayList<String> poker;//玩家手中的牌


	public ArrayList<String> getPoker() {
		return poker;
	}


	public void setPoker(ArrayList<String> poker) {
		this.poker = poker;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public Player(String name) {
		super();
		this.name = name;
		poker = new ArrayList<String>();
	}


	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}


	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Player other = (Player) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}


相關文章