需求与分析
需求
- 总共有54张牌
- 点数:"3","4","5","6","7","8","9","10","J","Q","K","A","2"
- 花色:"♠","♥","♣","♦"
- 大小王:"👲","🃏"
- 斗地主:发出51张牌,剩下3张作为底牌
分析实现
- 在启动游戏房间的时候,应该提前准备好54张牌
- 接着,需要完成洗牌、发牌、对牌排序、看牌
具体实现
牌类定义
package user.Collection; public class Card { private String number; private String color; //每张牌是存在牌值大小的 private int size; //0 1 2 ... public Card() { } public Card(String number, String color, int size) { this.number = number; this.color = color; this.size = size; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } @Override public String toString() { return number + color; } }
房间类定义
package user.Collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Room { //首先必须有一副牌 private List<Card> allCards = new ArrayList<>(); public Room(){ //1.做出54张牌,存入到集合allCards //a.所有牌的点数 String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"}; //b.所有牌的花色 String[] colors = {"♠","♥","♣","♦"}; int size = 0; //表示每张牌的牌值大小 //c.遍历点数,再遍历花色,组织牌 for(String number:numbers){ //number = "3" size++; //1 2 3 ...... for(String color:colors){ //得到一张牌 Card d = new Card(number,color,size); allCards.add(d); //存入牌库 } } //单独存入大小王 Card d1 = new Card("","🃏",++size); //小王 Card d2 = new Card("","👲",++size); //大王 Collections.addAll(allCards,d1,d2); } }
初步测试
在Room类中加一下输出语句:(已重写Card类的toString方法)
在主程序中运行:
运行结果:
启动游戏
在Room类中编写启动游戏的方法,再调用
public void start() { //1.洗牌 Collections.shuffle(allCards); System.out.println("洗牌后:" + allCards); //2.发牌,发给三个玩家 还是使用List集合 List<Card> MegMarch = new ArrayList<>(); List<Card> JoMarch = new ArrayList<>(); List<Card> BethMarch = new ArrayList<>(); //正式发牌给这三个玩家,依次发出51张牌,剩余三张作为底牌 for(int i = 0;i < allCards.size();i++){ Card c = allCards.get(i); //判断发牌给谁 if(i % 3 == 0){ //发牌给梅格 MegMarch.add(c); }else if(i % 3 == 1){ //发牌给乔 JoMarch.add(c); }else if(i % 3 == 2){ //发牌给贝丝 BethMarch.add(c); } } //3.对三个玩家的牌进行排序 sortCards(MegMarch); sortCards(JoMarch); sortCards(BethMarch); //4.看牌 System.out.println("梅格 :" + MegMarch); System.out.println("乔 :" + JoMarch); System.out.println("贝丝 :" + BethMarch); List<Card> lastThreeCards = allCards.subList(allCards.size() - 3,allCards.size()); System.out.println("底牌 :" + lastThreeCards); //假设乔抢到了地主 JoMarch.addAll(lastThreeCards); sortCards(JoMarch); System.out.println("乔抢到地主后:" + JoMarch); } private void sortCards(List<Card> cards) { Collections.sort(cards, new Comparator<Card>() { @Override public int compare(Card o1, Card o2) { return o2.getSize() - o1.getSize(); //降序排序 } }); }
运行案例
END