poker game in java

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 3847 Views - Last Post: 07 November 2010 - 10:48 PM Rate Topic: -----

#1 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

poker game in java

Posted 05 November 2010 - 11:31 AM

i've copy/pasted the code from this tutorial here and i'm trying to run it but it shows me that error.. i'm pretty new in java eclipse and i started to learning before 1 week because of my college :)
if anyone can guide me what is neccessery to make this poker game to work or to give me a few tips i will appreciate it!

Cheers,
best regards, aCceSs

Attached image(s)

  • Attached Image


Is This A Good Question/Topic? -1
  • +

Replies To: poker game in java

#2 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 11:40 AM

Apparently none of your classes includes a main. This is your entry-point, without it you can't compile.
Was This Post Helpful? 1
  • +
  • -

#3 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: poker game in java

Posted 05 November 2010 - 11:45 AM

You need a driver class , that is a class that contains a main method. You would use that to instantiate objects that are going to be used in your project.
Was This Post Helpful? 1
  • +
  • -

#4 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

Re: poker game in java

Posted 05 November 2010 - 11:56 AM

first of all thanks for answering so fast both of you!

to be honest i just found this one poker , can anyone guide me or give me a few tips how to make it work? i just wanna get a clue to understand what's happening with eclipse java and how to make a game :P is that hard for someone expert to teach me a few things with words or screen shots? i cannot recieve help from my friend(programmer) because he's left for army :-)

best regards,
aCceSs

This post has been edited by aCceSs: 05 November 2010 - 11:57 AM

Was This Post Helpful? 0
  • +
  • -

#5 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 12:08 PM

View PostaCceSs, on 05 November 2010 - 10:56 AM, said:

first of all thanks for answering so fast both of you!

to be honest i just found this one poker , can anyone guide me or give me a few tips how to make it work? i just wanna get a clue to understand what's happening with eclipse java and how to make a game :P is that hard for someone expert to teach me a few things with words or screen shots? i cannot recieve help from my friend(programmer) because he's left for army :-)

best regards,
aCceSs


That tutorial you posted tells you exactly how to use it. I see the person who posted it wrote a class called Main, you should read that and post it into your project to see if it compiles then.

This post has been edited by SarumanTheWhite: 05 November 2010 - 12:10 PM

Was This Post Helpful? 1
  • +
  • -

#6 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

Re: poker game in java

Posted 05 November 2010 - 12:15 PM

thanks a lot i will try to read it! but i have one another question, is it possible to make a graphical poker game with this code and eclipse java? and after that u just need to connect it with a database for login/password/names/chips ? or its more complicated? i dont wanna loose 4 years for this project if its cannot be successful... but now that im at college i just wanna try a project with my free 4 years time!
Was This Post Helpful? 0
  • +
  • -

#7 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 12:19 PM

A graphical game? For Java you'll need to look into the Swing library, as well as some Image libraries. As for Databases it can get fairly complicated depending on how far you are in your studies but not by much, however you may spend a lot more time studying Database concepts to make it effective such as ER diagrams, learn SQL, etc, etc.
Was This Post Helpful? 0
  • +
  • -

#8 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

Re: poker game in java

Posted 05 November 2010 - 12:32 PM

ok i manage to put all this code in my eclipse java but it shows me this error when i press "run" button :P can u check it out?

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#9 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 12:34 PM

Post your list of errors as well as the code you're using, it's hard to tell from the screen shot
Was This Post Helpful? 1
  • +
  • -

#10 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

Re: poker game in java

Posted 05 November 2010 - 12:50 PM

ok here is the full code, check it :) poker/src/playingcards/

Project name "poker"


Package name "playingcards"


errors is:
- File not Found: Hands.txt -

but it shows in code that more than 100 words are in red line :|



Card.java
//Card.java
//      Written by James Stewart
//      See PlayGame.java for main function & documentation.
//  Source Code: http://code.google.com/p/poker-java-classes/
package playingcards;

/**
 * Class to represent a playing card.
 * <p>
 * Related to:  http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html 
 */
public class Card {
        //Enumeration Values
        //      All the possible values the card can take.
        public enum Suit{Clubs, Diamonds, Hearts, Spades} 
        public enum Rank{Joker, Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King}//Joker has the ordinal value of 0, all other cards have their typical ordinal values.
        
        
        //Class Variables
        //      Properties of the card.
        private Suit suit;
        private Rank rank;
        private boolean wild; // Currently unused and outside of the requirements of this project.
        
        
        //Class Constructors
        Card(Rank rank){
                this.rank = rank;
                if( rank.toString().equals("Joker") )
                        this.wild = true;
        }
        
        Card(Rank rank, Suit suit){
                this(rank,suit,false);
        }
        
        /**
         * Card's Main Class Constructor
         * @param rank          rank of card.
         * @param suit          suit of card.
         * @param wild          is card wild?
         */
        Card(Rank rank, Suit suit, boolean wild){
                this.rank = rank;
                this.suit = suit;
                this.wild = wild;
        }


        //Accessor Functions
        public Rank rank() { return rank; }
        public Suit suit() { return suit; }
        public boolean isWild() { return wild; }
        public String toString()
        {
                return toString(false); //assumes the console cannot handle Unicode
        }
        /**
         * Creates a string representation of the card.
         *              Uses unicode if possible.
         * @param bUnicode              uses unicode if true, does not otherwise.
         * @return                              string representing the card.
         */
        public String toString(boolean bUnicode)
        {
                if(bUnicode) 
                        return print(); 
                else if(rank != null && suit != null)
                        return rank.toString() + " of " + suit.toString();
                else
                        return "* InValid Card *";
        }
        
        
        //Member Functions
        /**
         * Creates a string representation of the card using unicode to represent the suit.
         * @return              string representation of the card.
         */
        private String print()
        {
                String sCardPrint = "";

                if(rank != null)
                {
                        switch(rank){
                                case Two:       sCardPrint += " 2";break;
                                case Three:     sCardPrint += " 3";break;
                                case Four:      sCardPrint += " 4";break;
                                case Five:      sCardPrint += " 5";break;
                                case Six:       sCardPrint += " 6";break;
                                case Seven:     sCardPrint += " 7";break;
                                case Eight:     sCardPrint += " 8";break;
                                case Nine:      sCardPrint += " 9";break;
                                case Ten:       sCardPrint += "10";break;
                                case Jack:      sCardPrint += " J";break;
                                case Queen:     sCardPrint += " Q";break;
                                case King:      sCardPrint += " K";break;
                                case Ace:       sCardPrint += " A";break;
                                case Joker:     sCardPrint += "*J";break;
                                default:        sCardPrint += "-NO RANK-";break;
                        }
                }
                
                if(suit != null)
                {
                        switch(suit){
                                case Clubs:             sCardPrint += "\u2663";break;
                                case Diamonds:  sCardPrint += "\u2666";break;
                                case Hearts:    sCardPrint += "\u2665";break;
                                case Spades:    sCardPrint += "\u2660";break;
                                default:                sCardPrint += "-NO SUIT-";break;
                        }
                }
                
                if(wild)
                        sCardPrint += "*";
                
                return sCardPrint;
        }

        
        //Auto-Generated by Eclipse:
        @Override
        public int hashCode() {
                final int prime = 31;
                int result = 1;
                result = prime * result + ((rank == null) ? 0 : rank.hashCode());
                result = prime * result + ((suit == null) ? 0 : suit.hashCode());
                result = prime * result + (wild ? 1231 : 1237);
                return result;
        }

        @Override
        public boolean equals(Object obj) {
                if (this == obj)
                        return true;
                if (obj == null)
                        return false;
                if (getClass() != obj.getClass())
                        return false;
                Card other = (Card) obj;
                if (rank == null) {
                        if (other.rank != null)
                                return false;
                } else if (!rank.equals(other.rank))
                        return false;
                if (suit == null) {
                        if (other.suit != null)
                                return false;
                } else if (!suit.equals(other.suit))
                        return false;
                if (wild != other.wild)
                        return false;
                return true;
        }
}



Game.java
//Game.java
//      Written by James Stewart
//      See PlayGame.java for main function & documentation.
//  Source Code: http://code.google.com/p/poker-java-classes/
package playingcards;

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

/**
 * Class representing a Game of poker.
 * Currently only used for a single round of play.
 * @author James
 *
 */
public class Game {
        //Enumeration Values
        
        
        //Class Variables
        private Rules rGameRules; // The Rules of the game
        private int iNumberOfPlayers; // Number of Players playing the game
        private ArrayList<Player> alPlayers; // The players
        private ArrayList<Player> alpWinners; // the winning player(s)  ... if more than one, break tie, if still tie, split pot.

        
        //Class Constructors
        Game()
        {
                this.rGameRules = new Rules();
                this.alPlayers = new ArrayList<Player>(rGameRules.maxPlayers());
                this.iNumberOfPlayers = 0;
        }
        
        Game(ArrayList<Player> Players)
        {
                this.rGameRules = new Rules(Players.size());
                this.alPlayers = Players;
                this.iNumberOfPlayers = Players.size();
        }
        
        Game(List<Player> Players)
        {
                this.rGameRules = new Rules(Players.size());
                this.alPlayers = new ArrayList<Player>();
                
                for(int i=0;i<Players.size();i++)
                        alPlayers.add(Players.get(i));
                
                this.iNumberOfPlayers = Players.size();
        }
        
        
        //Accessor Functions
        public int players(){ return iNumberOfPlayers; }
        public Rules rules(){ return rGameRules; }
        public boolean addPlayer(Player player)
        {
                if(alPlayers.size() < rGameRules.maxPlayers())
                {
                        iNumberOfPlayers++;
                        return alPlayers.add(player);
                }
                else
                        return false;
        }
        public boolean remPlayer(Player player)
        {
                return alPlayers.remove(player);
        }
        public String toString(){ return toString(false); }
        public String toString(boolean bUnicode){ return print(bUnicode); }
        
        
        //Member Functions
        private String print(boolean bUnicode)
        {
                String sReturn = "";
                if(alpWinners == null)
                        determineWinner();
                
                for(int i=0;i<alPlayers.size();i++)
                        sReturn += alPlayers.get(i).toString(bUnicode) + "\n";
                
                if(alpWinners != null && alpWinners.size() == 1)
                        sReturn += "   The Winner is " + alpWinners.get(0).name();// + ". Player # " + (++iWinner).toString();
                else
                        sReturn += "   There is a " + alpWinners.size() + "-way Tie.";
                        
                return sReturn + "\n";
        }
        
        
        private void determineWinner()
        {
                alpWinners = new ArrayList<Player>(alPlayers.size());
                int iHighHand = 0;
                for(int i=0;i<alPlayers.size();i++)
                {
                        if(alPlayers.get(i).hand().value().ordinal() == iHighHand)
                        {
                                alpWinners.add(alPlayers.get(i));
                        }
                        if(alPlayers.get(i).hand().value().ordinal() > iHighHand)
                        {
                                iHighHand = alPlayers.get(i).hand().value().ordinal();
                                alpWinners.clear();
                                alpWinners.add(alPlayers.get(i));
                        }
                }
                
                if(alpWinners.size() > 1)
                {
                        //Break Tie
                        breakTie();
                }
        }
        
        
        // TODO fix breakTie
        // not working:
        private void breakTie()
        {
                /**
                 * NOTE!! ACE is the high card, but its ordinal value is 1   !!!!
                 * 
                 * There is a Tie, so all players in "alpWinners" must have hands of the same value.
                 * 
                 * If Straight or Straight Flush: The highest card of each players hand determines the winner, if they are the same, there is still a tie.
                 * 
                 * If Flush: The highest card of each of the players flush wins, unless they are the same, then the next highest, and so on.
                 * 
                 * If "High Card": Same as flush.
                 * 
                 * If "Three of a Kind" or "Four of a Kind" or "Full House": The paired card of 3 or more determines the winner... there cannot be a tie ASSUMING NO WILDS!!!
                 * 
                 * If "Pair" or "Two Pair": highest of the pairs wins, otherwise highest card
                 */
                
                switch(alpWinners.get(0).hand().value()){
                        case HighCard:          breakTieAllCards(); break;
                        case Pair:                      breakTie1Pair(); break;
                        case TwoPair:           break;
                        case ThreeKind:         breakTie1Pair(); break;
                        case Straight:          breakTieHighCard(); break;
                        case Flush:                     breakTieAllCards(); break;
                        case FullHouse:         break;
                        case FourKind:          breakTie1Pair(); break;
                        case StraightFlush: breakTieHighCard(); break;
                        case InValid:           break;
                        default:                        break;
                }
        }

        private void breakTieHighCard()
        {
                breakTieHighCard(1);
        }
        private void breakTieHighCard(Integer iPos) {
                Integer iCurrentHighestCard = 0;
                for(int i=0; i<alpWinners.size(); i++)
                        if(iCurrentHighestCard < alpWinners.get(i).hand().highCard(iPos))
                                iCurrentHighestCard = alpWinners.get(i).hand().highCard(iPos);
                
                for(int i=0; i<alpWinners.size(); i++)
                        if(iCurrentHighestCard > alpWinners.get(i).hand().highCard(iPos))
                                alpWinners.remove(i);
        }
        
        private void breakTieAllCards()
        {
                for(int i=1; i<=alpWinners.get(0).hand().cards(); i++)
                {
                        breakTieHighCard(i);
                        
                        if(1 == alpWinners.size())
                                break;
                }
        }
        
        private void breakTie1Pair()
        {
                Integer iCurrentHighestCard = 0;
                Integer iCurrentCard = 0;
                for(int i=0; i<alpWinners.size(); i++)
                {
                        iCurrentCard = alpWinners.get(i).hand().getHmRankPairings().keySet().iterator().next().ordinal();
                        if(1 == iCurrentCard)
                                iCurrentCard = 14;
                        if(iCurrentHighestCard < iCurrentCard)
                                iCurrentHighestCard = iCurrentCard;
                }
                
                for(int i=0; i<alpWinners.size(); i++)
                        if(iCurrentHighestCard > alpWinners.get(i).hand().getHmRankPairings().keySet().iterator().next().ordinal())
                                alpWinners.remove(i);
                
                if(alpWinners.size() > 1)
                        breakTieAllCards();
        }
}



Hand.java
//Hand.java
//      Written by James Stewart
//      See PlayGame.java for main function & documentation
//  Source Code: http://code.google.com/p/poker-java-classes/
package playingcards;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import playingcards.Card.Rank;

//TODO documentation
public class Hand {
        //Enumeration Values
        //      All the possible values the hand can take.
        //      Should Five of a kind be handled? Should the hand report its best value, even if its illegal, and leave it up to the "Game" to determine this, allowing for alternative play & wild cards?
        public enum Value{InValid, HighCard, Pair, TwoPair, ThreeKind, Straight, Flush, FullHouse, FourKind, StraightFlush} 
        
        
        //Class Variables
        private int iCards; //Valid number of cards in a hand.
        private ArrayList<Card> hand; //An array of Cards. //http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html
        private HashMap<Card.Rank, Integer> hmRankPairings;
        private Value value;
        private int[] iaRanks;
        
        //Class Constructors
        Hand(int iCards){
                this(iCards, null);
        }
        
        Hand(Card[] cards){
                this(cards.length, cards);
                //this.hand = cardArraytoArrayList(cards);
                //this.iCards = cards.length;
        }
        
        /**
         * Class' Main Constructor
         * @param iCards        number of cards in a valid hand.
         * @param cards         array of cards to place in hand.
         */
        Hand(int iCards, Card[] cards){
                this.iCards = iCards;
                if(cards != null && cards.length == iCards)
                        this.hand = cardArraytoArrayList(cards); //http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=013981
                else
                        this.hand = null;
        }
        
        
        //Accessor Functions
        public int cards(){ return iCards; }
        public ArrayList<Card> handAL(){ return hand;}
        public Card[] hand(){ return (Card[])hand.toArray();}
        //public void setHmRankPairings(HashMap<Card.Rank, Integer> hmRankPairings) {this.hmRankPairings = hmRankPairings;}
        public HashMap<Card.Rank, Integer> getHmRankPairings() {
                return hmRankPairings;
        }

        public String toString(){ return toString(false); }
        public String toString(boolean bUnicode){ return printHand(bUnicode); }
        public boolean addCard(Card card)
        {
                if(this.hand.size() < this.iCards)
                {
                        //Consider using array list instead of array to remove the need for the following line's complicated nature.
                        this.hand.add(card);
                        return true;
                }
                else
                        System.out.println("-Error: playingcards.Hand: Tried to add more cards to a hand than is allowed.");                    //ERROR!!! (throw exception?)
                
                return false;
        }
        public boolean removeCard(Card card)
        {
                boolean bCardRemoved = false;
                int index = hand.indexOf(card);
                
                if(index >= 0) //http://java.sun.com/j2se/1.4.2/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
                {
                        this.hand.remove(index);
                        bCardRemoved = true;
                }
                        
                return bCardRemoved;
        }
        public boolean empty()// Empties the hand to add cards for the next round of play.
        {
                if(hand.size() > 0)
                        this.hand.clear();
                else
                        return false; // returns false if the hand was empty to begin with
                
                return true; // returns true if the hand was cleared
        }
        public Value value()
        {
                if(value == null)
                        this.determineValue();
                
                return value;
        }


        //Member Functions
        /**
         * Utility function that converts an array of Card to an ArrayList of Card.
         * @param cards         array of cards to convert.
         * @return                      ArrayList of cards from the array of cards.
         */
        private ArrayList<Card> cardArraytoArrayList(Card[] cards)
        {
                return new ArrayList<Card>(Arrays.asList(cards)); //Converts array of cards into ArrayList<Card>
        }
        
        /**
         * Creates a string representation of the cards in the hand.
         * @param bUnicode              uses unicode if true, does not otherwise.
         * @return                              string representation of the hand.
         */
        private String printCards(boolean bUnicode)
        {
                String cardText = "";
                int i = 0;
                
                if(hand != null && hand.size() >= 1)
                {
                        while( i < hand.size() - 1 ){
                                cardText += hand.get(i).toString(bUnicode) + ", ";
                                i++;
                        }
                        cardText += hand.get(i).toString(bUnicode);
                
                        return cardText;
                }
                else
                        return "*NO HAND*";
        }
        
        /**
         * Creates a string representation of the hand's value.
         *              If the hand does not have a valid value, it will represent the cards in the hand instead.
         * @param bUnicode              uses unicode if true, does not otherwise.
         * @return                              string representation of the hand's value.
         */
        private String printHand(boolean bUnicode)
        {
                if(value == null)
                        if(isValid())
                                determineValue();
                        else
                                value = Value.InValid;

                
                if(value != null)
                {
                        switch(value){
                                case HighCard:          return "A High Card";
                                case Pair:                      return "A Pair";
                                case TwoPair:           return "Two Pair";
                                case ThreeKind:         return "Three of a Kind";
                                case Straight:          return "A Straight";
                                case Flush:                     return "A Flush";
                                case FullHouse:         return "A Full House";
                                case FourKind:          return "Four of a Kind";
                                case StraightFlush: return "A Straight Flush";
                                case InValid:           return " *InValid Hand* " + printCards(bUnicode); // will print out the cards if there are any.
                                default:                        return "-BAD HAND-";
                        }
                }
                else
                        return printCards(bUnicode); //if value cannot be determined, then the cards themselves are printed
        }
        
        /**
         * Validates the contents of the hand.
         * @return              true if the hand is valid, false otherwise.
         */
        boolean isValid() //Checks if the hand is valid
        {
                if(hand == null)
                        return false;
                else
                        if(iCards == hand.size())
                                for(int i=0;i<iCards;i++)
                                        if(hand.get(i) == null || hand.get(i).suit() == null || hand.get(i).rank() == null || hand.get(i).rank().ordinal() > 13 || hand.get(i).rank().ordinal() < 1)
                                                return false;
                                        

                return true;
        }
        
        /**
         * Determines the value of the hand.
         * Sets the value variable based on the cards in the hand.
         * <p>
         * Checks for:
         *              Flushes         - All cards are the same suit.
         *              Pairings        - Some cards have the same rank.
         *              Straights       - The hand forms a run which contains all cards in the hand.
         *                                      - A run is a grouping of cards who's rank is sequential, typically consisting of 3 or more cards.
         *                                      - A run does not have significance in most poker.
         * <p>
         * Assuming a standard 52 Card deck: (The algorithms do not assume this, but do assume there are no wild cards)
         *              If there is a flush, there cannot be pairings.
         *              If there are pairings, there cannot be a flush.
         * 
         *              If there is a pairing, there cannot be straight.
         *              If there is a straight, there cannot be a pairing.
         * 
         *              If there is a run, there COULD be a pairing.
         *              If there is a pairing there COULD be a run.
         * <p>
         * High Card algorithm:
         *              1. If there are no Flushes, Straights, or Pairings, then the hand's value is High Card.
         * <p>
         * ISSUES: (none are required by the assignment)
         *              Handling wild cards does not exist yet.
         *                      add 1 for each wild in hand to iStraight in isStraight
         *                      add 1 for each wild in hand to Pair type determined, full house is an issue (two pair becomes full house).
         *              Handling hands with greater than five cards is untested, but should work.
         *              Handling "Best 5 card hand out of 7 cards" like in Texas Hold'em:
         *                              requires separate checks for the right number of cards in hand & how many card are in a proper Straight.
         *              Handling Omaha hasn't even been considered. 
         *              
         */
        private void determineValue()
        {       
                findPairings();
                        
                boolean bFlush = isFlush();
                boolean bPairings = isPair();
                
                boolean bStraight = false;
                
                if(!bPairings)//if bPairings = false, then determine if a Straight exists.
                        bStraight = isStraight();
                        
                setHandValue(bFlush, bPairings, bStraight);
                
                assert(bPairings != bStraight);
                assert(value != null);
        }

        /**
         * Sets the value of the hand
         *              based upon determineValue()'s results
         * @param bFlush                Hand?isFlush
         * @param bPairings             Hand?isPair
         * @param bStraight             Hand?isStraight
         */
        private void setHandValue(boolean bFlush, boolean bPairings, boolean bStraight) {
                if(bPairings)//if bPairings = true && bStraight = false, then determine what type of pairings exist.(pair, 2pair, 3kind, 4kind, fullhouse)
                        setHandValuePairs();            
                
                if(bStraight && bFlush)
                        value = Value.StraightFlush;
                                
                if(bStraight && !bFlush)
                        value = Value.Straight;
                
                if(bFlush && !bStraight)
                        value = Value.Flush; // if there is no straight (and no straight flush), but there is a flush, then the hand value is flush.
                        
                if(!bFlush && !bStraight && !bPairings)
                        value = Value.HighCard; //if nothing else, then high card hand.
        }

        /**
         * Sets the hand value for hands containing pairs.
         * <p>
         * Pair type algorithm:
         *              1. If the {@link HashMap} has any Key with the Value of 4, then the hand's value is Four of a Kind.
         *              2. If the {@link HashMap} has any Key with the Value of 3, and no Key with Value of 2, then the hand's value is Three of a Kind.
         *              3. If the {@link HashMap} has any Key with the Value of 3, and also a Key with the Value of 2, then the hand's value is Full House.
         *              4. If the {@link HashMap} has any Key with the Value of 2, and has no other Key's with the Value of 2, then the hand's value is a Pair.
         *              5. If the {@link HashMap} has any Key with the Value of 2, and has another Key with the Value of 2, then the hand's value is Two Pair.
         */
        private void setHandValuePairs() {
                
                while(hmRankPairings.values().remove(1))
                {
                        //do nothing, it will remove each time it finds a value(1) until there are none left, at which point there should only be entries for pairs
                }
                
                if(hmRankPairings.containsValue(4))
                {
                        value = Value.FourKind;
                }
                else if(hmRankPairings.containsValue(3))
                {
                        if(hmRankPairings.containsValue(2))
                                value = Value.FullHouse;//need to make sure high card rank is set to 3 of a kind
                        else
                                value = Value.ThreeKind;
                }
                else if(hmRankPairings.containsValue(2))
                {
                        if(hmRankPairings.values().size() == 2) //This means there are 2 sets of pairs
                                value = Value.TwoPair; //need to make sure high card rank is set to the greater of the two-pair.
                        else
                                value = Value.Pair;
                }
        }
        
        public Integer highCard()
        {
                return highCard(1);
        }
        public Integer highCard(Integer iPosition)
        {
                if(iaRanks == null)
                {
                        iaRanks = new int[hand.size()];
                        for(int i=0;i<hand.size();i++)
                        {
                                iaRanks[i] = hand.get(i).rank().ordinal();
                                
                                if(1 == hand.get(i).rank().ordinal())
                                        iaRanks[i] = 14;
                        }
                        java.util.Arrays.sort(iaRanks);
                }
                
                assert(iPosition > 0);
                assert(iPosition <= iaRanks.length);
                return iaRanks[iaRanks.length - iPosition];
        }
        
        /**
         * Determines if there is a Straight.
         * <p>
         * Straight determination algorithm:
         *              1. Determine if the hand contains an Ace(1)
         *              2. Find Highest Value Card
         *              3. If the Max Card is a King(13) && The hand contains an Ace, set iHighCardRank to 14
         *              4. For each card iCards(5) away from the Max card, add 1 to iStraight
         *              5. If iStraight == iCards(5), then all cards in hand form a straight
         * @return              true if there is a straight, false otherwise.
         */
        private boolean isStraight() {
                Integer iStraight = 1; //the first is the high card, whatever it may be.
                Integer iHighCardRank = 0;
                
                // 1. Determine if the hand contains an Ace(1)
                boolean bAceInHand = isAce();

                // 2. Find Highest Value Card
                for(int i=0;i<hand.size();i++)
                {
                        if(hand.get(i).rank().ordinal() > iHighCardRank)
                                iHighCardRank = hand.get(i).rank().ordinal();
                }
                
                // 3. If the Max Card is a King(13) && The hand contains an Ace, set iHighCardRank to 14
                if(iHighCardRank == Rank.King.ordinal() && bAceInHand)
                {
                        iHighCardRank = 14;
                }
                
                // 4. For each card iCards(5) away from the Max card, add 1 to iStraight
                for(int i=0;i<hand.size();i++)
                {
                        if(hand.get(i).rank().ordinal() > iHighCardRank - iCards && hand.get(i).rank().ordinal() < iHighCardRank)
                                iStraight++;
                }
                        
                // 5. If iStraight == iCards(5), then all cards in hand form a straight
                if(iStraight == iCards)
                        return true; //Straight
                else
                        return false; //No Straight
        }

        /**
         * Sets up hmRankPairings based upon pairs in the hand.
         * <p>
         * Pairing determination algorithm:
         *              1. Iterate over all of the cards in the hand.
         *              2. If the rank of the card is not in the {@link HashMap}, then add it to the {@link HashMap}.
         *              3. If the rank of the card is found in the {@link HashMap}, increment its value by one.
         *              4. If the {@link HashMap} has as many Keys as total cards in the hand, there are no pairings.
         *              5. If the {@link HashMap} has less Keys than total cards in hand, then there must be pairings.
         */
        private void findPairings() {
                hmRankPairings = new HashMap<Card.Rank, Integer>(iCards);
                
                // The HashMap will contain one of each rank and how many times they occur. http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html
                getHmRankPairings().put(hand.get(0).rank(), 1); // puts the first card's rank in the HashMap
                for(int i=1;i<iCards;i++)
                {
                        if(getHmRankPairings().containsKey(hand.get(i).rank())) // Checks for duplicated ranks
                        {
                                getHmRankPairings().put(hand.get(i).rank(), getHmRankPairings().get(hand.get(i).rank()) + 1 ); // increments the counter for the rank if more than one are found.
                        }
                        else
                                getHmRankPairings().put(hand.get(i).rank(), 1); // Adds a rank that does not yet exist in the HashMap.
                }
        }
        
        /**
         * Determines if there is a flush.
         * <p>
         * Flush determination algorithm:
         *              1. Assume there is a flush
         *              2. Get the suit of the first card in the hand
         *              3. Iterate over all other cards in the hand
         *              4. Check if any card has a suit different that the first card
         *              5. If a different suit is found, there is no flush (return false)
         *              6. If no different suit is found, there is a flush (return true)
         * @return              true if there is a flush, false otherwise.
         */
        public boolean isFlush()
        {
                Card.Suit suitFlush = hand.get(0).suit(); // get the suit of the first card in the hand
                for(int i=1;i<iCards;i++)
                        if(suitFlush != hand.get(i).suit())// Only change flush to false if you find a suit that doesn't match the first
                                return false;
                
                return true;
        }
        
        /**
         * Determines if there is an Ace in Hand.
         * @return              true if there is an Ace, false otherwise
         */
        public boolean isAce()
        {
                for(int i=0;i<iCards;i++)
                        if(hand.get(i).rank() == Rank.Ace)
                                return true;
                
                return false;
        }
        
        /**
         * Determines if there are pairs in the hand.
         *              Based upon hmRankPairings set up in findPairings()
         * @return              true if there is a pair, false otherwise.
         */
        public boolean isPair()
        {
                if(getHmRankPairings() != null && getHmRankPairings().size() > 0 && getHmRankPairings().size() < iCards) // if the number of different ranks is less than the number of cards, then there are pairings & no straight.
                        return true;
                
                return false;
        }
}



HandTest.java
package playingcards;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

import playingcards.Card.Rank;
import playingcards.Card.Suit;

public class HandTest {
        private Card card1;
        private Card card2;
        private Card card3;
        private Card card4;
        private Card card5;
        private Hand hPair;
        private Hand hFlush;
        private Hand hAce;
        private Hand hNoAce;
        private Hand hInValid;
        private Hand hStraight;
        private Hand hAceLowStraight;
        //private Hand hAceHighStraight;
        //private Hand hStraightFlush;
        
        @Before
        public void setUp() throws Exception {
                card1 = new Card(Rank.Ace, Suit.Clubs);
                card2 = new Card(Rank.Two, Suit.Clubs);
                card3 = new Card(Rank.Three, Suit.Clubs);
                card4 = new Card(Rank.Four, Suit.Clubs);
                card5 = new Card(Rank.Five, Suit.Clubs);
                
                Card[] cards = {card1, card2, card3, card4, card5};
                hAce = hAceLowStraight = hFlush = hStraight = new Hand(cards);
                hInValid = new Hand(7, cards);
                
                card1 = new Card(Rank.Three, Suit.Spades);
                Card[] cards2 = {card1, card2, card3, card4, card5};
                hNoAce = hPair = new Hand(cards2);
        }

        @Test
        public void testIsValid() {
                Assert.assertTrue("Good Hand", hAceLowStraight.isValid());
                Assert.assertTrue("Not enough Cards in constructor", !hInValid.isValid());
        }

        @Test
        public void testIsFlush() {
                Assert.assertTrue(hFlush.isFlush());            
                Assert.assertTrue(!hPair.isFlush());
        }

        @Test
        public void testIsAce() {               
                Assert.assertTrue(hAce.isAce());
                Assert.assertTrue(!hNoAce.isAce());
        }

        @Test
        public void testIsPair() {
                Assert.assertTrue(!hStraight.isPair());
                
                //Assert.assertTrue(hPair.isPair());            
        }

}



Player.java
//Player.java
//      Written by James Stewart
//      See PlayGame.java for main function & documentation
//      Source Code: http://code.google.com/p/poker-java-classes/
package playingcards;

/**
 * Class that represents a Player.
 * @author James
 *
 */
public class Player {
        //Enumeration Values
        
        
        //Class Variables
        private String name; // Name of player.
        private Hand hand; // The players hand.
        private int bet; // Players current bet.
        private int purse; // Amount of $$$ the player has to bet from.
        
        
        //Class Constructors
        Player(String name, int iCards)
        {
                this.name = name;
                this.hand = new Hand(iCards);
                this.bet = 0;
                this.purse = 1000;
        }
        
        Player(String name, Card[] cards)
        {
                this.name = name;
                this.hand = new Hand(cards);
                this.bet = 0;
                this.purse = 1000;
        }
        
        Player(String name, Hand hand)
        {
                this.name = name;
                this.hand = hand;
                this.bet = 0;
                this.purse = 1000;
        }
        
        
        //Accessor Functions
        public String name(){ return name; }
        public Hand hand(){ return hand; }
        public int bet(){ return bet; }
        public int purse(){ return purse; }
        public String toString(){ return toString(false); }
        public String toString(boolean bUnicode){ return "Player: " + name + " - " + hand.toString(bUnicode); }
        //TODO addHand, clearHand, addCard, removeCard
        
        
        //Member Functions
}



PlayGame.java

//PlayGame.java
/**
 * Poker playing Java Program
 *              Written by James Stewart (jgs194@psu.edu) #1994         9-23-2008
 *              Written with the Eclipse Platform v3.4.0
 *              Source Code: http://code.google.com/p/poker-java-classes/
 * <p>
 * References to the URL of websites used for guidance are included as line comments wherever possible. 
 *              Many aspects of the Card class are very similar to one on http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html
 *              All of the algorithms used to determine the value of a hand are original and no outside sources were consulted.
 * <p>          
 * Eclipse is definitely partly responsible for making writing this program much easier. "AutoComplete" like found in VisualStuido is invaluable for learning member functions of classes.
 * <p>
 * Classes:
 *              Card    - Responsible for representing a playing card.
 *              Hand    - Responsible for representing a players hand, a grouping of cards & determining the poker value of the hand. (the algorithms for determining the value of the hand being the bulk of the assignment)
 *              Player  - Responsible for representing a player.
 *              Rules   - Responsible for representing the rules of the particular game.
 *              Game    - Responsible for the rules of the game, as well as determining a winner of a round of cards & ensuring the players behave legally.
 *                              -       The Game class should also determine if the cards in each hand are legal, as well as all cards played per round, based upon given constraints.
 *              PlayGame- The class which actually reads the hands in from a file and "plays" the hands.
 * <p>
 * Problems:
 *              Tie Breaking algorithm is not completed entirely.
 *              There's something wrong with the hand.determinevalue function's finding of straights that contain an ace, which was working at one point.
 */
//TODO implement comparable interfaces for card/hand
//TODO code cleanup

package playingcards;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.io.File;

import playingcards.Card.Rank;
import playingcards.Card.Suit;

/**
 * A Poker Game playing class.
 * @author James
 *
 */
public class PlayGame {
        private static boolean bUnicode = false; // if the system supports unicode, this will be set to true. Used to decide to do unicode printing.
        
        /**
         * The main function that coordinates playing the hands of poker from a file.
         * <p>
         * The file is assumed to be "Hands.txt" if no file is specified.
         * @param args          command line arguments to the program, which will be checked for a file to read from. (optional)
         */
        public static void main(String[] args)
        {
                bUnicode = isSystemUnicode(); // If the console supports unicode, then the cards will be printed using the unicode representations of the suits, instead of text.
                String sTextFile = "Hands.txt"; //Hands.txt is the default location of the file which the poker hands will be read from.
                if(args != null && args.length > 0)//Verifies there was a command line argument passed to the program.
                        sTextFile = args[0]; //Sets the location of the text file based upon the first command line argument.
                
                playGames(getPlayersFromFile(sTextFile)); // read file, process lines to players, "Play Games" with pairs of players.
        }
        
        /**
         * Plays poker games with each pair of players.
         * @param alpPlayers    players of the games.
         */
        public static void playGames(ArrayList<Player> alpPlayers)
        {
                // 2 Players per game for the assignment.
                Game gGame = null;
                for(int i=0;i<alpPlayers.size();i=i+2)
                {
                        gGame = new Game(alpPlayers.subList(i, i+2));
                        System.out.println(gGame.toString(bUnicode)); //Print Results to screen.
                }
        }
        
        /**
         * Determines if Unicode can be printed to the console.
         * @return              true if the console can accept Unicode, false otherwise.
         */
        public static boolean isSystemUnicode()
        {
                String sEncoding = Charset.defaultCharset().name();
                if(sEncoding == "UTF-8" || sEncoding == "UTF-16" || sEncoding == "UTF-16LE" || sEncoding == "UTF-16BE") //http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html
                        return true; 
                else
                        return false;
        }
        
        /**
         * Reads all the lines in a file to an ArrayList<String>
         * @param sTextFile             location of the file on the hard drive to read from.
         * @return                              the lines of the file as ArrayList<String>
         */
        public static ArrayList<String> readFile(String sTextFile)
        {
                ArrayList<String> alsRawText = new ArrayList<String>();
                //http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
                try {
                        // Open file
                        FileInputStream fstream = new FileInputStream(sTextFile);
                        BufferedReader brRead = new BufferedReader(new InputStreamReader(fstream));
                        String sLine = "";
                        while((sLine = brRead.readLine()) != null)
                        {
                                alsRawText.add(sLine);
                        }
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        System.out.println("- File not Found: " + sTextFile + " - ");
                        e.printStackTrace();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.out.println("- Bad File ReadLine -");
                        e.printStackTrace();
                }
                return alsRawText;
        }
        
        /**
         * Takes a single line as String and processes it into a player's name & hand, if possible.
         * <p>
         *       Valid form is "(PlayerName): (rank) of (suit), (rank) of (suit), (rank) of (suit), (rank) of (suit), (rank) of (suit)"
         * @param sRawText              string containing the raw text representation of the player.
         * @return                              player representation of the raw text.
         */
        public static Player processRawText(String sRawText)
        {
                Card[] caCards = new Card[5];
                Suit suit;
                Rank rank;
                String sName = sRawText.subSequence(0, sRawText.indexOf(58)).toString(); //58 is ascii code for ':'
                
                // Gets the raw text of just the card values:
                String sCards = sRawText.subSequence(sRawText.indexOf(58) + 1, sRawText.length()).toString();
                sCards = sCards.replace(" of", ","); // Replaces the text "of" with commas for splitting.
                String[] saCards = sCards.split(", ");// Even indexes are now ranks, Odd indexes are now Suit;
                
                for(int i=0;i<saCards.length-1;i=i+2)
                {
                        //TODO implement Bounds checking
                        if(saCards[i].matches(" *[0-9]+ *")) // If its a number, get the rank by its ordinal value in the enumeration
                                if(Integer.parseInt(saCards[i].trim()) < 14)
                                        rank = Rank.values()[Integer.parseInt(saCards[i].trim())];
                                else
                                {
                                        System.out.println("- Rank out of valid range:  " + saCards[i] + " > (1-13) ");
                                        rank = null;
                                }
                        else // If its not a number, get the rank by comparison to the enumeration values.
                                rank = Rank.valueOf(saCards[i].trim());
                        
                        suit = Suit.valueOf(saCards[i+1].trim()); //The suit is always the next in the array after the rank
                        
                        caCards[i/2] = new Card(rank,suit); //There are half as many cards as entries in the split array & i is always even, so i/2 maps the index properly
                }
                return new Player(sName, caCards);
        }
        
        /**
         * Gets all the raw text from the file, then sends it along for processing.
         * @param sFileName             location of the file on the hard drive to read from.
         * @return                              players found in the file.
         */
        public static ArrayList<Player> getPlayersFromFile(String sFileName)
        {
                ArrayList<Player> alpPlayers = new ArrayList<Player>();
                ArrayList<String> alsRawText = null;
                File fFileToCheck = new File(sFileName);
                
                if(fFileToCheck.exists()) // Make sure the file exists. Avoids exceptions & potential problems.
                {
                        alsRawText = readFile(sFileName);//Read in file that contains the hands of cards.
                        
                        for(int i = 0; i < alsRawText.size(); i++) // Processes all players found in file
                                alpPlayers.add(processRawText(alsRawText.get(i)));
                }
                else
                        System.out.println("- File not Found: " + sFileName + " - ");
                
                return alpPlayers;
        }
}



Rules.java
//Rules.java
//      Written by James Stewart
//      See PlayGame.java for main function & documentation
//      Source Code: http://code.google.com/p/poker-java-classes/
package playingcards;

/**
 * Class representing the rules of a poker game.
 * @author James
 *
 */
public class Rules {
        //Enumeration Values
        
        
        //Class Variables
        private int iNumberOfCards; // Number of Cards in a hand
        private int iMaxPlayers; // Max number of players allowed at a "table".
        private int iMaxPot; // Pot limit, null or 0 for no-limit.
        private int iMaxBet; // Bet limit, 0 for no-limit, null for pot-limit.
        private int iMinBet; // Bet minimum.
        
        
        //Class Constructors
        Rules()
        {
                this(2,5);// Defaults
        }
        
        Rules(int iPlayers)
        {
                this(iPlayers, 5);
        }
        
        /**
         * Main Class Constructor
         * @param iPlayers              number of players allowed/required for a valid game.
         * @param iCards                number of cards allowed/required for a valid hand.
         */
        Rules(int iPlayers, int iCards)
        {
                this.iMaxPlayers = iPlayers;
                this.iNumberOfCards = iCards;
        }
        
        
        //Accessor Functions
        public int players(){ return iMaxPlayers; }
        public int cards(){ return iNumberOfCards; }
        public int maxPlayers(){ return iMaxPlayers; }
        public int maxPot(){ return iMaxPot; }
        public int maxBet(){ return iMaxBet; }
        public int minBet(){ return iMinBet; }
        
        
        //Member Functions
}


Was This Post Helpful? -1
  • +
  • -

#11 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 01:05 PM

That is not the list of errors, it's the Console output. The Problems tab should list the error messages.

From what I can see so far, your program is looking for a file that it needs for input and doesn't find it, then quits.

Although.. I'm not sure how it compiled in the first place to give you that output

This post has been edited by SarumanTheWhite: 05 November 2010 - 01:07 PM

Was This Post Helpful? 1
  • +
  • -

#12 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

Re: poker game in java

Posted 05 November 2010 - 01:08 PM

you mean this list of errors?


Description Resource Path Location Type
Assert cannot be resolved HandTest.java /poker/src/playingcards line 46 Java Problem
Assert cannot be resolved HandTest.java /poker/src/playingcards line 47 Java Problem
Assert cannot be resolved HandTest.java /poker/src/playingcards line 52 Java Problem
Assert cannot be resolved HandTest.java /poker/src/playingcards line 53 Java Problem
Assert cannot be resolved HandTest.java /poker/src/playingcards line 58 Java Problem
Assert cannot be resolved HandTest.java /poker/src/playingcards line 59 Java Problem
Assert cannot be resolved HandTest.java /poker/src/playingcards line 64 Java Problem
Before cannot be resolved to a type HandTest.java /poker/src/playingcards line 27 Java Problem
Test cannot be resolved to a type HandTest.java /poker/src/playingcards line 44 Java Problem
Test cannot be resolved to a type HandTest.java /poker/src/playingcards line 50 Java Problem
Test cannot be resolved to a type HandTest.java /poker/src/playingcards line 56 Java Problem
Test cannot be resolved to a type HandTest.java /poker/src/playingcards line 62 Java Problem
The import junit cannot be resolved HandTest.java /poker/src/playingcards line 3 Java Problem
The import org.junit cannot be resolved HandTest.java /poker/src/playingcards line 5 Java Problem
The import org.junit cannot be resolved HandTest.java /poker/src/playingcards line 6 Java Problem
Was This Post Helpful? 0
  • +
  • -

#13 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 01:21 PM

Ah, yes those error messages. Those functions are from the JUnit API which it seems you don't have. If I were you I'd comment those functions out for the time being until you get into Unit Testing. Also comment out the import for junit.

Although doing so will probably still give you the File Not Found error until you create Hands.txt which apparently holds the list of cards you have or something
Was This Post Helpful? 0
  • +
  • -

#14 aCceSs  Icon User is offline

  • New D.I.C Head

Reputation: -19
  • View blog
  • Posts: 16
  • Joined: 04-November 10

Re: poker game in java

Posted 05 November 2010 - 01:32 PM

i can't understand what u say :/ can someone help me with more details? :P
Was This Post Helpful? 0
  • +
  • -

#15 SarumanTheWhite  Icon User is offline

  • D.I.C Regular

Reputation: 73
  • View blog
  • Posts: 352
  • Joined: 04-November 08

Re: poker game in java

Posted 05 November 2010 - 01:40 PM

Sorry, let me clarify.

Those lines of code that are all red lined. They're calling a function Assert() which is only defined in the org.junit library, which as far as I know is a 3rd party library not included in the main Java API. In other words you don't have this library.

I would either:

1) Remove those lines of code and the references to org.junit

OR

2) Remove the HandTest.java file altogether seeing as I don't think they're being used anywhere in the main code.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2