/* Blackjack.h - Class for the card game Blackjack. */


#ifndef BLACKJACK_H
#define BLACKJACK_H

#include <iostream.h>
#include <String.h>
#include <stdlib.h>
			
#include "Deck.h"
#include "Player.h"


class Blackjack  {
public:

    Blackjack(int n);                               // Construct a game.
    Deck deck;                                      // deck for all players to share
    
    void load_players();                            // Load the players.
    void play();                                    // Play the game.
    
private:

    Player* player;                                 // Pointer to the player.
    Player* dealer;                                 // Pointer to the dealer.

    int     the_bet;
    int     get_total(Player* ref);                 // total # of points.
    int     player_tot, dealer_tot;

    void    instant_winner() , find_winner();
    void    common_display() , display_all();                    
    
    char    resp, yes_no();
};


/* Function definitions for Blackjack.h */


Blackjack::Blackjack(int n)
{
    player = new Player(deck);                              
    player->set_score(n);
    dealer  = new Player(deck);	                    
} 


void Blackjack::load_players() 
{
    char name[80];
    cout << "What is your name?   ";
    cin.get(name,80);

    player->set_name( name );
    dealer->set_name( "Dealer" );
}


void Blackjack::play()  
{
    try {
        
       while (1)
          {
          system("clear");                                     // Clear the screen
          cout << endl << player->Name() << ", you have $";
          cout << player->get_score() << "." << endl << endl;
          cout << "Enter an integer bet:  (example:  50)    ";  cout.flush();
          
          char num[80];                                        // Read in a char to be safe.
          while ( 1 )    
            {
            cin >> num;  the_bet = atoi(num);                  // Convert char to int.
            if ( (the_bet <= player->get_score() ) && (the_bet > 0) ) break;
            cout << "That was not a valid bet.  Try again." << endl;
            }

          player->hand.reset();    
          dealer->hand.reset();
          
      // Deal 2 cards each.
     
          for (int i=0; i < 2; i++)  player->hand.add( deck.deal() );   
          for (int j=0; j < 2; j++)  dealer->hand.add( deck.deal() );
   
          player_tot = get_total(player);
          dealer_tot = get_total(dealer);

          if ( player_tot == 21 || dealer_tot == 21 )
             instant_winner();
          else  
             find_winner();
            
          cout << "Another hand?  (y or n) " << endl;
          resp = yes_no();

          if ( (resp=='n') || (resp=='N') ) exit(1);
          }
   }

   catch(Player::NoMoney)  
   {}
}


/* These functions are used in Blackjack::play() . */

void Blackjack::instant_winner()
{
      display_all();                                           
      
      if (dealer_tot < 21)       
      {
         cout << "Player has Blackjack!  You win!" << endl;
         player->add_score(the_bet);
      }

      else if (player_tot < 21)  
      {
         cout << "Dealer has Blackjack! You lose " << the_bet << " dollars!" << endl;
         player->sub_score(the_bet);
      }
      
      else 
         cout << "Both the player and dealer have 21. " << endl;
}


void Blackjack::find_winner()
{    
    common_display();

    try {
        unsigned keepLooping = 1;
        while (keepLooping)
           {       
           cout << endl << "Do you want to Hit (H) or Stay (S)?   " << endl;
           cin >> resp;
           
           switch (resp)    {

               case 's' :
               case 'S' :
                         system("clear");
                         keepLooping = 0;
                         break;
               case 'h' :
               case 'H' :     
                         system("clear");
                         player->hand.add( deck.deal() );      // Deal another card.
                         player_tot = get_total(player);
                         if (player_tot > 21)  throw player;
                         common_display();
                         break;
               default:                                        // Don't clear screen unless input is valid.
                         cout << "That was not a valid response." << endl;
           }
        }
  

   // Dealer must hit until hand total reaches 17.
     
        while (dealer_tot < 17) 
           {
           dealer->hand.add( deck.deal() );
           cout << "Dealer draws a card ...    " << endl;
           dealer_tot = get_total(dealer);
           if (dealer_tot > 21)   throw dealer;
           }
        
        display_all();                         // Display all cards; announce winner
        
        if (dealer_tot >= player_tot)
            {
            cout << "Sorry!  Dealer wins. " << endl;
            player->sub_score(the_bet);
            }
        else
            {
            cout << "Congratulations!  You win " << the_bet << " dollars." << endl;
            player->add_score(the_bet);
            }
     }

     catch (Player* loser)
     { 
        display_all();
        cout << endl << loser->Name() << " goes over 21!  ";
        cout << loser->Name() << " loses the hand."  << endl << endl;
        loser->sub_score(the_bet); 
        if (loser == dealer)  player->add_score(the_bet);
     }
}    
   
      
/* Find point value for a hand. Card games have different ways of assigning point 
   values to cards.  Usually, the point values aren't trivial (in Blackjack the 
   Ace is 1 or 11, depending on the total.)  Consequently this MUST be 
   calculated HERE to maintain modularity of the other classes.  It must also be 
   recomputed from scratch each time, because of the weird Ace's.     
   Jack, Queen, and King are given point values of 10.
   All other cards have point values that correspond to their face value.
*/

int Blackjack::get_total(Player* ref)
{   
    int points    = 0;
    int total     = 0;
    int ace_count = 0;
        
    for (int i = 1; i <= ref->hand.Num_Elts(); i++)  
       {
       points = ref->hand[i]->get_rank();
       if ( points == 1 ) 
           ace_count++;
       else if ( points > 10 ) 
           points = 10;

       total = total + points;
       }

    for (int j = 0; j < ace_count; j++)
       {
       while (total < 12)
          total = total + 10;
       }
          
    return total;
}


/* Display all of the Player's cards and only ONE of the dealer's cards.*/
   
void Blackjack::common_display()
{
    cout << endl << "        " << dealer->Name() << "'s hand:  " << endl;
    dealer->hand.display(1);
   
    cout << endl << "        " << player->Name() << "'s hand:  " <<endl;
    player->hand.display();
   
    cout << player->Name() << "'s total:  " << player_tot << endl << endl;
}


/* Display all of the player's cards and all of the dealer's cards.  */
   
void Blackjack::display_all()
{
    cout << endl << "        " << dealer->Name() << "'s hand:  " << endl;
    dealer->hand.display();

    cout << endl << "        " << player->Name() << "'s hand:  " << endl;
    player->hand.display();

    cout << dealer->Name() << "'s total:  " << dealer_tot << endl << endl;
    cout << player->Name() << "'s total:  " << player_tot << endl << endl;
}


inline char Blackjack::yes_no()
{
    char ans;
    
    while ( 1 )        {
      cin  >> ans;
      if ( (ans=='y') || (ans=='Y') || (ans=='n') || (ans=='N') )
         break;
      cout << "That was not a valid response.  Try again." << endl;            
    }
    
    return ans;
}

#endif
