package yuwei.com;
import java.util.Collections;
import java.util.List;
import java.util.LinkedList;
public class ShowHand {
//定义玩家的数量
private final int PLAYER_NUM = 4;
//定义扑克牌的数量和huase
private String[] types = {"方块","草花","红心","黑桃"};
private String[] values = {"2","3","4","5","6","7","8","9","10","j","q","K","A"};;
//cards一局中剩余的牌数
private List<String> cards = new LinkedList<String>();
//定义所有玩家
private String[] players = new String[PLAYER_NUM];
//所有玩家手上的扑克牌
private List<String>[] playersCards = new List[PLAYER_NUM];
/** * 初始化扑克牌 * 并随机进行顺序排列 * */
public void initCards() {
for(int i = 0;i < types.length;i++) {
for(int j = 0;j < values.length;j++) {
cards.add(types[i] + values[j]);
}
}
Collections.shuffle(cards);
}
/** * 初始化玩家 * 为其命名 * */
public void initPlayer(String...name) {
if(name.length > PLAYER_NUM || name.length < 2) {
System.out.println("玩家的数量不对");
return ;
}
else
{
//初始化玩家姓名
for(int i = 0;i < name.length;i++) {
players[i] = name[i];
}
}
}
/** * 初始化玩家手上的牌为null*/
public void initPlayweCards() {
for(int i = 0;i < players.length;i++) {
if(this.players[i] != null) {
this.playersCards[i] = new LinkedList<>();
}
}
//playersCards[0].add("a");
}
/** * 输出全部扑克牌,该方法没有实际作用仅用于测试 * */
public void showAllCards() {
for(String card:cards) {
System.out.println(card);
}
}
/** * 发扑克 * @param first 最先派发给谁 * */
public String deliverCard(String first) {
int firstPos = ArrayUtils(players,first);
for(int i = firstPos;i <PLAYER_NUM;i++ ) {
if(players[i] != null) {
if(!cards.isEmpty()) {
playersCards[i].add(cards.get(0));
cards.remove(0);
}
}
}
//
for(int i = 0;i<firstPos;i++) {
if(players[i]!=null) {
if(!cards.isEmpty()) {
playersCards[i].add(cards.get(0));
cards.remove(0);
}
}
}
if(!cards.isEmpty()) {
return cards.get(0);
}
return null;
}
/** * 输出玩家手上的牌 * */
public void showPlayerCards() {
for(int i = 0;i< PLAYER_NUM;i++) {
if(players[i] != null) {
//输出玩家
System.out.println(players[i] + ":");
for(String card:this.playersCards[i]) {
System.out.print(card + "\t");
}
System.out.println();
}
}
}
private int ArrayUtils(String[] players, String first) {
// TODO Auto-generated method stub
int i = 0;
for(i = 0;i < players.length;i++) {
if(players[i] == first) {
return i;
}
}
return 0;
}
public static void main(String[] args) {
ShowHand sh = new ShowHand();
sh.initPlayer("诸葛亮","孙悟空","玩家A","玩家B");
sh.initCards();
sh.initPlayweCards();
sh.showAllCards();
System.out.println("-------------");
//为用户发牌
while(sh.deliverCard("孙悟空")!=null) {}
sh.showPlayerCards();
}
}
来自java疯狂讲义自学练习,已修改