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

Java入门第三季7-1简易扑克牌作业

winxblast
关注TA
已关注
手记 1
粉丝 0
获赞 5

自己根据前三季的学习,尝试编写了这个程序,期间也参考了一些同学的写法,这里我还自学了enum的用法,并将其应用在程序中。
  程序总共由三个文件组成,代码中的注释不是很多,但是通过输出的文字大家还是能够了解到某段代码的意思的。
  程序通过简单的修改能快速实现多人的游戏,有少部分易出错的地方没有加抛出异常,这里就暂时不做优化了···

运行效果如图所示
图片描述

package com.game;

public class Card implements Comparable<Card> {

    private SuitEnum suit;//花色
    private NumberEnum number;//点数

    /**
     * 构造方法
     */
    public Card (SuitEnum suit, NumberEnum number) {
//      this.suit = suit;
        //这样在setter中可以对输入进行判断
        this.setSuit(suit);
//      this.number = NumberEnum.valueOf(number);
        this.setNumber(number);
    }

    public String getSuit() {
        return suit.toString();
    }

    public void setSuit(SuitEnum suit) {
        try {
            this.suit = suit;
        } catch (Exception e) {
            System.out.println("发牌错误");//不过由于是程序发牌,这句就简单处理了,不会有错的
            //String类输入改为enum类,这样不会有错了
        }
    }

    public String getNumber() {
        return number.toString();
    }

    public void setNumber(NumberEnum number) {
        try {
            this.number = number;
        } catch (Exception e) {
            System.out.println("发牌错误");//不过由于是程序发牌,这句就简单处理了,不会有错的
        }

    }

    @Override //比较牌的大小
    public int compareTo(Card o) {
        // TODO Auto-generated method stub
        if (this.number.equals(o.number)) {
            return this.suit.compareTo(o.suit);
        } else {
            return this.number.compareTo(o.number);
        }
    }

    @Override//输出牌的名称
    public String toString () {
        return suit.toString()+number.toString();
    }

    public enum SuitEnum {
        DIAMONDS("方块"),CLUBS("梅花"),HEARTS("红桃"),SPADES("黑桃");

        private String suitName;

        //构造方法
        private SuitEnum (String suitName) {
            this.suitName = suitName;
        }

        @Override
        public String toString () {
            return this.suitName;
        }
    }

    public enum NumberEnum {
        //点数,从大到小3-10,J,Q,K,A,2
        THREE("3"),FOUR("4"),FIVE("5"),SIX("6"),SEVEN("7"),EIGHT("8"),NINE("9"),TEN("10"),
        JACK("J"),QUEEN("Q"),KING("K"),ACE("A"),TWO("2");

        private String numberName;

        private NumberEnum (String numberName) {
            this.numberName = numberName;
        }

        @Override
        public String toString () {
            return this.numberName;
        }
    }
}
package com.game;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Player {

    private String id;
    private String name;
    private List<Card> handCards;

    public Player () {
        this.setId();
        this.setName();
        this.handCards  = new ArrayList<Card>();
    }

    public String getId() {
        return id;
    }
    public void setId() {
        System.out.println("请输入1~4位长度玩家ID");
        Scanner in = new Scanner(System.in);
        while (true) {
            try {
                this.id = String.valueOf(in.nextInt());
                if (this.id.length()<1 || this.id.length()>4) {
                    throw new IllegalArgumentException();
                }
                break;
            } catch (Exception e) {
                System.out.println("格式错误,请重新输入1~4位长度玩家ID");
                this.id = in.next();
            }
        }

    }

    public String getName() {
        return name;
    }
    public void setName() {
        System.out.println("请输入1~10位长度玩家姓名");
        Scanner in = new Scanner(System.in);
        this.name = in.next();
        while (this.name.length()<1 || this.name.length()>10) {
            System.out.println("请重新输入1~10位长度玩家姓名");
            this.name = in.next();
        }
    }

    public void getHandCards() {
        System.out.print("玩家:"+id+","+name+"手中的全部牌为:[");
        for (Card card : handCards) {
            System.out.print(card.getSuit()+card.getNumber()+" ");
        }
        System.out.println("]");
    }
    public void setHandCards(Card card) {
        this.handCards.add(card);
    }

    public Card getMaxCard () {
        Card maxCard = handCards.get(0);
        for (Card card : handCards) {
            if (card.compareTo(maxCard)>0)
                maxCard = card;
        }
        return maxCard;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Player))
            return false;
        Player other = (Player) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (id.equals(other.id))
            return true;//被我修改过了,不是最初生成的equals,id和name有一个对到就算重复
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (name.equals(other.name))
            return true;
        return false;
    }   
}
package com.game;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Game {

    private List<Card> aPoker;//创建一副扑克牌
    private List<Player> players;//所有玩家

    public static void main(String[] args) {
        Game newGame = new Game();
        newGame.initialPoker();
        newGame.shuffle();
        newGame.initialPlayer();
        newGame.deal();
        newGame.compareCard();

    }

    /**
     * 游戏类构造方法,功能未扩展,暂时只有两位玩家一副牌
     */
    public Game() {
        this.aPoker = new ArrayList<Card>();
        this.players = new ArrayList<Player>();
    }

    public void initialPoker() {
        System.out.println("-------创建扑克牌-------");
        System.out.println("扑克牌为:");
        for (Card.SuitEnum se : Card.SuitEnum.values()) {
            //values()方法网上有介绍,但是java API中找不到,比较诡异
            System.out.print("[");
            for (Card.NumberEnum ne : Card.NumberEnum.values()) {
                aPoker.add(new Card(se,ne));
                System.out.print(se.toString()+ne.toString()+",");
            }
            System.out.println("]");
        }
        System.out.println("-------创建扑克牌成功!-------");
    }

    public void shuffle() {
        System.out.println("-------开始洗牌-------");
        List<Card> pokerTemp = new ArrayList<Card>(aPoker);//这里没法用aPoker.clone()方法
        Random random = new Random();
        for (int i=52; i>0; i--) {
            int r = random.nextInt(i);
            aPoker.set(52-i, pokerTemp.remove(r));
        }
        System.out.println("-------洗牌结束-------");
//      for (Card card : aPoker) {
//          System.out.print(card.getSuit()+card.getNumber()+" ");
//      }
    }

    public void initialPlayer() {
        System.out.println("-------创建玩家-------");
        for (int i=0; i<2; i++) {
            Player p;
            boolean b;
            System.out.println("请输入第"+(i+1)+"位玩家的信息:");
            do {
                p = new Player();
                if (players.contains(p)) {
                    System.out.println("已存在该玩家或ID,请重新输入!");
                    b = true;
                } else {
                    b = false;
                }
            } while (b);
            players.add(p);
        }
        for (Player player : players) {
            System.out.println("----欢迎玩家:"+player.getName());
        }
    }

    public void deal() {
        System.out.println("-------开始发牌-------");
        for (int i=0; i<2; i++) {//一人发两张牌
            for (Player player : players) {
                player.setHandCards(aPoker.remove(0));
                System.out.println("----玩家:"+player.getName()+"-拿牌");
            }
        }
        System.out.println("-------发牌结束!-------");
    }

    public void compareCard() {
        System.out.println("-------开始游戏...-------");
        Player winPlayer = players.get(0);
        for (Player player : players) {
            System.out.println("玩家:"+player.getName()+"最大的手牌为:"+player.getMaxCard().toString());
            if (player.getMaxCard().compareTo(winPlayer.getMaxCard())>0) {
                winPlayer = player;
            }
        }
        System.out.println("-------玩家:"+winPlayer.getName()+"获胜!-------");
        System.out.println("玩家各自的手牌为:");
        for (Player player : players) {
            player.getHandCards();
        }
    }
}
打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP