how to declare the winning card from the hands of the 2 players. Need help please

280 views Asked by At

Ok, sorry for my English and for the post if it's not posted correctly. I'll try to explain this. The game is based on a card game call War. they put down there cards and the highest card win's. If there's a tie, they keep playing until the highest cards win with all the card that as been played for the tie breaker.

After the players have there five cards in the window JApplet. The players chooses one of their 5 cards. When this is done, The highest value win, with Ace as a value of 1.

My problem is I can't find a formula to compare these cards once after the 2 players played by pressing the button below the card. After this button is deactivated. They have 4 cards left to choose from and so on. After the 5 cards are played, they take another 5 cards and the process is repeated until 4 hands are played.

And when the 4 hands are played, the winner is declared by the most cards won in there pile.

How to compare 2 cards after they been played by the 2 players from there 5 five cards?

here is the other class

{

public class Carte{

            // définition des attributs
    private int enseigne, valeur;
    private int monPointageCarte;//attribut pour donner une vraie valeur de la carte

    //définir des tableaux String pour nos cartes enseignes et valeurs
    String[] enseignes={"Coeur","Carreau","Pique","Trèfle"};
    String[] valeurs={"As","2","3","4","5","6","7","8","9","10","Valet","Dame","Roi"};

    //Constructeur
    Carte(int enseigne,int valeur)
    {
        this.enseigne=enseigne;
        this.valeur=valeur;
        monPointageCarte=valeur;
    }

    //Méthode
    public int getValeur() 
    {
         return valeur;
    }

    public int getEnseigne() 
    {
        return enseigne;
    }

    public int getPoinCarte()
    {
        return monPointageCarte;
    }

    //Cette fonction afficher nos cartes à l'écran
    public void print() 
    {
        System.out.println(valeurs[valeur] + " de " + enseignes[enseigne]);
    }

    //Cette fonction pour que nos valeurs soient transformer 
    //dans une forme convenable à l'écran(String en override) ex.: As de Pique
    //Si non on verra des chiffre hexadécimale
    public String toString()
    {
      return (valeurs[valeur]+" de "+enseignes[enseigne]);
    }

    public int compareTo(Object o) 
     { 
         Carte other=(Carte)o; 
         return monPointageCarte-other.getValeur(); 
      }
}

{

public class JeuDeCartes {

         ArrayList<Carte> pile;
        //Conctructeur pour créer 52 cartes

JeuDeCartes()
{
    pile = new ArrayList<Carte>();
    //Ce code pour aller chercher nos 52 cartes
    for (int x=0; x<=3; x++)
        for (int y=0; y<=12; y++)
            pile.add( new Carte(x,y) );

}

//Méthode
//ajoute une carte que l'on cré à pile
public void ajout(Carte carte)
{
    pile.add(carte);
}

//Méthode qui enlève la carte du haut de la pile
public Carte pioche()
{
    //Ceci pour arrêter le retrait de carte quand il n'a plus de carte dans la pile
    if(this.pile.size()<=0)
    {
        System.out.println("Le paquet de carte est vide");
        return null;
    }
    else
    {
        //Ici pour diminuer notre pile de 1
        //On peut mettre 51 entre les () de .remove(51)
        //Je trouve ceci plus pratique pour le futur
        int dernier=this.pile.size()-1;
        return this.pile.remove(dernier);
    }
}

//Méthode qui mélange l'ordre des cartes
public void melange()
{
     Collections.shuffle(pile);

    //Inspirer de random sur divers site pour arriver à faire un mélange des cartes dans la pile
    /*for(int i=pile.size()-1;i<0;i--)
    {
        Random melange=new Random();

        int index1,index2;
        Carte temp;
        index1=melange.nextInt(pile.size()-1);
        index2=melange.nextInt(pile.size()-1);;

        //échange des cartes
        temp=(Carte)pile.get(index2);
        pile.set(index2, pile.get(index1));
        pile.set(index1,temp);
        //int index= melange.nextInt( pile.size() );
        //Ici pas nécessaire de faire un print mais je voulais voir le résultat à l'écran
        //On peut écrire pile.remove(index))mais cela enlève une carte du pacquet
        System.out.println(pile.set(index1, temp));
    }*/
}

 public int getQuantitePile()
{
    return pile.size();
}
}




public class Pile {

    Pile()
    {
        pile = new Carte[52];
        front = 0; end = 0;
    }
    int getSize()
    {
        return end - front;
    }
    void clear()
    {
        front = 0; end = 0;
    }
    void addCard(Carte c)
    {
        pile[end] = c;
        end++;
    }
    void addCards(Pile p)
    {
        while (p.getSize() > 0)
            addCard(p.nextCard());
    }

    Carte pioche()
    {
        Carte c=pile[front];
        //end--;
        return c;
    }
    Carte nextCard()
    {
        if (front == end)
            return null; // should not happen
        Carte c = pile[front];
        front++;
        return c;
    }
    private Carte [] pile;
    private int front, end; // front  end
}

{

class Joueur{

Joueur(String n)
{
    name = n;
    playPile = new Pile();
    wonPile = new Pile();
}
Carte playCard()
{
    if (playPile.getSize() == 0)
        useWonPile();
    if (playPile.getSize() > 0)
        return playPile.nextCard();
    return null;
}
String getName()
{
    return name;
}
void collectCard(Carte c)
{
    wonPile.addCard(c);
}
void collectCards(Pile p)
{
    wonPile.addCards(p);
}

void useWonPile()
{
    playPile.clear(); // reset front and end to 0
    playPile.addCards(wonPile);
    wonPile.clear(); // reset front and end to 0
}
int numCards()
{
    return playPile.getSize() + wonPile.getSize();
}
private Pile playPile, wonPile;
private String name;
}



public class MainDeCartes {
private Vector hand;   // The cards in the hand.

   public MainDeCartes() {
           // Create a Hand object that is initially empty.
      hand = new Vector();
   }

   public void clear() {
         // Discard all the cards from the hand.
      hand.removeAllElements();
   }

   public void addCard(Carte c) {
         // Add the card c to the hand.  c should be non-null.  (If c is
         // null, nothing is added to the hand.)
      if (c != null)
         hand.addElement(c);
   }

   public void removeCard(Carte c) {
         // If the specified card is in the hand, it is removed.
      hand.removeElement(c);
   }

   public void removeCard(int position) {
         // If the specified position is a valid position in the hand,
         // then the card in that position is removed.
      if (position >= 0 && position < hand.size())
         hand.removeElementAt(position);
   }

   public int getCardCount() {
         // Return the number of cards in the hand.
      return hand.size();
   }

   public Carte getCard(int position) {
          // Get the card from the hand in given position, where positions
          // are numbered starting from 0.  If the specified position is
          // not the position number of a card in the hand, then null
          // is returned.
      if (position >= 0 && position < hand.size())
         return (Carte)hand.elementAt(position);
      else
         return null;
   }
/*private int mySize;
private int nbreCarteRestant;
private ArrayList carteDsMain=new ArrayList();

public MainDeCartes()
{
    carteDsMain.getClass();
}

public int getSize()
{
    return mySize;
}

public void ajoutCarte(Carte carte)
{
    if(carteDsMain.size()<mySize)
        carteDsMain.add(carte);
}

public Carte getCarte(int i)
{
    return (Carte)carteDsMain.get(i);
}

public void printLaMain()
{
    int i;
    Carte carte;
    for(i=0;i<carteDsMain.size();i++)
    {
        carte=(Carte)carteDsMain.get(i);
        System.out.println(carte.getEnseigne());
    }
}

private void changeLaCarte(int pos,Carte carte)
{
    carteDsMain.set(pos,carte);
}

public void trier()
{
    int indexBas;
    Carte carte;
    int i;
    for(i=0;i<getSize();i++)
    {
        indexBas=trouverIndexBas(i);
        //échange de carte
        carte=getCarte(i);
        changeLaCarte(i,getCarte(indexBas));
        changeLaCarte(indexBas,carte);
    }

}

private int trouverIndexBas(int debutIndex)
{
    int i;
    int bas=debutIndex;
    Carte carteBasse=getCarte(bas);
    for(i=debutIndex+1;i<getSize();i++)
        if(getCarte(i).compareTo(carteBasse)<0)
        {
            bas=i;
            carteBasse=getCarte(i);
        }
    return bas;
}*/
}

The problem if I don't try to implement a code IF before the first loop of Do I get a null error cause I don't have a value yet for mainJoueur1.getCard(compteurI1). And If I Do put a IF with acceptable value, when the 3rd card is chosen it continue to compare. I can't find a solution for executing the first DO loop only when 2 cards have been played from the hand(MainDeCartes) after the 4th card and so on.

{

public void actionPerformed(ActionEvent evt) {

    Object source=evt.getSource();

    /*if(evt.getSource()==nouvellePartie)
        rejoue();*/


    /*jbChoixJun1.setEnabled(false);
    jbChoixJun2.setEnabled(false);
    jbChoixJun3.setEnabled(false);
    jbChoixJun4.setEnabled(false);
    jbChoixJun5.setEnabled(false);*/
    if(paquet.getQuantitePile()!=0)
    {
    while(paquet.getQuantitePile()>=2)
    {
        p1.collectCard(paquet.pioche());
        p2.collectCard(paquet.pioche());

    }
    }
    System.out.println(p1.numCards());

    //Action bouton piger joueur1
            //Met 5 cartes dans la MainDeCartes mainJoueur1 et affiche ces 5 cartes
            if (source==btPiocheJoueur1) 
            {
                //Initialise
                //carte1=paquetJoueur1.pioche();
                //Carte c1=p1.playCard();

                for(int i=0;i<5;i++)
                {
                    mainJoueur1.addCard(p1.playCard());

                    carteImagesJoueur1[i]=getImage(getDocumentBase(),mainJoueur1.getCard(i).valeurs[mainJoueur1.getCard(i).getValeur()] + mainJoueur1.getCard(i).enseignes[mainJoueur1.getCard(i).getEnseigne()]+".gif");
                    compteur=1;
                    jbChoixJun[i].setEnabled(true);
                }                   

                btPiocheJoueur1.setEnabled(false);

            } 

            //Action bouton joueur2
            //Mets 5 cartes dans la MainDeCartes mainJoueur2 et affiche ces 5 cartes

            if (source==btPiocheJoueur2) 
            {
                //Carte c2=p2.playCard();

                //Initialise
                //carte2=paquetJoueur2.pioche();



                //Mets les cartes piocher par le joueur dans la classe MainDeCartes
                for(int i=0;i<5;i++)
                {
                    mainJoueur2.addCard(p2.playCard());

                    carteImagesJoueur2[i]=getImage(getDocumentBase(),mainJoueur2.getCard(i).valeurs[mainJoueur2.getCard(i).getValeur()] + mainJoueur2.getCard(i).enseignes[mainJoueur2.getCard(i).getEnseigne()]+".gif");
                    compteur=1;
                    jbChoixJdeux[i].setEnabled(true);
                }
                //repaint();
                //Désactive le bouton 
                btPiocheJoueur2.setEnabled(false);

            }
            System.out.println(compteur1+"compteur1");
            System.out.println(compteurMain+"compteurMain");
            System.out.println(p1.numCards()+" nbr de carte restante de la main du joueur1");
            do
            {
                boolean[] vraiFaux=new boolean[2];
                vraiFaux[0]=true;
                vraiFaux[1]=false;


            for(int i=0;i<5;i++)
            {
                if(source==jbChoixJun[i])
                {
                    mainJoueur1.getCard(i);
                    jbChoixJun[i].setEnabled(false);
                    compteur1=1;
                    compteurI1=i;
                    System.out.println("compteurI1="+compteurI1);
                }
            }
            System.out.println("compteurI1="+compteurI1);

            for(int i=0;i<5;i++)
            {
                if(source==jbChoixJdeux[i])
                {
                    mainJoueur2.getCard(i);
                    jbChoixJdeux[i].setEnabled(false);
                    compteur2=1;
                    compteurI2=i;
                    System.out.println("compteurI1="+compteurI1);
                }
            }



            System.out.println("compteurMain = "+compteurMain);
                Carte c1=mainJoueur1.getCard(compteurI1);
                Carte c2=mainJoueur2.getCard(compteurI2);
                p1.useWonPile();
                p2.useWonPile();
                Pile down=new Pile();
                System.out.println("carte du joueur 1 "+c1);
                System.out.println("carte du joueur 2 "+c2);
                if(compteurI1!=-1&compteurI2!=-1)//This is  where I'm trying to prevent 
//the null error and to implement 
//something that execute the rest only
// if the 2 cards are played from the hand, after 4 cards and so on
//Until all 5 cards have been played, then restart
                {
                do
                {
                //Compare la valeur des 2 cartes choisies
                if(mainJoueur1.getCard(compteurI1).getValeur()<mainJoueur2.getCard(compteurI2).getValeur())
                //if(c1.compareTo(c2)<0)
                {
                    p2.collectCard(mainJoueur1.getCard(compteurI1));
                    p2.collectCard(mainJoueur2.getCard(compteurI2));
                    mainJoueur1.removeCard(compteurI1);
                    mainJoueur2.removeCard(compteurI2);

                }
                else if(mainJoueur1.getCard(compteurI1).getValeur()>mainJoueur2.getCard(compteurI2).getValeur())
                //if(c1.compareTo(c2)>0)
                {
                    p1.collectCard(mainJoueur1.getCard(compteurI1));
                    p1.collectCard(mainJoueur2.getCard(compteurI2));
                    mainJoueur1.removeCard(compteurI1);
                    mainJoueur2.removeCard(compteurI2);

                }
                else
                {
                    down.clear();
                    down.addCard(mainJoueur1.getCard(compteurI1));
                    down.addCard(mainJoueur2.getCard(compteurI2));
                    mainJoueur1.removeCard(compteurI1);
                    mainJoueur2.removeCard(compteurI2);
                    boolean done=false;
                    if(c1.compareTo(c2)>0)
                        p1.collectCards(down);
                    else
                        p2.collectCards(down);
                }
                System.out.println("compteur1 ="+compteur1);
                System.out.println(p1.numCards() + " to "+ p2.numCards());
                System.out.println(mainJoueur1.getCardCount());
                System.out.println(mainJoueur2.getCardCount());


            }while(compteurMain==compteurMain+2);
            //if(i==compteur1)
            }
            }while(mainJoueur1.getCardCount()==0 & mainJoueur2.getCardCount()==0);
            repaint();
        } 


boolean enoughCards(int n)
    {
        if (p1.numCards() < n || p2.numCards() < n)
            return false;
        return true;
    }

Joueur getWinner()
{
    if (p1.numCards() > p2.numCards())
        return p1;
    else if (p2.numCards() > p1.numCards())
        return p2;
    else
        return null;
 }



 public void paint(Graphics g) 
    {
     int i,x,y;
     x=30; 
     y=50; 
     if(compteur==0)
     {
         g.drawImage(carteImagesBack[0],30,50,60,90,this);
         g.drawImage(carteImagesBack[0],30,300,60,90,this);

     }

     if(compteur1==1)
     {
        x=100*compteurI1;
        g.setColor(new Color(130,50,40));//Astuce pour afficher
        g.fillRect(30+x,y,60,90);//une image
        /*if(compteur2==1)
        {
            g.setColor(new Color(130,50,40));//Astuce pour afficher
            g.fillRect(30+x,300,60,90);//une image pour effacer la carte utilisée
            compteurMain++;
        }*/
        compteurMain++; 
        g.drawImage(carteImagesJoueur1[compteurI1],600,y,60,90,this);

     }       
     else if(compteur2==1)
     {
        x=100*compteurI2;
        g.setColor(new Color(130,50,40));//Astuce pour afficher
        g.fillRect(30+x,300,60,90);//une image
        /*if(compteur1==1)
        {
            g.setColor(new Color(130,50,40));//Astuce pour afficher
            g.fillRect(30+x,50,60,90);//une image
            compteurDeMain++;
        }*/
        g.drawImage(carteImagesJoueur2[compteurI2],600,300,60,90,this);

     }
     else
     {

         // g.drawImage(carteImagesJoueur1[1],80,50,60,90,this);
         for(i=0;i<mainJoueur1.getCardCount();i++)
         {
             //peindre les cartes pour le joueur1
             g.drawImage(carteImagesJoueur1[i],x,y,60,90,this);
             x=x+100; 
         } 
         //peindre de la main du joueur2
         x=30; 
         y=300; 
         for (i=0;i<carteImagesJoueur2.length;i++) 
         { 
             g.drawImage(carteImagesJoueur2[i],x,y,60,90,this); 
             x=x+100; 
         }
     } 
        /*
        g.setColor(Color.white);//Astuce pour afficher
        g.fillRect(150,100,115,165);//une image
        //Place l'image completement à gauche coin en Haut
        g.drawImage(carteImagesJoueur1[0],150,100,115,165,this); //115 est la largeur et 165 est la hauteur de l'image

        g.setColor(Color.white);
        g.fillRect(300, 100, 115, 165);
        g.drawImage(carteImagesJoueur2[0], 300, 100, 115, 165, this);
   */
    }

    public void rejoue() 
    { 
        btPiocheJoueur1.setEnabled(true); 
        btPiocheJoueur1.setEnabled(true); 
        nouvellePartie.setEnabled(false); 
       // msg.setText(""); 
        start();       
   } 
} 
1

There are 1 answers

2
trashgod On

All the other class are working fine.

You may have to consider a significantly different approach.

  1. Model individual instances of Card using an enum, as shown here. Java enum values are already Comparable to each other based on order.

  2. Rather than an array or List<Card>, model your deck and hands as a Deque<Card>. Because a Deque<Card> is a Collection you can use shuffle().

  3. Your play loop will catch a NoSuchElementException, thrown when you attempt to access an empty hand or deck, as detailed in the Deque API.

In this complete example, note how procedure Play draws a card from each hand, looping until one player wins. The terminating exception is caught by the caller, procedure Play_Game