本文主要是介绍JavaSE——集合框架二(2/6)-综合案例-斗地主游戏(做牌、洗牌、发牌、排序、看牌),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
需求与分析
具体实现
牌类定义
房间类定义
初步测试
启动游戏
运行案例
需求与分析
需求
- 总共有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;}@Overridepublic 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>() {@Overridepublic int compare(Card o1, Card o2) {return o2.getSize() - o1.getSize(); //降序排序}});}
运行案例
END
学习自:黑马程序员——JavaSE课程
这篇关于JavaSE——集合框架二(2/6)-综合案例-斗地主游戏(做牌、洗牌、发牌、排序、看牌)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!