继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

简易扑克牌游戏-Java基础练习(面向对象+集合)

慕粉3848213
关注TA
已关注
手记 5
粉丝 5
获赞 110
知识点:
  • 集合

    • List 接口的实现类 ArrayList
    • SortedSet (Set 接口子类,实现了排序)接口的实现类 TreeSet
    • SortedMap (Map 接口的子类,实现了 key 排序)接口的实现类 TreeMap
    • Comparable 接口及其 comparaTo() 方法的实现
  • 面向对象

    • 封装
    • 多态
  • 重写 equals() 和 hashCode()
  • 静态代码块
代码:
  • Const.java

public class Const {

    static Map<String, Integer> pokerContent;
    static Map<String, Integer> pokerColor;

    static {
        pokerContent = new HashMap<>();
        pokerColor = new HashMap<>();
        pokerContent.put("2", 2);
        pokerContent.put("3", 3);
        pokerContent.put("4", 4);
        pokerContent.put("5", 5);
        pokerContent.put("6", 6);
        pokerContent.put("7", 7);
        pokerContent.put("8", 8);
        pokerContent.put("9", 9);
        pokerContent.put("10", 10);
        pokerContent.put("J", 11);
        pokerContent.put("Q", 12);
        pokerContent.put("K", 13);
        pokerContent.put("A", 14);

        pokerColor.put("黑桃", 4);
        pokerColor.put("红桃", 3);
        pokerColor.put("方片", 2);
        pokerColor.put("梅花", 1);
    }

    public static int getPokerContentInteger(String content){
        return pokerContent.get(content);
    }

    public static int getPokerColorInteger(String color){
        return pokerColor.get(color);
    }
}
  • Poker.java

public class Poker implements Comparable {

    private String color;
    private String content;

    public Poker() {

    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return getColor() + getContent();
    }

    @Override
    public int compareTo(Object o) {
        Poker poker = (Poker) o;
        int thisPokerContentInteger = Const.getPokerContentInteger(this.getContent());
        int pokerContentInteger = Const.getPokerContentInteger(poker.getContent());
        if (thisPokerContentInteger > pokerContentInteger) {
            return 1;
        } else if (thisPokerContentInteger == pokerContentInteger) {
            int thisPokerColorInteger = Const.getPokerColorInteger(this.getColor());
            int pokerColorInteger = Const.getPokerColorInteger(poker.getColor());
            if (thisPokerColorInteger > pokerColorInteger) {
                return 1;
            } else if (thisPokerColorInteger == pokerColorInteger) {
                return 0;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null  getClass() != o.getClass()) return false;

        Poker poker = (Poker) o;

        if (!this.content.equals(poker.content)) return false;
        return this.color.equals(poker.color);

    }

    @Override
    public int hashCode() {
        int result = color.hashCode();
        result = 31 * result + content.hashCode();
        return result;
    }
}
  • Player.java

public class Player implements Comparable {

    private int ID;
    private String name;

    private SortedSet<Poker> sortedPoker;

    public SortedSet<Poker> getSortedPoker() {
        return sortedPoker;
    }

    public void addSortedPoker(Poker sortedPoker) {
        this.sortedPoker.add(sortedPoker);
    }

    public Player() {
        sortedPoker = new TreeSet<>();
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "玩家 {" +
                "ID=" + ID +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null  getClass() != o.getClass()) return false;

        Player player = (Player) o;

        return ID == player.ID;

    }

    @Override
    public int hashCode() {
        return ID;
    }

    @Override
    public int compareTo(Object o) {
        Player player = (Player) o;
        if (this.getID() > player.getID()) {
            return 1;
        } else if (this.getID() == player.getID()) {
            return 0;
        } else if (this.getID() < player.getID()) {
            return -1;
        }
        return 0;
    }
}
  • PlayGame.java

/**
 * 1.创建扑克牌,用到随机数,四个花色(黑桃,红桃,方片,梅花),数字(2-0),字母(J,Q,K,A),不含大小王,总计52张牌.
 * 2.遍历生成的扑克牌,显示生成的扑克牌,显示花色和内容
 * 3.洗牌,把生成的扑克牌顺序打乱
 * 4.生成2个玩家,包括 ID,姓名
 * 5.发牌,一人一张牌,从打乱顺序的牌的开头发牌,一人2张牌,就是前4张牌
 * 6.开始游戏,显示2个玩家手中最大的手牌(先比较数字,数字相同时比较花色(黑桃>红桃>方片>梅花))
 * 7.显示胜利者的名字
 * 8.显示2个玩家名字及手牌
 */
public class PokerGame {

    //扑克牌
    List<Poker> pokerList;
    //洗牌以后的扑克牌
    List<Poker> shufflerPoker;
    //创建2个玩家,ID不能相同
    SortedSet<Player> playerSet;
    //玩家手牌数量
    private int playerHandPokerNumber = 2;

    public void play() {
        //创建52张扑克牌
        createPoker();
        //洗牌
        pokerShuffle();
        //遍历洗牌以后的扑克牌
//        iteratorAfterShuffle();
        //创建2个玩家
        createPlayer();
        //遍历玩家
        iteratorPlayer();
        //发牌
        dealPoker();
        //开始游戏
        comparePlayerHandPoker();
        //遍历玩家手牌
        iteratorHandPoker();
    }

    /**
     * 创建扑克牌
     */
    private void createPoker() {
        System.out.println("-----------创建扑克牌-----------");
        List<String> pokerContent = new ArrayList<>(Const.pokerContent.keySet());
        List<String> pokerColor=new ArrayList<>(Const.pokerColor.keySet());
        pokerList = new ArrayList<>();
        Poker temPoker;
        for (int i = 0; i < pokerColor.size(); i++) {
            for (int j = 0; j < pokerContent.size(); j++) {
                temPoker = new Poker();
                temPoker.setColor(pokerColor.get(i));
                temPoker.setContent(pokerContent.get(j));
                pokerList.add(temPoker);
            }
        }
        System.out.println("-----------扑克牌创建成功-----------");
        iteratorPoker();
    }

    /**
     * 遍历扑克牌
     */
    public void iteratorPoker() {
        for (int i = 0; i < pokerList.size(); i++) {
            if (i == 0) {
                System.out.print("为:[" + pokerList.get(i) + ", ");
                continue;
            }
            if (i == pokerList.size() - 1) {
                System.out.println(pokerList.get(i) + "]");
                continue;
            }
            System.out.print(pokerList.get(i) + ", ");
        }
    }

    /**
     * 洗牌
     */
    public void pokerShuffle() {
        System.out.println("-----------开始洗牌...-----------");
        shufflerPoker = new ArrayList<>();
        Random random = new Random();

        while (shufflerPoker.size() < pokerList.size()) {
            Poker poker = pokerList.get(random.nextInt(pokerList.size()));
            if (shufflerPoker.contains(poker)) {
                continue;
            }
            shufflerPoker.add(poker);
        }
        System.out.println("-----------洗牌结束!-----------");
    }

    /**
     * 洗牌结束后遍历牌
     */
    public void iteratorAfterShuffle() {
        Iterator<Poker> iterator = shufflerPoker.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    /**
     * 创建 2 个玩家,要求 ID 必须为整数, ID不能重复。
     */
    private void createPlayer() {
        playerSet = new TreeSet<>();
        Scanner scanner = new Scanner(System.in);
        System.out.println("-----------创建玩家...-----------");
        Player temPlayer;
        for (int i = 1; i <= 2; i++) {
            //检查 ID 是否重复
            boolean isDuplication = false;
            while (!isDuplication) {
                temPlayer = new Player();
                System.out.println("请输入第 " + i + " 位玩家的ID和姓名:");

                boolean isID = false;
                while (!isID) {
                    System.out.println("输入ID:");
                    int id;
                    try {
                        id = Integer.parseInt(scanner.next());
                    } catch (Exception e) {
                        System.out.println("请输入整数类型的ID!");
                        isID = false;
                        continue;
                    }
                    isID = true;
                    temPlayer.setID(id);
                }

                boolean isName = false;
                while (!isName) {
                    System.out.println("输入姓名:");
                    String name;
                    try {
                        name = scanner.next();
                    } catch (Exception e) {
                        System.out.println("请输入正确的玩家姓名!");
                        isName = false;
                        continue;
                    }
                    isName = true;
                    temPlayer.setName(name);
                }
                if (playerSet.contains(temPlayer)) {
                    isDuplication = false;
                    System.out.println("玩家ID已经被占用,请重新输入");
                    continue;
                }
                playerSet.add(temPlayer);
                isDuplication = true;
            }
        }

    }

    /**
     * 遍历玩家,显示玩家姓名
     */
    private void iteratorPlayer() {
        for (Player p : playerSet) {
            System.out.println("---欢迎玩家:" + p.getName());
        }
    }

    /**
     * 发牌
     */
    private void dealPoker() {
        System.out.println("-----------开始发牌...-----------");
        for (int i = 0; i < playerHandPokerNumber * playerSet.size(); i++) {
            Player player;
            if (i % 2 == 0) {
                player = playerSet.first();
                player.addSortedPoker(shufflerPoker.get(i));
            } else {
                player = playerSet.last();
                player.addSortedPoker(shufflerPoker.get(i));
            }
            System.out.println("----玩家:" + player.getName() + "-拿牌");
        }
        System.out.println("-----------发牌结束!-----------");
    }

    /**
     * 显示玩家的手牌
     */
    private void iteratorHandPoker() {
        System.out.println("玩家各自的手牌为:");
        for (Player p : playerSet) {
            SortedSet<Poker> sortedPoker = p.getSortedPoker();
            System.out.print(p.getName() + ":[");
            for (Poker poker : sortedPoker) {
                if (poker.equals(sortedPoker.last())) {
                    System.out.print(poker + "]" + "\n");
                } else {
                    System.out.print(poker + ", ");
                }
            }
        }
    }

    /**
     * 比较玩家的手牌
     */
    private void comparePlayerHandPoker() {
        System.out.println("-----------开始游戏...-----------");
        SortedMap<Poker, Player> playerHandMaxPoker = new TreeMap<>();
        for (Player p : playerSet) {
            Poker poker = p.getSortedPoker().last();
            playerHandMaxPoker.put(poker, p);
            System.out.println("玩家:" + p.getName() + "最大的手牌为:" + poker);
        }
        Poker maxPoker = playerHandMaxPoker.lastKey();
        Player player = playerHandMaxPoker.get(maxPoker);
        System.out.println("--------------玩家:" + player.getName() + "获胜!----------------");
    }

    public static void main(String[] args) {
        PokerGame pokerGame = new PokerGame();
        pokerGame.play();
    }
}
  • 测试结果

-----------创建扑克牌-----------
-----------扑克牌创建成功-----------
为:[黑桃A, 黑桃J, 黑桃K, 黑桃Q, 黑桃2, 黑桃3, 黑桃4, 黑桃5, 黑桃6, 黑桃7, 黑桃8, 黑桃9, 黑桃10, 梅花A, 梅花J, 梅花K, 梅花Q, 梅花2, 梅花3, 梅花4, 梅花5, 梅花6, 梅花7, 梅花8, 梅花9, 梅花10, 方片A, 方片J, 方片K, 方片Q, 方片2, 方片3, 方片4, 方片5, 方片6, 方片7, 方片8, 方片9, 方片10, 红桃A, 红桃J, 红桃K, 红桃Q, 红桃2, 红桃3, 红桃4, 红桃5, 红桃6, 红桃7, 红桃8, 红桃9, 红桃10]
-----------开始洗牌...-----------
-----------洗牌结束!-----------
-----------创建玩家...-----------
请输入第 1 位玩家的ID和姓名:
输入ID:
aqwe
请输入整数类型的ID!
输入ID:
1
输入姓名:
Tom
请输入第 2 位玩家的ID和姓名:
输入ID:
2
输入姓名:
Jack
---欢迎玩家:Tom
---欢迎玩家:Jack
-----------开始发牌...-----------
----玩家:Tom-拿牌
----玩家:Jack-拿牌
----玩家:Tom-拿牌
----玩家:Jack-拿牌
-----------发牌结束!-----------
-----------开始游戏...-----------
玩家:Tom最大的手牌为:梅花K
玩家:Jack最大的手牌为:梅花Q
--------------玩家:Tom获胜!----------------
玩家各自的手牌为:
Tom:[红桃6, 梅花K]
Jack:[黑桃6, 梅花Q]
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP

热门评论

非常好!

查看全部评论