// DeckOfCards.java  D&D 10.21
// Card shuffling and dealing program
// APPLET CODE="DeckOfCards" HEIGHT=200 WIDTH=400
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class DeckOfCards extends JApplet {
	private Card deck[ ];
	private int currentCard;

	// GUI components
	private Container c;
	private JButton dealButton, shuffleButton;
	private JTextField displayCard, cardNumber;

	public void init( ) {
		String faces[ ] = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
		String suits[ ] = { "Hearts", "Diamonds", "Clubs", "Spades" };
		int values[ ] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
		deck = new Card[ 52 ];
		currentCard = -1;

		for ( int i = 0; i < deck.length; i++ ) {
			deck[ i ] = new Card( faces[ i % 13 ], suits[ i / 13 ], values[ i % 13 ] );
		}

		// GUI Set-up
		c = getContentPane( );
		c.setLayout( new FlowLayout( ) );

		dealButton = new JButton( "Deal Card" );
		dealButton.addActionListener( 
			new ActionListener( ) {
				public void actionPerformed( ActionEvent e ) {
					Card dealt = dealCard( );
			
					if ( dealt != null ) {
						// it's a legit card
						displayCard.setText ( dealt.toString( ) );  // convert card to String and show in TextField
						cardNumber.setText( "Card #:  " + currentCard );
					} else {
						displayCard.setText( "ALL CARDS HAVE BEEN DEALT" );
						cardNumber.setText( "Shuffle to continue" );
					}
				}
			}
		);
		c.add( dealButton );
					
		shuffleButton = new JButton( "Shuffle Cards" );
		shuffleButton.addActionListener(
			new ActionListener( ) {
				public void actionPerformed( ActionEvent e ) {
					displayCard.setText( "SHUFFLING ... " );
					cardNumber.setText( "" );  // blank out cardNumber
					shuffle( );
					displayCard.setText( "DECK IS SHUFFLED" );
				}
			}
		);
		c.add( shuffleButton );		
			
		displayCard = new JTextField( 30 );
		displayCard.setEditable( false );
		c.add( displayCard );

		cardNumber = new JTextField( 10 );
		c.add( cardNumber );
	}

	public void shuffle( ) {
		currentCard = -1;  // reinitialize to -1

		for ( int i = 0; i < deck.length; i++ ) {
			int j = ( int ) ( Math.random( ) * 52 );  // random numbers 0 - 51
			Card temp = deck[ i ];  // card from deck stored in temp
			deck[ i ] = deck[ j ];  // the card's place is taken by another card selected at random
			deck[ j ] = temp;  // the random card's place is taken by the original card
		}
	}

	public Card dealCard( ) {
		// returns a Card object
		if ( ++currentCard < deck.length )
			return deck[ currentCard ];  // return the next card in the deck array
		else
			return null;
	}
}