JAVA 面向对象 程序设计 微课版 P118页
第1 个玩家:
红心2 红心A 草花A 草花K 黑桃Q 草花Q 方块Q 草花J 方块9 黑桃8 红心8 草花8 黑桃7 黑桃5 方块5 方块4 红心3
第2 个玩家:
小王 草花2 方块A 方块K 黑桃J 红心J 黑桃10 红心10 草花10 黑桃9 红心9 草花9 方块8 草花7 方块7 黑桃6 红心5
第3 个玩家:
大王 黑桃2 方块2 黑桃A 红心K 方块J 方块10 红心7 红心6 草花6 方块6 草花5 黑桃4 红心4 黑桃3 草花3 方块3
底牌:
草花4
红心Q
黑桃K
package _8;public class Card {private static String face[]={"J","Q","K","A","2","小王","大王"};private static String suit[]={"方块","草花","红心","黑桃"};private int rank;//片的点数private int suitIdx;//花色编号public int getRank() {return rank;}public int getSuitIndex() {return suitIdx;}public Card(int rank,int suitIdx){this.rank =rank;this.suitIdx =suitIdx;}@Overridepublic String toString() {if(rank<=10)return suit[suitIdx]+rank;else if(rank<=15)return suit[suitIdx]+face[rank -11 ];elsereturn face[rank-11];}
}
package _8;import java.util.Comparator;public class CardComparator implements Comparator<Card> {@Overridepublic int compare(Card o1, Card o2) {if(o1.getRank()==o2.getRank())return o2.getSuitIndex() -o1.getSuitIndex();elsereturn o2.getRank()-o1.getRank();}
}
package _8;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;public class CardTest {public static void main(String[] args) {List<Card> cards = new ArrayList<Card>();//所有牌List<List<Card>> p_cards = new ArrayList<List<Card>>();//多个人,每个人多张牌for (int i = 3; i <= 15; i++) {for (int j = 0; j < 4; j++) {cards.add(new Card(i, j));}}cards.add(new Card(16, 0));cards.add(new Card(17, 0));for (int i = 0; i < 3; i++) {List<Card> p_card = new ArrayList<Card>();p_cards.add(p_card);}Collections.shuffle(cards);//洗牌CardComparator comparator = new CardComparator();//分发牌for (int i = 0; i < 3; i++) {for (int j = 0; j < 17; j++) {Card card = cards.remove(0);p_cards.get(i).add(card);}}//打印三个人手中信息for (int i = 0; i < 3; i++) {//p_cards.get(i).sort(comparator);Collections.sort(p_cards.get(i), comparator);System.out.println(" 第" + (i + 1) + " 个玩家:");for (int j = 0; j < p_cards.get(i).size(); j++) {System.out.print(p_cards.get(i).get(j) + " ");}System.out.println();}//底牌System.out.println("底牌:");for (Card card : cards) System.out.println(card);}
}