Search code examples
javadata-structuresstackplaying-cards

To implement pile of cards and manage players


includes a pile of cards in a player’s hand and two actions: TAKE and DISCARD. TAKE puts a card on the top of a player’s pile of cards when that player receives a card from a dealer. DISCARD removes a card from the top of a player’s pile of cards when a player plays it against another player in the game. Each player receives 16 cards from the dealer at the beginning of a game........

I tried my code like this which gives me nothing

public class play {

    int noOfCards = 16;

    static void TAKE(Stack st, int a) {
        st.push(new Integer(a));
    }

    static void DISCARD(Stack st) {
        Integer a = (Integer) st.pop();
    }

    public static void main(String args[]) {
        for(int i=0; i<=16; i++) {     
            Stack st = new Stack();
            st.take();
            st.discard();
        }
    }
}

I am new to this concepts ....give me a path to solve this question


Solution

  • I'm sorry but I didn't fully understand the whole process you're trying to do. But I still gave it a shot.

    public class Play 
    {
    
        private static int noOfCards = 16;
        private static Stack<Integer> player1 = new Stack<Integer>();
        private static Stack<Integer> player2 = new Stack<Integer>();
    
        static void takeCard(Stack<Integer> st,int cardValue){
            st.push(cardValue);
        }
    
        static int discardCard(Stack<Integer> st){
            return st.pop();
        }
    
        static int getRandomValue(int min, int max){
            Random r = new Random();
            return r.nextInt((max - min) + 1) + min;
        }
    
        //Filled card pile with random values from 1-13
        public static void main(String[] args)
        {
            for(int i = 0 ; i < noOfCards; i++){
                takeCard(player1,getRandomValue(1,13));
                takeCard(player2,getRandomValue(1,13));
            }
    
            //player 1 takes a card!
            //Size of player1's pile before and after taking card
            System.out.println("Before:" + player1.size());
            takeCard(player1, getRandomValue(1, 13));
            System.out.println("After" + player1.size());
            //player 2 discards a card and outputs the card's value
            System.out.println("Player 2 discards: " + discardCard(player2));
        }
    }