为了账号安全,请及时绑定邮箱和手机立即绑定

把游戏稍微扩充了下,N个玩家比牌面,ID不是手动输入,是由程序自动生成。

package com.exercise;

//Create a Card class with two attribute, suit and point
public class Card implements Comparable<Card>{
    private String suit;
    private String point;
    final String[] cardSuit = {"diamond","club","spade","heart" };
    final String[] cardPoint = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
    
    /**
     * return the position of the given string in the string array of cardSuit and cardPoint
     * so that we can compare a card by suit and point
     * @param str
     * @param s
     *
     */
    public int getIndex(String[] str,String s){
        int i=0;
        
        while (!str[i].equals(s)){
            i++;
        }
        return i;
    }
    
    public Card(String suit,String point){
        this.suit = suit;
        this.point = point;
    }
    
    public String getSuit(){
        return suit;
    }
    
    public String getPoint(){
        return point;
    }

    
    
    @Override
    /**
     * override the compareTo method to implement the idea as following:
     * given two cards, firstly we compare both points, if the points are same
     * we compare the suits according with the ascending order as the array of cardSuit
     */
    public int compareTo(Card o) {
        // TODO Auto-generated method stub
        Integer index1 = getIndex(cardPoint,this.point);
        Integer index2 = getIndex(cardPoint,o.point);        
        int result = index1.compareTo(index2);
        
        if (result!=0)
            return result;
        else{
            index1 = getIndex(cardSuit,this.suit);
            index2 = getIndex(cardSuit,o.suit);
            return index1.compareTo(index2);
        }                
        
    }
}
package com.exercise;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * create player class with 3 attributes:name, id and a list of cards
 * and one original method of taking cards, and one override method
 * of compareTo
 */
public class Player implements Comparable<Player>{    
    
    private String name;
    private String ID;
    public List<Card> cards;
    
    public Player(String name, String ID){
        this.name = name;
        this.ID = ID;
        this.cards = new ArrayList<Card>();
    }
    
    public String getName(){
        return name;
    }

    public String getID(){
        return ID;
    }
    
    public void setName(String name){
        this.name = name;
    }
    
    public void setID(String ID){
        this.ID = ID;
    }    

    //Take a card from the cardSet after shuffle
    //parameter index indicates the order number of shuffle card
    public void takeCard(List<Card> shuffleCard, int index){
        cards.add(shuffleCard.get(index));
    }

    @Override
    /**
     * the method compare all the cards of two players
     * firstly we sort all the card of one player
     * then we compare the last card of the two players
     */
    public int compareTo(Player o) {
        
        Collections.sort(this.cards);
        Collections.sort(o.cards);
        return this.cards.get(1).compareTo(o.cards.get(1));
    
    }
}
package com.exercise;
 
//create an exception in case the customer enter an username starting with an non-alphabet character
public class PlayerNameException extends Exception {
    public PlayerNameException(){
    
    }
    public String toString(){
        return "Game player name must start with an alphabet character, please try again: ";
    }
}
package com.exercise;

public class PlayerNumberException extends Exception {
    public PlayerNumberException(){
    
    }
    public String toString(){
        return "The number should be an integer greater than 2, please try again: ";
    }
}
package com.exercise;

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

/**
 * Create the whole set of cards
 * Create n game players, player name must start with an alphabet character, otherwise go exception handling
 * Auto-generate game player ID with 3 digits, but the first digit can't be 0 * 
 *
 */
public class Game {
    final String[] cardSuit = {"diamond","club","spade","heart" };
    final String[] cardPoint = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
    final int idNum = 3;
    List<Player> playerList;
    

    public Game(){
        playerList = new ArrayList<Player>();
    }
    
    //the CardCase generation is a procedure of combination of suit and Point
    public void genCardCase(List<Card> cardCase){
        Card cd;
        for (int i=0;i<cardSuit.length;i++){
            for (int j=0;j<cardPoint.length;j++){
                cd = new Card(cardSuit[i],cardPoint[j]);
                cardCase.add(cd);                
            }            
        }        
    }
    
    /**
     * shuffle is a procedure as following
     * generate a unique random index for each element, and then take the corresponding card from the sorted cardlist
     * @param cardCaseShuffle stores the cards after shuffle
     * @param cardCase stores the previous sorted cards
     */
    public void shuffle(List<Card> cardCaseShuffle, List<Card> cardCase){
        Random ran = new Random();
        int index;
        int size = cardCase.size();
        List <Integer> idList = new ArrayList<Integer>(); 
        
        for (int i=0;i<size;i++){
            index = ran.nextInt(size);
            
            //guarantee the generating number is unique, if yes take the corresponding card from
            //sorted list to the shuffle list
            while(idList.contains(index)){
                index = ran.nextInt(size);
            }
            idList.add(index);            
            cardCaseShuffle.add(cardCase.get(index));
            
        }
        
    }

正在回答

3 回答

good!

0 回复 有任何疑惑可以回复我~

最后输出,包含各种错误输入

5760dcfe0001c7cd05000443.jpg

5760dd090001964305000457.jpg

5760dd10000165c703400291.jpg

0 回复 有任何疑惑可以回复我~
//display the whole set of cards after successful creation
    public void displayCards(List<Card> cardCase){
        int i=1;
        for (Card c:cardCase){
            System.out.print(c.getSuit()+c.getPoint()+" ");
            if (i%4==0)
                System.out.print("\n");
            i++;
        }
        System.out.println("\n");
    }
    
    /**
     * Auto generate an ID for the game player, which include 3-digit starting with non-zero digit
     * @return the ID string
     */
    public String genID(){
        Random ran = new Random();
        StringBuffer sb = new StringBuffer();
        int digit;
        
        for (int i=0;i<idNum;i++){
            digit = ran.nextInt(10);
            if (i==0){
                while(digit==0){
                    digit = ran.nextInt(10);
                }
            }
            sb.append(digit+"");
        }
        return sb.toString();
    }
    
    //throw exception when the game player enter a wrong name
    public void checkPlayerName(String name) throws PlayerNameException{
        if (((name.toLowerCase().charAt(0))<'a')||((name.toLowerCase().charAt(0))>'z'))
            throw new PlayerNameException();
    }
    //create the nth game player
    public Player genPlayer(int num,List<String> plIDList){
        String plName = null;
        System.out.print("Please enter the player "+(num+1)+"'s name: ");    
        boolean flag = false;
        
        do{
            try{
                Scanner input = new Scanner(System.in);
                plName = input.nextLine();
                checkPlayerName(plName);
                flag = true;
            }catch (PlayerNameException e){
                System.out.print(e);
            }
        }while (flag == false);
        
        //the auto-generated ID should be unique, if no, re-generate it
        String plID = genID();
        while (plIDList.contains(plID)){
            plID = genID();
        }
        plIDList.add(plID);
        System.out.println("Your auto-generated ID: "+plID);
        return (new Player(plName,plID));        
    }
    
    //displayer all the cards in player's hand
    public void displayPlayerCard(Player pl){
        System.out.print(pl.getName()+" has hand: ");
        for(Card cd:pl.cards){
            System.out.print(cd.getSuit()+cd.getPoint()+" ");
        }
        System.out.print("\n");
    }
    
    public void checkPlayerNumber(int num)throws PlayerNumberException{
        if (num<2)
            throw new PlayerNumberException();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Game game = new Game();
        List<String> plIDList = new ArrayList<String>();
        List<Card> cardCase = new ArrayList<Card>();
        int i;
        
        
        System.out.println("*********Creating the cardcase*********\n");
        game.genCardCase(cardCase);
        System.out.println("*************Creation done*************\n");
        game.displayCards(cardCase);
        System.out.println("*************Start shuffle*************\n");
        List<Card> newCardCase = new ArrayList<Card>();
        game.shuffle(newCardCase, cardCase);    
        System.out.println("**************shuffle done*************\n");
        //game.displayCards(newCardCase);        
        
        Player pl;
        int playerNum=0;
        boolean flag = false;
        System.out.println("************Creating players***********\n");
        System.out.print("Please enter the player number: ");
        
        //do-while loop control exception, which may be non-integer input exception
        //or incorrect integer input exception
        do{
            try{
                Scanner input = new Scanner(System.in);
                playerNum = input.nextInt();
                game.checkPlayerNumber(playerNum);
                flag = true;
            }catch(PlayerNumberException e){//incorrect integer input exception
                System.out.print(e);
            }catch(Exception e){//non-integer input exception
                System.out.print("the number can'be an non-integer, please try again: ");                
            }
        }while (flag == false);
          
        for (i = 0;i<playerNum;i++){
            pl = game.genPlayer(i,plIDList);
            game.playerList.add(pl);
        }
        
        i=1;
        for (Player p: game.playerList){
            System.out.println("Welcome player "+i+":  "+p.getID()+"  "+p.getName());
            i++;
        }

        
        System.out.println("\n**************Start Deal***************\n");
        /**
         * give our cards for n players, each player will get two cards
         */
        for (i=0;i<=playerNum;i+=playerNum){
            for (int j=0;j<playerNum;j++){
                pl = game.playerList.get(j);
                pl.takeCard(newCardCase, i+j);
                System.out.println("Game player "+pl.getName()+" is taking a card\n");
            }            
        }
        System.out.println("****************Deal done!***************\n");
        
        System.out.println("****************Game start***************\n");
        //after sorting the player list, the winner definitely is the last one in the list.
        Collections.sort(game.playerList);
        for (Player p: game.playerList){
            System.out.println("Player "+p.getName()+"'s biggest card: "+p.cards.get(1).getSuit()+p.cards.get(1).getPoint());
        }
        System.out.println("\n***************The winner is*************\n");
        System.out.println("         "+game.playerList.get(playerNum-1).getName()+"\n");    
                
        //display two cards in all the player's hand
        for (Player p:game.playerList){
            game.displayPlayerCard(p);
        }
        
            
    }

}


0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

把游戏稍微扩充了下,N个玩家比牌面,ID不是手动输入,是由程序自动生成。

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信