Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Help with Java Poker Project

    So in one of my classes we were assigned a project to create a simple poker game. I have some of the code, but I still need to finish it and I don't know where to continue. When running TestPlaySimplePoker.java, it gets to the point where it says "enter positions to keep" then it just stops and if anything else is entered, it gives an error.

    Here is TestPlaySimplePoker.java which should NOT be changed.
    Code:
    /*************************************************************************************
     *
     *  This program is used to test PJ4.SimplePoker class
     *  More info are given in Readme file
     * 
     *  PJ4 class allows user to run program as follows:
     *
     *    	java PJ4		// default credit is $100
     *  or 	java PJ4 NNN		// set initial credit to NNN
     *
     *  Do not modify this file!
     *
     **************************************************************************************/
    
    import PJ4.SimplePoker;
    
    class TestPlaySimplePoker {
    
        public static void main(String args[]) 
        {
    	SimplePoker mypokergame;
    	if (args.length > 0)
    		mypokergame = new SimplePoker(Integer.parseInt(args[0]));
    	else
    		mypokergame = new SimplePoker();
    	mypokergame.play();
        }
    }
    Here is PlayingCard.java

    Code:
    package PJ4;
    
    import java.util.*;
    import java.util.Collections;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     * class PlayingCardException: It is used for errors related to Card and Deck
     * objects Do not modify this class!
     */
    class PlayingCardException extends Exception {
    
        /* Constructor to create a PlayingCardException object */
        PlayingCardException() {
            super();
        }
    
        PlayingCardException(String reason) {
            super(reason);
        }
    }
    
    /**
     * class Card : for creating playing card objects it is an immutable class. Rank
     * - valid values are 1 to 13 Suit - valid values are 0 to 3 Do not modify this
     * class!
     */
    class Card {
    
        /* constant suits and ranks */
        static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
        static final String[] Rank = {"", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
    
        /* Data field of a card: rank and suit */
        private int cardRank;  /* values: 1-13 (see Rank[] above) */
    
        private int cardSuit;  /* values: 0-3  (see Suit[] above) */
    
        /* Constructor to create a card */
        /* throw PlayingCardException if rank or suit is invalid */
    
        public Card(int rank, int suit) throws PlayingCardException {
            if ((rank < 1) || (rank > 13)) {
                throw new PlayingCardException("Invalid rank:" + rank);
            } else {
                cardRank = rank;
            }
            if ((suit < 0) || (suit > 3)) {
                throw new PlayingCardException("Invalid suit:" + suit);
            } else {
                cardSuit = suit;
            }
        }
    
        /* Accessor and toString */
        /* You may impelemnt equals(), but it will not be used */
        public int getRank() {
            return cardRank;
        }
    
        public int getSuit() {
            return cardSuit;
        }
    
        public String toString() {
            return Rank[cardRank] + " " + Suit[cardSuit];
        }
    
        /* Few quick tests here */
        public static void main(String args[]) {
            try {
                Card c1 = new Card(1, 3);    // A Spades
                System.out.println(c1);
                c1 = new Card(10, 0);	// 10 Clubs
                System.out.println(c1);
                c1 = new Card(10, 5);        // generate exception here
            } catch (PlayingCardException e) {
                System.out.println("PlayingCardException: " + e.getMessage());
            }
        }
    }
    
    /**
     * class Decks represents : n decks of playing cards Use class Card to construct
     * n * 52 playing cards!
     *
     * Do not add new data fields! Do not modify any methods You may add private
     * methods
     */
    class Decks {
    
        /* this is used to keep track of original n*52 cards */
        private List<Card> originalDecks;
    
        /* this starts with n*52 cards deck from original deck   */
        /* it is used to keep track of remaining cards to deal */
        /* see reset(): it resets dealDecks to a full deck      */
        private List<Card> dealDecks;
    
        /* number of decks in this object */
        private int numberDecks;
    
        /**
         * Constructor: Creates default one deck of 52 playing cards in
         * originalDecks and copy them to dealDecks. initialize numberDecks=n Note:
         * You need to catch PlayingCardException from Card constructor Use
         * ArrayList for both originalDecks & dealDecks
         */
        public Decks() {
            // implement this method!
            originalDecks = new ArrayList<Card>();  
            numberDecks=1;
            for (int i = 0; i < numberDecks; i++) {
                
                for (int j = 0; j <= 3; j++) {
                    for (int k = 1; k <= 13; k++) {
                        try {
                            originalDecks.add(new Card(k, j));
                        } catch (PlayingCardException e) {
                            System.out.println("PlayingCardException: " + e.getMessage());
                        }
                    }
                }
            }
            dealDecks = new ArrayList<Card>(originalDecks);
        }
    
        /**
         * Constructor: Creates n decks (52 cards each deck) of playing cards in
         * originalDecks and copy them to dealDecks. initialize numberDecks=n Note:
         * You need to catch PlayingCardException from Card constructor Use
         * ArrayList for both originalDecks & dealDecks
         */
        public Decks(int n) {
            // implement this method!
            originalDecks = new ArrayList<Card>();        
            numberDecks = n;
            for (int i = 0; i < numberDecks; i++) {
                
                for (int j = 0; j <= 3; j++) {
                    for (int k = 1; k <= 13; k++) {
                        try {
                            originalDecks.add(new Card(k, j));
                        } catch (PlayingCardException e) {
                            System.out.println("PlayingCardException: " + e.getMessage());
                        }
                    }
                }
            }
            dealDecks = new ArrayList<Card>(originalDecks);
        }
        
    
        /**
         * Task: Shuffles cards in deal deck. Hint: Look at java.util.Collections
         */
        public void shuffle() {
            // implement this method!
            Collections.shuffle(this.dealDecks);
        }
    
        /**
         * Task: Deals cards from the deal deck.
         *
         * @param numberCards number of cards to deal
         * @return a list containing cards that were dealt
         * @throw PlayingCardException if numberCard > number of remaining cards
         *
         * Note: You need to create ArrayList to stored dealt cards and should
         * removed dealt cards from dealDecks
         *
         */
        public List<Card> deal(int numberCards) throws PlayingCardException {
            // implement this method!
    
            List dealtCards = new ArrayList<Card>();
            if (numberCards > dealDecks.size()) {
                    throw new PlayingCardException("Not enough cards to deal");
                } 
            for (int i = 0; i < numberCards; i++) {
                dealtCards.add(dealDecks.remove(0));
            }
            return dealtCards;
        }
    
        /**
         * Task: Resets deal deck by getting all cards from the original deck.
         */
        public void reset() {
            // implement this method!
            
            dealDecks = new ArrayList<Card>(originalDecks);
        }
    
        /**
         * Task: Return number of remaining cards in deal deck.
         */
        public int remain() {
            return dealDecks.size();
        }
    
        /**
         * Task: Returns a string representing cards in the deal deck
         */
        public String toString() {
            return "" + dealDecks;
        }
    
    
        /* Quick test                   */
        /*                              */
        /* Do not modify these tests    */
        /* Generate 2 decks of cards    */
        /* Loop 2 times:                */
        /*   Deal 30 cards for 4 times  */
        /*   Expect exception last time */
        /*   reset()                    */
        public static void main(String args[]) {
    
            System.out.println("*******    Create 2 decks of cards      *********\n\n");
            Decks decks = new Decks(2);
    
            for (int j = 0; j < 2; j++) {
                System.out.println("\n************************************************\n");
                System.out.println("Loop # " + j + "\n");
                System.out.println("Before shuffle:" + decks.remain() + " cards");
                System.out.println("\n\t" + decks);
                System.out.println("\n==============================================\n");
    
                int numHands = 4;
                int cardsPerHand = 30;
                for (int i = 0; i < numHands; i++) {
                    decks.shuffle();
                    System.out.println("After shuffle:" + decks.remain() + " cards");
                    System.out.println("\n\t" + decks);
                    try {
                        System.out.println("\n\nHand " + i + ":" + cardsPerHand + " cards");
                        System.out.println("\n\t" + decks.deal(cardsPerHand));
                        System.out.println("\n\nRemain:" + decks.remain() + " cards");
                        System.out.println("\n\t" + decks);
                        System.out.println("\n==============================================\n");
                    } catch (PlayingCardException e) {
                        System.out.println("*** In catch block : PlayingCardException : msg : " + e.getMessage());
                    }
                }
    
                decks.reset();
            }
        }
    }

  • #2
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts
    and here is SimplePoker.java
    Code:
    package PJ4;
    
    import java.util.*;
    import java.util.Collections;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /*
     * Ref: http://en.wikipedia.org/wiki/Video_poker
     *      http://www.google.com/ig/directory?type=gadgets&url=www.labpixies.com/campaigns/videopoker/videopoker.xml
     *
     *
     * Short Description and Poker rules:
     *
     * Video poker is also known as draw poker. 
     * The dealer uses a 52-card deck, which is played fresh after each currentHand. 
     * The player is dealt one five-card poker currentHand. 
     * After the first draw, which is automatic, you may hold any of the cards and draw 
     * again to replace the cards that you haven't chosen to hold. 
     * Your cards are compared to a table of winning combinations. 
     * The object is to get the best possible combination so that you earn the highest 
     * payout on the bet you placed. 
     *
     * Winning Combinations
     *  
     * 1. Jacks or Better: a pair pays out only if the cards in the pair are Jacks, 
     * 	Queens, Kings, or Aces. Lower pairs do not pay out. 
     * 2. Two Pair: two sets of pairs of the same card denomination. 
     * 3. Three of a Kind: three cards of the same denomination. 
     * 4. Straight: five consecutive denomination cards of different suit. 
     * 5. Flush: five non-consecutive denomination cards of the same suit. 
     * 6. Full House: a set of three cards of the same denomination plus 
     * 	a set of two cards of the same denomination. 
     * 7. Four of a kind: four cards of the same denomination. 
     * 8. Straight Flush: five consecutive denomination cards of the same suit. 
     * 9. Royal Flush: five consecutive denomination cards of the same suit, 
     * 	starting from 10 and ending with an ace
     *
     */
    /* This is the main poker game class.
     * It uses Decks and Card objects to implement poker game.
     * Please do not modify any data fields or defined methods
     * You may add new data fields and methods
     * Note: You must implement defined methods
     */
    public class SimplePoker {
    
        // default constant values
        private static final int startingBalance = 100;
        private static final int numberOfCards = 5;
        // default constant payout value and currentHand types
        private static final int[] multipliers = {1, 2, 3, 5, 6, 9, 25, 50, 250};
        private static final String[] goodHandTypes = {
            "Royal Pair", "Two Pairs", "Three of a Kind", "Straight", "Flush	",
            "Full House", "Four of a Kind", "Straight Flush", "Royal Flush"};
        // must use only one deck
        private static final Decks oneDeck = new Decks(1);
        // holding current poker 5-card hand, balance, bet    
        private List<Card> currentHand;
        private int balance;
        private int bet;
    
        /**
         * default constructor, set balance = startingBalance
         */
        public SimplePoker() {
            this(startingBalance);
        }
    
        /**
         * constructor, set given balance
         */
        public SimplePoker(int balance) {
            this.balance = balance;
        }
    
        /**
         * This display the payout table based on multipliers and goodHandTypes
         * arrays
         */
        private void showPayoutTable() {
            System.out.println("\n\n");
            System.out.println("Payout Table   	      Multiplier   ");
            System.out.println("=======================================");
            int size = multipliers.length;
            for (int i = size - 1; i >= 0; i--) {
                System.out.println(goodHandTypes[i] + "\t|\t" + multipliers[i]);
            }
            System.out.println("\n\n");
        }
    
        /**
         * Check current currentHand using multipliers and goodHandTypes arrays Must
         * print yourHandType (default is "Sorry, you lost") at the end of function.
         * This can be checked by testCheckHands() and main() method.
         */
        private void checkHands() {
            // implement this method!
            int rank = 0;
            String ranks;
    
            if (isRoyalPair() == true) {
                rank = 1;
            } else if (isTwoPair() == true) {
                rank = 2;
            }
            if (isThreeOfAKind() == true) {
                rank = 3;
            }
    
            if (isStraight() == true) {
                rank = 4;
            }
            if (isFlush() == true) {
                rank = 5;
            }
            if (isFullHouse() == true) {
                rank = 6;
            }
            if (isFourOfAKind() == true) {
                rank = 7;
            }
            if (isStraightFlush() == true) {
                rank = 8;
            }
            if (isRoyalFlush() == true) {
                rank = 9;
            }
    
    
            rank -= 1;
            if (rank < 0) {
                ranks = "Sorry, you lost!";
            } else {
                ranks = goodHandTypes[rank];
            }
    
            System.out.println("" + ranks);
    
    
            switch (ranks) {
                case "1":
                    this.balance += (this.bet * multipliers[0]);
                    break;
                case "2":
                    this.balance += (this.bet * multipliers[1]);
                    break;
                case "3":
                    this.balance += (this.bet * multipliers[2]);
                    break;
                case "4":
                    this.balance += (this.bet * multipliers[3]);
                    break;
                case "5":
                    this.balance += (this.bet * multipliers[4]);
                    break;
                case "6":
                    this.balance += (this.bet * multipliers[5]);
                    break;
                case "7":
                    this.balance += (this.bet * multipliers[6]);
                    break;
                case "8":
                    this.balance += (this.bet * multipliers[7]);
                    break;
                case "9":
                    this.balance += (this.bet * multipliers[8]);
                    break;
                default:
                    break;
            }
    
    
        }
    
        /**
         * ***********************************************
         * add new private methods here ....
         *
         ************************************************
         */
        private boolean isStraight() {
            return false;
    
        }
    
        private boolean isFlush() {
    
            for (int i = 0; i < numberOfCards; i++) {
                if (currentHand.get(i).getSuit() != currentHand.get(i + 1).getSuit()) {
                    return false;
                }
            }
    
            return true;
        }
    
        private boolean isStraightFlush() {
            if (isStraight() == true && isFlush() == true) {
                return true;
            }
            return false;
        }
    
        private boolean isRoyalFlush() {
            if (isFlush() == false || isStraight() == false) {
                return false;
            } else {
                if (currentHand.get(0).getRank() == 10) {
                    return true;
                }
                return false;
            }
        }
    
        private boolean isFourOfAKind() {
            return false;
        }
    
        private boolean isFullHouse() {
            if (isThreeOfAKind() == true && isOnePair() == true) {
                return true;
            } else {
                return false;
            }
        }
    
        private boolean isThreeOfAKind() {
            return false;
        }
    
        private boolean isTwoPair() {
            //check if it is four of a kind or two pair))
            if (isFourOfAKind() == true) {
                return false;
            }
            int numberOfPair = 0;
            int counter = 1;
    
            //implement moore
            return false;
        }
    
        private boolean isOnePair() {
            return false;
        }
    
        public boolean isRoyalPair() {
            return false;
        }
    
        public void play() {
            /**
             * The main algorithm for single player poker game
             *
             * Steps: showPayoutTable()
             *
             * ++ show balance, get bet verify bet value, update balance reset deck,
             * shuffle deck, deal cards and display cards ask for position of cards
             * to keep get positions in one input line update cards check hands,
             * display proper messages update balance if there is a payout if
             * balance = O: end of program else ask if the player wants to play a
             * new game if the answer is "no" : end of program else :
             * showPayoutTable() if user wants to see it goto ++
             */
            // implement this method!
            Scanner input = new Scanner(System.in);
            List<Card> keepCard = new ArrayList<Card>();
            int counter = 0;
            boolean newGame = true;
            boolean rightBet = false;
            while (newGame) {
                oneDeck.shuffle();
    
                showPayoutTable();
                System.out.println("Balance:" + balance + "\n");
                while (!rightBet) {
                    System.out.println("Enter bet:");
                    bet = Integer.parseInt(input.nextLine());
                    if (bet > balance) {
                        System.out.println("insufficient fund!");
                        rightBet = false;
                    } else {
                        rightBet = true;
                    }
    
                }
    
                balance = balance - bet;
                try {
                    currentHand = oneDeck.deal(5);
                } catch (PlayingCardException e) {
                    System.out.println("Exception dealing a new hand" + e.getMessage());
                }
                System.out.println("" + currentHand.toString());
                System.out.println("Enter positions to keep:");
                if (input.hasNext()) {
    
                    String s = input.nextLine();
                    if (!(input.nextLine() == "0")) {
                        input = new Scanner(s);
                        input = input.useDelimiter("\\s*");
                        while (input.hasNext()) {
                            keepCard.add(currentHand.get((input.nextInt()) - 1));
                            counter++;
                        }
                    }
                }
                currentHand = keepCard;
                try {
                    currentHand.addAll(oneDeck.deal(5 - counter));
                } catch (PlayingCardException e) {
                    System.out.println("Exception dealing the second hand" + e.getMessage());
                }
    
                System.out.println("" + currentHand.toString());
                //checkHands();
                System.out.println("Your balance: " + balance + " you want another game y/n ?");
    
    
                String s = input.nextLine();
    
                if (balance == 0) {
                    newGame = false;
                    break;
                }
                if (s == "y") {
                    newGame = true;
                } else {
                    newGame = false;
                }
    
                System.out.println("Want to see payout table ? (y/n)");
                s = input.nextLine();
                if (s == "y") {
                    showPayoutTable();
                }
                oneDeck.reset();
            }
            System.out.println("Bye");
    
    
        }
    
        public void testCheckHands() {
            try {
                currentHand = new ArrayList<Card>();
    
                // set Royal Flush
                currentHand.add(new Card(3, 2));
                currentHand.add(new Card(4, 3));
                currentHand.add(new Card(5, 3));
                currentHand.add(new Card(6, 3));
                currentHand.add(new Card(7, 3));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Straight Flush
                currentHand.set(0, new Card(9, 3));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Straight
                currentHand.set(4, new Card(8, 1));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Flush 
                currentHand.set(4, new Card(5, 3));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // "Royal Pair" , "Two Pairs" , "Three of a Kind", "Straight", "Flush	", 
                // "Full House", "Four of a Kind", "Straight Flush", "Royal Flush" };
    
                // set Four of a Kind
                currentHand.clear();
                currentHand.add(new Card(8, 3));
                currentHand.add(new Card(8, 0));
                currentHand.add(new Card(12, 3));
                currentHand.add(new Card(8, 1));
                currentHand.add(new Card(8, 2));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Three of a Kind
                currentHand.set(4, new Card(11, 3));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Full House
                currentHand.set(2, new Card(11, 1));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Two Pairs
                currentHand.set(1, new Card(9, 1));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // set Royal Pair
                currentHand.set(0, new Card(3, 1));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
    
                // non Royal Pair
                currentHand.set(2, new Card(3, 3));
                System.out.println(currentHand);
                checkHands();
                System.out.println("-----------------------------------");
            } catch (Exception e) {
                System.out.println("exception" + e.getMessage());
            }
        }
    
        /* Quick testCheckHands() */
        public static void main(String args[]) {
            SimplePoker mypokergame = new SimplePoker();
            mypokergame.testCheckHands();
        }
    }

  • #3
    New to the CF scene
    Join Date
    May 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    this forum is for javascript Not Java!

  • #4
    New to the CF scene
    Join Date
    Sep 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Sorry. I will repost in the appropriate section.

  • #5
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,636
    Thanks
    6
    Thanked 1,003 Times in 976 Posts
    No, please do not cross-post. If a thread is in the wrong section it will be moved. You just have to report it or let some moderator know in another way.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •