SlideShare a Scribd company logo
1 of 55
blackjackrevised2/BlackJack.h
//BLACKJACK
#ifndef _BLACKJACK
#define _BLACKJACK
#include "BlackJackHand.h"
#include "BlackJackDeck.h"
#include "ValidInput.h"
class BlackJack
{
public:
BlackJack(unsigned int deckNumber = 1);
void Run();
//GetArrayOfStats
private:
enum class GameState
{
Wager,
FirstRound, //check for blackjack and allow
double down; splitting COULD also go here; might be better to
have isFirstRound bool
PlayerInput,
DealerReveal, //let player surrender
DealerInput,
EndRound,
Exit
};
const int DECK_NUMBER; // not actually used
should delete
string message;
string error;
int input;
string name; //PLAYER NAME needed for persistent
stats (not implemented) should be constructor parameter
default:"Player"
BlackJackDeck deck;
BlackJackHand player;
BlackJackHand dealer;
int playerChips;
int playerWager;
//stuff for persistant stats (not implemented) maybe
make it an array which can be passed to the main.cpp menu
which will handle the user profile txt
unsigned long int handsPlayed;
unsigned long int handsWon;
unsigned long int handsLost;
unsigned long int chipsWon;
unsigned long int chipsLost;
void Output();
void Input();
void Processing();
void DealCards();
void HandsOnTable();
GameState state;
};
BlackJack::BlackJack(unsigned int deckNumber) :
DECK_NUMBER(deckNumber), deck(deckNumber)
{
playerChips = 500; //use static constant
input = 0;
state = GameState::Wager;
deck.Shuffle();
}
void BlackJack::Run()
{
while (state != GameState::Exit)
{
Output();
Input();
Processing();
}
}
void BlackJack::Output()
{
system("CLS"); //clear the console
if (state == GameState::Wager)
{
//player betting screen
cout << "Place your bet." << endl << endl
<< "Player Chips: " << playerChips << endl <<
endl
<< error << endl
<< "How much do you want to wager? ";
}
else if (state == GameState::PlayerInput)
{
//player input menu
HandsOnTable();
cout << "1. Hit" << endl
<< "2. Stand" << endl
//<< "3. Double Down //not done" << endl
//<< "4. Surrender //not done" << endl << endl
<< error << message << endl
<< "Option: ";
}
else if (state == GameState::DealerInput)
{
HandsOnTable();
cout << message << endl
<< "Continue...";
}
else if (state == GameState::EndRound)
{
HandsOnTable();
cout << message << endl
<< "Continue...";
}
}
void BlackJack::Input()
{
string sInput;
getline(cin, sInput);
stringstream linestream(sInput);
linestream >> input;
}
void BlackJack::Processing()
{
//CHECK IF DECK IS EMPTY HERE
error = "";
message = "";
//new round state?
if (state == GameState::Wager)
{
//player betting screen
if (input < 1 )
{
error += "You must bet at least one chip. ";
}
else if (input > playerChips)
{
error += "You cannot bet more chips than you
have. ";
}
else
{
playerWager = input;
playerChips -= input;
stringstream linestream;
linestream << "Player wagers " << playerWager
<< " chips. ";
message = linestream.str();
state = GameState::PlayerInput;
DealCards();
}
}
else if (state == GameState::PlayerInput)
{
//player input menu
//may have to split GameState::FirstRound where we
let player double down and check for blackjack
switch (input)
{
case 1:
{
BlackJackCard card =
deck.DrawCard();
player.AddCard(card);
message += "Player drew ";
message += card.ToString();
message += ". ";
if (player.GetBust())
{
message += "Player busts.
";
dealer.FlipFirstCard();
state =
GameState::EndRound;
}
else if (player.GetHandValue()
== 21)
{
dealer.FlipFirstCard();
state =
GameState::DealerInput;
}
break;
}
case 2:
{
message += "Player stands.
Dealer hand is revealed. ";
dealer.FlipFirstCard();
state = GameState::DealerInput;
break;
}
/* case 3: //betting not
implemented
break;
case 4:
break; */
default:
error += "Invalid Option ";
}
}
else if (state == GameState::DealerInput)
{
if (dealer.GetHandValue() < 17 &&
dealer.GetHandValue() <= player.GetHandValue())
{
BlackJackCard card = deck.DrawCard();
message += "Dealer drew ";
message += card.ToString();
message += ". ";
dealer.AddCard(card);
if (dealer.GetBust())
{
message += " Dealer busts. ";
state = GameState::EndRound;
}
else if (dealer.GetHandValue() >= 17)
{
message += " Dealer stands. ";
state = GameState::EndRound;
}
}
else
{
message += "Dealer stands. ";
state = GameState::EndRound;
}
}
else if (state == GameState::EndRound)
{
if (playerWager == 0)
{
if (playerChips == 0)
{
}
else
{
state = GameState::Wager;
player.EmptyHand();
dealer.EmptyHand();
}
}
else
{
if (player.GetBust() || (dealer.GetHandValue() >
player.GetHandValue() && !dealer.GetBust()))
{
stringstream linestream;
linestream << "You lost " << playerWager
<< " chips. ";
message = linestream.str();
}
else if (player.GetHandValue() ==
dealer.GetHandValue())
{
playerChips += playerWager;
stringstream linestream;
linestream << "Push. " << playerWager <<
" chips were returned to you. ";
message = linestream.str();
}
else
{
stringstream linestream;
if (player.isBlackJack)
{
playerChips += playerWager * 3 / 2;
linestream << "You won " <<
(playerWager * 3 / 2) << " chips. ";
}
else
{
playerChips += playerWager * 2;
linestream << "You won " <<
playerWager << " chips. ";
}
message = linestream.str();
}
playerWager = 0;
}
}
}
void BlackJack::DealCards()
{
BlackJackCard card;
card = deck.DrawCard();
player.AddCard(card);
card = deck.DrawCard();
dealer.AddCard(card);
card = deck.DrawCard();
player.AddCard(card);
card = deck.DrawCard();
dealer.AddCard(card);
if (player.GetHandValue() == 21)
{
message += "Player Black Jack! ";
player.isBlackJack = true;
state = GameState::EndRound;
}
if (dealer.GetHandValue() == 21)
{
message += "Dealer Black Jack! ";
dealer.isBlackJack = true;
state = GameState::EndRound;
}
else if ((dealer.GetHandValue() == 21 &&
player.GetHandValue() == 21) == false)
{
dealer.FlipFirstCard();
}
}
void BlackJack::HandsOnTable()
{
cout << "Cards left in deck: " << deck.CardsRemaining()
<< endl;
cout << "Dealer Hand: " << dealer.ToString() << " (" <<
dealer.GetHandValue();
if (dealer.GetFaceDown()) cout << "?"; //estimate dealer's
hand
cout << ")nn"
<< "Player Hand: " << player.ToString() << " ("
<< player.GetHandValue() << ")" << endl << endl
<< "Player Chips: " << playerChips << endl
<< "Player Wager: " << playerWager << endl <<
endl;
}
#endif
blackjackrevised2/BlackJackCard.h
/*
HEADER
*/
#ifndef _BLACKJACK_CARD
#define _BLACKJACK_CARD
#include <iostream>
#include <stdexcept>
#include <sstream>
using namespace std;
enum Rank // converts implicitly to int
{
Ace = 1, // explicity set Ace to 1
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King
};
enum Suit // converts implicitly to int
{
Spades = 1,
Hearts,
Diamonds,
Clubs
};
class BlackJackCard
{
public:
//constants
static const Rank MIN_RANK;
static const Rank MAX_RANK;
static const Suit MIN_SUIT;
static const Suit MAX_SUIT;
static const char RANKS[]; // an array that holds the
names of the ranks
static const char SUITS[];
//constructors
BlackJackCard() : myRank(Rank::Ace),
mySuit(Suit::Spades), isFaceUp(true) {}
BlackJackCard(Rank rank, Suit suit, bool faceUp =
true);
//accessors
Rank GetRank(){ return myRank; }
Suit GetSuit(){ return mySuit; }
bool GetFaceUp(){ return isFaceUp; }
string ToString();
//mutators
void SetRank(Rank rank);
void SetSuit(Suit suit);
void FlipCard(){ isFaceUp = !isFaceUp; }
private:
Rank myRank;
Suit mySuit;
bool isFaceUp;
};
//static member initialization
const Rank BlackJackCard::MIN_RANK = Rank::Ace;
const Rank BlackJackCard::MAX_RANK = Rank::King;
const Suit BlackJackCard::MIN_SUIT = Suit::Spades;
const Suit BlackJackCard::MAX_SUIT = Suit::Clubs;
const char BlackJackCard::RANKS[] = { '0', 'A', '2', '3', '4', '5',
'6', '7', '8', '9', 'T', 'J', 'Q', 'K'};
const char BlackJackCard::SUITS[] = { '0', 'S', 'H', 'D', 'C' };
BlackJackCard::BlackJackCard(Rank rank, Suit suit, bool
faceUp)
{
SetRank(rank);
mySuit = suit;
isFaceUp = faceUp;
}
void BlackJackCard::SetRank(Rank rank)
{
if(rank < MIN_RANK || rank > MAX_RANK)
{ //throw out of range exception with description
stringstream strOut;
strOut << "Rank argument: " << rank
<< " is out of range. Rank must be between "
<< MIN_RANK << " and " << MAX_RANK
<< ". ";
throw out_of_range(strOut.str());
}
else
{
myRank = rank;
}
}
void BlackJackCard::SetSuit(Suit suit)
{
if(suit < MIN_SUIT || suit > MAX_SUIT)
{ //throw out of range exception with description
stringstream strOut;
strOut << "Suit argument: " << suit
<< " is out of range. Suit must be between "
<< MIN_SUIT << " and " << MAX_SUIT <<
". ";
throw out_of_range(strOut.str());
}
else
{
mySuit = suit;
}
}
string BlackJackCard::ToString()
{
stringstream strOut;
if (isFaceUp)
{
strOut << SUITS[GetSuit()] << RANKS[GetRank()];
}
else
{
strOut << '?' << '?';
}
return strOut.str();
}
#endif
blackjackrevised2/BlackJackDeck.h
/*
HEADER
*/
#ifndef _BLACKJACK_DECK
#define _BLACKJACK_DECK
#include "BlackJackCard.h"
#include <ctime>
#include <vector>
using namespace std;
class BlackJackDeck
{
public:
static const int STANDARD_SIZE;
//constructor
BlackJackDeck(unsigned int num = 1); // use usinged int?
//dont need to delete vector?
//destructor
//copy constructor
//assignment operator
BlackJackCard DrawCard();
//initialize
void Initialize();
//use vector? deque? stack?
void Shuffle();
const int CardsRemaining() { return cardNumber; }
void OutputDeck(); //debug only, should not exist here
private:
int deckNumber;
int cardNumber;
vector<BlackJackCard> deck;
};
const int BlackJackDeck::STANDARD_SIZE =
BlackJackCard::MAX_SUIT * BlackJackCard::MAX_RANK;
//52 card deck
BlackJackDeck::BlackJackDeck(unsigned int num)
{
deckNumber = num;
Initialize();
}
void BlackJackDeck::Initialize()
{
deck.clear();
cardNumber = deckNumber * STANDARD_SIZE;
deck.reserve(cardNumber);
//generate deck
BlackJackCard card;
for (int i = 0; i < deckNumber; i++)
{
for (int suit = BlackJackCard::MIN_SUIT; suit <=
BlackJackCard::MAX_SUIT; suit++)
{
for (int rank = BlackJackCard::MIN_RANK; rank <=
BlackJackCard::MAX_RANK; rank++)
{
card.SetSuit(static_cast<Suit>(suit));
card.SetRank(static_cast<Rank>(rank));
deck.push_back(card);
}
}
}
}
void BlackJackDeck::Shuffle()
{
//just use random_shuffle lmao <algorithm>
vector<BlackJackCard> tempDeck = deck;
deck.clear();
int randomCard = 0;
srand(time(NULL));
for (int i = 0; i < cardNumber; i++)
{
randomCard = rand() % (cardNumber - i);
deck.push_back(tempDeck.at(randomCard));
tempDeck.erase(tempDeck.begin() + randomCard);
}
}
BlackJackCard BlackJackDeck::DrawCard()
{
BlackJackCard card = deck.back();
deck.pop_back();
cardNumber--;
return card;
}
//remove later
void BlackJackDeck::OutputDeck()
{
cout << "nDeck Contentsn"
<< "===================" << endl;
for (int i = 0; i < cardNumber; i++)
{
cout << deck.at(i).ToString() << endl;
}
cout << "===================" << endl;
}
#endif
blackjackrevised2/BlackJackHand.h
/*
HEADER
BlackJackHand
*/
#ifndef _BLACKJACK_HAND
#define _BLACKJACK_HAND
#include "BlackJackCard.h"
#include <list>
class BlackJackHand
{
public:
//constructor
BlackJackHand() { handValue = 0; isBust = false;
isBlackJack = false; hasFaceDown = false;}
void EmptyHand();
void AddCard(BlackJackCard card);
void CalculateValue(); // needed to recalculate if has
ace and hand is bust
string ToString();
bool GetBust(){ return isBust; }
bool GetFaceDown(){ return hasFaceDown; }
int GetHandValue(){ return handValue; }
bool isBlackJack;
void FlipFirstCard();
private:
list<BlackJackCard> hand;
list<BlackJackCard>::iterator handIter;
bool isBust;
bool hasFaceDown;
int handValue;
};
//constuctor?
void BlackJackHand::AddCard(BlackJackCard card)
{
hand.push_back(card);
CalculateValue();
}
void BlackJackHand::CalculateValue()
{
bool calculate = true;
int aceLow = 0;
//loop
while (calculate)
{
hasFaceDown = false;
handValue = 0;
int aceCount = 0;
for(handIter = hand.begin(); handIter != hand.end();
++handIter)
{
if (handIter->GetFaceUp())
{
//if card is ace ++acecount add 11
if (handIter->GetRank() == Ace)
{
if (aceLow > aceCount)
{
handValue += 1;
}
else
{
handValue += 11;
}
aceCount++;
}
//if card is jack, queen, king ++10
else if (handIter->GetRank() == Jack ||
handIter->GetRank() == Queen || handIter->GetRank() == King)
{
handValue += 10;
}
//else use enum rank int
else
{
handValue += handIter->GetRank();
}
}
else
{
hasFaceDown = true;
}
}
//if handValue > 21 and contians aces -> recalculate with
one ace as value of 1
if (handValue > 21 && aceLow < aceCount)
{
aceLow++;
}
//elseif value > 21 isBust = true
else
{
if (handValue > 21)
{
isBust = true;
}
calculate = false;
}
}
}
string BlackJackHand::ToString()
{
stringstream strOut;
for(handIter = hand.begin(); handIter != hand.end();
++handIter)
{
strOut << handIter->ToString() << ' ';
}
return strOut.str();
}
void BlackJackHand::FlipFirstCard()
{
handIter = hand.begin();
handIter->FlipCard();
CalculateValue();
}
void BlackJackHand::EmptyHand()
{
hand.clear();
isBust = false;
isBlackJack = false;
hasFaceDown = false;
handValue = 0;
}
#endif
blackjackrevised2/main.cppblackjackrevised2/main.cpp/*
HEADER
main for testing
*/
#include<iostream>
#include"BlackJackCard.h"
#include"BlackJackDeck.h"
#include"BlackJackHand.h"
#include"BlackJack.h"
#include"ValidInput.h"
usingnamespace std;
enumState
{
MainMenu,
DeckNumber,
Game,
Exit
};
int main()
{
State state =MainMenu;
int input =0;
string error ="";
int deckNumber =1;
while(state !=Exit)
{
if(state ==MainMenu)
{
cout <<"Main Menu nnnn"<<"1. Startn2. Exit"<< en
dl;
cout << error << endl;
error ="";
ValidInput::CinGetInteger(input,"Enter Choice: ","");
switch(input)
{
case1:
state =DeckNumber;
break;
case2:
state =Exit;
break;
default:
error ="Invalid Option";
}
}
elseif(state ==DeckNumber)
{
cout <<"How many decks do you want to play with? n
nnn"<<"1. (1)n2. (2)n3. (4)n4. (6)n5. (8)"<< endl;
cout << error << endl;
error ="";
ValidInput::CinGetInteger(input,"Enter Choice: ","");
switch(input)
{
case1:
deckNumber =1;
state =Game;
break;
case2:
deckNumber =2;
state =Game;
break;
case3:
deckNumber =4;
state =Game;
break;
case4:
deckNumber =6;
state =Game;
break;
case5:
deckNumber =8;
state =Game;
break;
default:
error ="Invalid Option";
}
}
elseif(state ==Game)
{
BlackJack game(deckNumber);
game.Run();
state =MainMenu;
}
system("CLS");
}
return0;
}
blackjackrevised2/ValidInput.h
//Nick Pierson
//Validation and Utility Functions
#ifndef _VALIDINPUT
#define _VALIDINPUT
#include <sstream>
#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <climits> // for limits of a int INT_MIN and
INT_MAX
#include <cfloat> // for limits of a double DBL_MIN and
DBL_MAX
using namespace std;
namespace ValidInput
{
bool IsStringInteger(string);
int StringToInteger(string);
bool CinGetInteger(int& value, string preText = "Please
enter an integer: ", string postText = "nPlease enter a valid
integer.n");
//
double GetValidDouble(const double MIN = -DBL_MAX,
const double MAX = DBL_MAX);
/** ClearInputBuffer function
* Clears the input buffer and resets the fail state of an
istream object.
*
* @param in (istream object by ref) - the object
to clear & reset; defaults to cin.
* @return none.
*/
void ClearInputBuffer(istream &in = cin); // function
prototype
bool IsStringInteger(string sInput)
{
char character = 0;
int number = 0;
stringstream linestream(sInput);
return ((linestream >> number) && !(linestream >>
character));
}
int StringToInteger(string sInput)
{
int number = 0;
if (IsStringInteger(sInput))
{
stringstream linestream(sInput);
linestream >> number;
}
return number;
}
bool CinGetInteger(int& value, string preText, string
postText)
{
string input = "";
bool valid = true;
cout << preText;
cin.sync();
getline(cin, input);
if (IsStringInteger(input))
{
value = StringToInteger(input);
}
else
{
value = -1;
cout << postText;
valid = false;
}
return valid;
}
//THOMS CODE
double GetValidDouble(const double MIN, const double
MAX)
{
double validNumber = 0.0; // holds the user input
cin >> validNumber; // try to get input
if(cin.fail()) // if user input fails...
{
// reset the cin object and clear the buffer.
ClearInputBuffer();
// report the problem to the user.
cerr << "nInvalid input. Please try again and enter
a numeric value.n";
// Try again by calling the function again
(recursion)
validNumber = GetValidDouble(MIN, MAX);
}
else if(validNumber < MIN || validNumber > MAX)//
if value is outside range...
{
// report the problem to the user.
cerr << "nInvalid input. Please try again and enter
a value between "
<< MIN << " and " << MAX << ".n";
// Try again by call the function again (recursion)
validNumber = GetValidDouble(MIN, MAX);
}
return validNumber; // returns a valid value to the
calling function.
}
void ClearInputBuffer(istream &in)
{
char characterFromBuffer; // a char variable to hold
input from the buffer
// if the in object has failed...
if(in.fail())
{
in.clear(); // clear the fail state of the object
characterFromBuffer = in.get(); // attempt to
read a character
// while the character read is not new-line or not
end-of-file
while (characterFromBuffer != 'n' &&
characterFromBuffer != EOF)
{
// therefore something was read from the
buffer
// attempt to read another character
characterFromBuffer = in.get();
} // end of while
}// end of if
} // end of ClearInputBuffer
}
#endif

More Related Content

Similar to blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx

package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfinfo430661
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfasif1401
 
ANS#include iostream int Rn_get(int low, int high); int cva.pdf
ANS#include iostream int Rn_get(int low, int high); int cva.pdfANS#include iostream int Rn_get(int low, int high); int cva.pdf
ANS#include iostream int Rn_get(int low, int high); int cva.pdfanikkothari1
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfezzi97
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
New Tools for a More Functional C++
New Tools for a More Functional C++New Tools for a More Functional C++
New Tools for a More Functional C++Sumant Tambe
 
Introduction Now that the Card and Deck classes are completed, th.pdf
Introduction Now that the Card and Deck classes are completed, th.pdfIntroduction Now that the Card and Deck classes are completed, th.pdf
Introduction Now that the Card and Deck classes are completed, th.pdfcharanjit1717
 

Similar to blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx (9)

package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 
The main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdfThe main class of the tictoe game looks like.public class Main {.pdf
The main class of the tictoe game looks like.public class Main {.pdf
 
Code em Poker
Code em PokerCode em Poker
Code em Poker
 
AI For Texam Hold'em poker
AI For Texam Hold'em pokerAI For Texam Hold'em poker
AI For Texam Hold'em poker
 
ANS#include iostream int Rn_get(int low, int high); int cva.pdf
ANS#include iostream int Rn_get(int low, int high); int cva.pdfANS#include iostream int Rn_get(int low, int high); int cva.pdf
ANS#include iostream int Rn_get(int low, int high); int cva.pdf
 
C++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdfC++You will design a program to play a simplified version of war, .pdf
C++You will design a program to play a simplified version of war, .pdf
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
New Tools for a More Functional C++
New Tools for a More Functional C++New Tools for a More Functional C++
New Tools for a More Functional C++
 
Introduction Now that the Card and Deck classes are completed, th.pdf
Introduction Now that the Card and Deck classes are completed, th.pdfIntroduction Now that the Card and Deck classes are completed, th.pdf
Introduction Now that the Card and Deck classes are completed, th.pdf
 

More from AASTHA76

(APA 6th Edition Formatting and St.docx
(APA 6th Edition Formatting and St.docx(APA 6th Edition Formatting and St.docx
(APA 6th Edition Formatting and St.docxAASTHA76
 
(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx
(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx
(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docxAASTHA76
 
(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx
(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx
(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docxAASTHA76
 
(Assmt 1; Week 3 paper) Using ecree Doing the paper and s.docx
(Assmt 1; Week 3 paper)  Using ecree        Doing the paper and s.docx(Assmt 1; Week 3 paper)  Using ecree        Doing the paper and s.docx
(Assmt 1; Week 3 paper) Using ecree Doing the paper and s.docxAASTHA76
 
(Image retrieved at httpswww.google.comsearchhl=en&biw=122.docx
(Image retrieved at  httpswww.google.comsearchhl=en&biw=122.docx(Image retrieved at  httpswww.google.comsearchhl=en&biw=122.docx
(Image retrieved at httpswww.google.comsearchhl=en&biw=122.docxAASTHA76
 
(Dis) Placing Culture and Cultural Space Chapter 4.docx
(Dis) Placing Culture and Cultural Space Chapter 4.docx(Dis) Placing Culture and Cultural Space Chapter 4.docx
(Dis) Placing Culture and Cultural Space Chapter 4.docxAASTHA76
 
(1) Define the time value of money.  Do you believe that the ave.docx
(1) Define the time value of money.  Do you believe that the ave.docx(1) Define the time value of money.  Do you believe that the ave.docx
(1) Define the time value of money.  Do you believe that the ave.docxAASTHA76
 
(chapter taken from Learning Power)From Social Class and t.docx
(chapter taken from Learning Power)From Social Class and t.docx(chapter taken from Learning Power)From Social Class and t.docx
(chapter taken from Learning Power)From Social Class and t.docxAASTHA76
 
(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx
(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx
(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docxAASTHA76
 
(a) The current ratio of a company is 61 and its acid-test ratio .docx
(a) The current ratio of a company is 61 and its acid-test ratio .docx(a) The current ratio of a company is 61 and its acid-test ratio .docx
(a) The current ratio of a company is 61 and its acid-test ratio .docxAASTHA76
 
(1) How does quantum cryptography eliminate the problem of eaves.docx
(1) How does quantum cryptography eliminate the problem of eaves.docx(1) How does quantum cryptography eliminate the problem of eaves.docx
(1) How does quantum cryptography eliminate the problem of eaves.docxAASTHA76
 
#transformation10EventTrendsfor 201910 Event.docx
#transformation10EventTrendsfor 201910 Event.docx#transformation10EventTrendsfor 201910 Event.docx
#transformation10EventTrendsfor 201910 Event.docxAASTHA76
 
$10 now and $10 when complete Use resources from the required .docx
$10 now and $10 when complete Use resources from the required .docx$10 now and $10 when complete Use resources from the required .docx
$10 now and $10 when complete Use resources from the required .docxAASTHA76
 
#MicroXplorer Configuration settings - do not modifyFile.Versio.docx
#MicroXplorer Configuration settings - do not modifyFile.Versio.docx#MicroXplorer Configuration settings - do not modifyFile.Versio.docx
#MicroXplorer Configuration settings - do not modifyFile.Versio.docxAASTHA76
 
#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docx#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docxAASTHA76
 
$ stated in thousands)Net Assets, Controlling Interest.docx
$ stated in thousands)Net Assets, Controlling Interest.docx$ stated in thousands)Net Assets, Controlling Interest.docx
$ stated in thousands)Net Assets, Controlling Interest.docxAASTHA76
 
#include stdio.h#include stdlib.h#include pthread.h#in.docx
#include stdio.h#include stdlib.h#include pthread.h#in.docx#include stdio.h#include stdlib.h#include pthread.h#in.docx
#include stdio.h#include stdlib.h#include pthread.h#in.docxAASTHA76
 
#include customer.h#include heap.h#include iostream.docx
#include customer.h#include heap.h#include iostream.docx#include customer.h#include heap.h#include iostream.docx
#include customer.h#include heap.h#include iostream.docxAASTHA76
 
#Assessment BriefDiploma of Business Eco.docx
#Assessment BriefDiploma of Business Eco.docx#Assessment BriefDiploma of Business Eco.docx
#Assessment BriefDiploma of Business Eco.docxAASTHA76
 
#include stdio.h#include stdint.h#include stdbool.h.docx
#include stdio.h#include stdint.h#include stdbool.h.docx#include stdio.h#include stdint.h#include stdbool.h.docx
#include stdio.h#include stdint.h#include stdbool.h.docxAASTHA76
 

More from AASTHA76 (20)

(APA 6th Edition Formatting and St.docx
(APA 6th Edition Formatting and St.docx(APA 6th Edition Formatting and St.docx
(APA 6th Edition Formatting and St.docx
 
(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx
(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx
(a) Thrasymachus’ (the sophist’s) definition of Justice or Right o.docx
 
(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx
(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx
(Glossary of Telemedicine and eHealth)· Teleconsultation Cons.docx
 
(Assmt 1; Week 3 paper) Using ecree Doing the paper and s.docx
(Assmt 1; Week 3 paper)  Using ecree        Doing the paper and s.docx(Assmt 1; Week 3 paper)  Using ecree        Doing the paper and s.docx
(Assmt 1; Week 3 paper) Using ecree Doing the paper and s.docx
 
(Image retrieved at httpswww.google.comsearchhl=en&biw=122.docx
(Image retrieved at  httpswww.google.comsearchhl=en&biw=122.docx(Image retrieved at  httpswww.google.comsearchhl=en&biw=122.docx
(Image retrieved at httpswww.google.comsearchhl=en&biw=122.docx
 
(Dis) Placing Culture and Cultural Space Chapter 4.docx
(Dis) Placing Culture and Cultural Space Chapter 4.docx(Dis) Placing Culture and Cultural Space Chapter 4.docx
(Dis) Placing Culture and Cultural Space Chapter 4.docx
 
(1) Define the time value of money.  Do you believe that the ave.docx
(1) Define the time value of money.  Do you believe that the ave.docx(1) Define the time value of money.  Do you believe that the ave.docx
(1) Define the time value of money.  Do you believe that the ave.docx
 
(chapter taken from Learning Power)From Social Class and t.docx
(chapter taken from Learning Power)From Social Class and t.docx(chapter taken from Learning Power)From Social Class and t.docx
(chapter taken from Learning Power)From Social Class and t.docx
 
(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx
(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx
(Accessible at httpswww.hatchforgood.orgexplore102nonpro.docx
 
(a) The current ratio of a company is 61 and its acid-test ratio .docx
(a) The current ratio of a company is 61 and its acid-test ratio .docx(a) The current ratio of a company is 61 and its acid-test ratio .docx
(a) The current ratio of a company is 61 and its acid-test ratio .docx
 
(1) How does quantum cryptography eliminate the problem of eaves.docx
(1) How does quantum cryptography eliminate the problem of eaves.docx(1) How does quantum cryptography eliminate the problem of eaves.docx
(1) How does quantum cryptography eliminate the problem of eaves.docx
 
#transformation10EventTrendsfor 201910 Event.docx
#transformation10EventTrendsfor 201910 Event.docx#transformation10EventTrendsfor 201910 Event.docx
#transformation10EventTrendsfor 201910 Event.docx
 
$10 now and $10 when complete Use resources from the required .docx
$10 now and $10 when complete Use resources from the required .docx$10 now and $10 when complete Use resources from the required .docx
$10 now and $10 when complete Use resources from the required .docx
 
#MicroXplorer Configuration settings - do not modifyFile.Versio.docx
#MicroXplorer Configuration settings - do not modifyFile.Versio.docx#MicroXplorer Configuration settings - do not modifyFile.Versio.docx
#MicroXplorer Configuration settings - do not modifyFile.Versio.docx
 
#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docx#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docx
 
$ stated in thousands)Net Assets, Controlling Interest.docx
$ stated in thousands)Net Assets, Controlling Interest.docx$ stated in thousands)Net Assets, Controlling Interest.docx
$ stated in thousands)Net Assets, Controlling Interest.docx
 
#include stdio.h#include stdlib.h#include pthread.h#in.docx
#include stdio.h#include stdlib.h#include pthread.h#in.docx#include stdio.h#include stdlib.h#include pthread.h#in.docx
#include stdio.h#include stdlib.h#include pthread.h#in.docx
 
#include customer.h#include heap.h#include iostream.docx
#include customer.h#include heap.h#include iostream.docx#include customer.h#include heap.h#include iostream.docx
#include customer.h#include heap.h#include iostream.docx
 
#Assessment BriefDiploma of Business Eco.docx
#Assessment BriefDiploma of Business Eco.docx#Assessment BriefDiploma of Business Eco.docx
#Assessment BriefDiploma of Business Eco.docx
 
#include stdio.h#include stdint.h#include stdbool.h.docx
#include stdio.h#include stdint.h#include stdbool.h.docx#include stdio.h#include stdint.h#include stdbool.h.docx
#include stdio.h#include stdint.h#include stdbool.h.docx
 

Recently uploaded

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 

Recently uploaded (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 

blackjackrevised2BlackJack.hBLACKJACK#ifndef _BLACKJA.docx

  • 1. blackjackrevised2/BlackJack.h //BLACKJACK #ifndef _BLACKJACK #define _BLACKJACK #include "BlackJackHand.h" #include "BlackJackDeck.h" #include "ValidInput.h" class BlackJack { public: BlackJack(unsigned int deckNumber = 1); void Run(); //GetArrayOfStats
  • 2. private: enum class GameState { Wager, FirstRound, //check for blackjack and allow double down; splitting COULD also go here; might be better to have isFirstRound bool PlayerInput, DealerReveal, //let player surrender DealerInput, EndRound, Exit }; const int DECK_NUMBER; // not actually used should delete string message; string error;
  • 3. int input; string name; //PLAYER NAME needed for persistent stats (not implemented) should be constructor parameter default:"Player" BlackJackDeck deck; BlackJackHand player; BlackJackHand dealer; int playerChips; int playerWager; //stuff for persistant stats (not implemented) maybe make it an array which can be passed to the main.cpp menu which will handle the user profile txt unsigned long int handsPlayed; unsigned long int handsWon; unsigned long int handsLost; unsigned long int chipsWon; unsigned long int chipsLost;
  • 4. void Output(); void Input(); void Processing(); void DealCards(); void HandsOnTable(); GameState state; }; BlackJack::BlackJack(unsigned int deckNumber) : DECK_NUMBER(deckNumber), deck(deckNumber) { playerChips = 500; //use static constant input = 0; state = GameState::Wager; deck.Shuffle();
  • 5. } void BlackJack::Run() { while (state != GameState::Exit) { Output(); Input(); Processing(); } } void BlackJack::Output() { system("CLS"); //clear the console if (state == GameState::Wager) {
  • 6. //player betting screen cout << "Place your bet." << endl << endl << "Player Chips: " << playerChips << endl << endl << error << endl << "How much do you want to wager? "; } else if (state == GameState::PlayerInput) { //player input menu HandsOnTable(); cout << "1. Hit" << endl << "2. Stand" << endl //<< "3. Double Down //not done" << endl //<< "4. Surrender //not done" << endl << endl << error << message << endl << "Option: ";
  • 7. } else if (state == GameState::DealerInput) { HandsOnTable(); cout << message << endl << "Continue..."; } else if (state == GameState::EndRound) { HandsOnTable(); cout << message << endl << "Continue..."; } }
  • 8. void BlackJack::Input() { string sInput; getline(cin, sInput); stringstream linestream(sInput); linestream >> input; } void BlackJack::Processing() { //CHECK IF DECK IS EMPTY HERE error = ""; message = ""; //new round state? if (state == GameState::Wager)
  • 9. { //player betting screen if (input < 1 ) { error += "You must bet at least one chip. "; } else if (input > playerChips) { error += "You cannot bet more chips than you have. "; } else { playerWager = input; playerChips -= input; stringstream linestream; linestream << "Player wagers " << playerWager << " chips. ";
  • 10. message = linestream.str(); state = GameState::PlayerInput; DealCards(); } } else if (state == GameState::PlayerInput) { //player input menu //may have to split GameState::FirstRound where we let player double down and check for blackjack switch (input) { case 1: { BlackJackCard card = deck.DrawCard();
  • 11. player.AddCard(card); message += "Player drew "; message += card.ToString(); message += ". "; if (player.GetBust()) { message += "Player busts. "; dealer.FlipFirstCard(); state = GameState::EndRound; } else if (player.GetHandValue() == 21) { dealer.FlipFirstCard(); state = GameState::DealerInput;
  • 12. } break; } case 2: { message += "Player stands. Dealer hand is revealed. "; dealer.FlipFirstCard(); state = GameState::DealerInput; break; } /* case 3: //betting not implemented break; case 4: break; */ default: error += "Invalid Option "; }
  • 13. } else if (state == GameState::DealerInput) { if (dealer.GetHandValue() < 17 && dealer.GetHandValue() <= player.GetHandValue()) { BlackJackCard card = deck.DrawCard(); message += "Dealer drew "; message += card.ToString(); message += ". "; dealer.AddCard(card); if (dealer.GetBust()) { message += " Dealer busts. "; state = GameState::EndRound; }
  • 14. else if (dealer.GetHandValue() >= 17) { message += " Dealer stands. "; state = GameState::EndRound; } } else { message += "Dealer stands. "; state = GameState::EndRound; } } else if (state == GameState::EndRound) { if (playerWager == 0) { if (playerChips == 0)
  • 15. { } else { state = GameState::Wager; player.EmptyHand(); dealer.EmptyHand(); } } else { if (player.GetBust() || (dealer.GetHandValue() > player.GetHandValue() && !dealer.GetBust())) { stringstream linestream; linestream << "You lost " << playerWager << " chips. "; message = linestream.str();
  • 16. } else if (player.GetHandValue() == dealer.GetHandValue()) { playerChips += playerWager; stringstream linestream; linestream << "Push. " << playerWager << " chips were returned to you. "; message = linestream.str(); } else { stringstream linestream; if (player.isBlackJack) { playerChips += playerWager * 3 / 2; linestream << "You won " << (playerWager * 3 / 2) << " chips. ";
  • 17. } else { playerChips += playerWager * 2; linestream << "You won " << playerWager << " chips. "; } message = linestream.str(); } playerWager = 0; } } } void BlackJack::DealCards() {
  • 18. BlackJackCard card; card = deck.DrawCard(); player.AddCard(card); card = deck.DrawCard(); dealer.AddCard(card); card = deck.DrawCard(); player.AddCard(card); card = deck.DrawCard(); dealer.AddCard(card); if (player.GetHandValue() == 21) { message += "Player Black Jack! "; player.isBlackJack = true;
  • 19. state = GameState::EndRound; } if (dealer.GetHandValue() == 21) { message += "Dealer Black Jack! "; dealer.isBlackJack = true; state = GameState::EndRound; } else if ((dealer.GetHandValue() == 21 && player.GetHandValue() == 21) == false) { dealer.FlipFirstCard(); } } void BlackJack::HandsOnTable() { cout << "Cards left in deck: " << deck.CardsRemaining() << endl;
  • 20. cout << "Dealer Hand: " << dealer.ToString() << " (" << dealer.GetHandValue(); if (dealer.GetFaceDown()) cout << "?"; //estimate dealer's hand cout << ")nn" << "Player Hand: " << player.ToString() << " (" << player.GetHandValue() << ")" << endl << endl << "Player Chips: " << playerChips << endl << "Player Wager: " << playerWager << endl << endl; } #endif blackjackrevised2/BlackJackCard.h /* HEADER */
  • 21. #ifndef _BLACKJACK_CARD #define _BLACKJACK_CARD #include <iostream> #include <stdexcept> #include <sstream> using namespace std; enum Rank // converts implicitly to int { Ace = 1, // explicity set Ace to 1 Two, Three, Four, Five, Six, Seven,
  • 22. Eight, Nine, Ten, Jack, Queen, King }; enum Suit // converts implicitly to int { Spades = 1, Hearts, Diamonds, Clubs }; class BlackJackCard {
  • 23. public: //constants static const Rank MIN_RANK; static const Rank MAX_RANK; static const Suit MIN_SUIT; static const Suit MAX_SUIT; static const char RANKS[]; // an array that holds the names of the ranks static const char SUITS[]; //constructors BlackJackCard() : myRank(Rank::Ace), mySuit(Suit::Spades), isFaceUp(true) {} BlackJackCard(Rank rank, Suit suit, bool faceUp = true); //accessors Rank GetRank(){ return myRank; }
  • 24. Suit GetSuit(){ return mySuit; } bool GetFaceUp(){ return isFaceUp; } string ToString(); //mutators void SetRank(Rank rank); void SetSuit(Suit suit); void FlipCard(){ isFaceUp = !isFaceUp; } private: Rank myRank; Suit mySuit; bool isFaceUp; }; //static member initialization const Rank BlackJackCard::MIN_RANK = Rank::Ace;
  • 25. const Rank BlackJackCard::MAX_RANK = Rank::King; const Suit BlackJackCard::MIN_SUIT = Suit::Spades; const Suit BlackJackCard::MAX_SUIT = Suit::Clubs; const char BlackJackCard::RANKS[] = { '0', 'A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'}; const char BlackJackCard::SUITS[] = { '0', 'S', 'H', 'D', 'C' }; BlackJackCard::BlackJackCard(Rank rank, Suit suit, bool faceUp) { SetRank(rank); mySuit = suit; isFaceUp = faceUp; } void BlackJackCard::SetRank(Rank rank) { if(rank < MIN_RANK || rank > MAX_RANK)
  • 26. { //throw out of range exception with description stringstream strOut; strOut << "Rank argument: " << rank << " is out of range. Rank must be between " << MIN_RANK << " and " << MAX_RANK << ". "; throw out_of_range(strOut.str()); } else { myRank = rank; } } void BlackJackCard::SetSuit(Suit suit) { if(suit < MIN_SUIT || suit > MAX_SUIT) { //throw out of range exception with description stringstream strOut;
  • 27. strOut << "Suit argument: " << suit << " is out of range. Suit must be between " << MIN_SUIT << " and " << MAX_SUIT << ". "; throw out_of_range(strOut.str()); } else { mySuit = suit; } } string BlackJackCard::ToString() { stringstream strOut; if (isFaceUp) { strOut << SUITS[GetSuit()] << RANKS[GetRank()];
  • 28. } else { strOut << '?' << '?'; } return strOut.str(); } #endif blackjackrevised2/BlackJackDeck.h /* HEADER */
  • 29. #ifndef _BLACKJACK_DECK #define _BLACKJACK_DECK #include "BlackJackCard.h" #include <ctime> #include <vector> using namespace std; class BlackJackDeck { public: static const int STANDARD_SIZE; //constructor
  • 30. BlackJackDeck(unsigned int num = 1); // use usinged int? //dont need to delete vector? //destructor //copy constructor //assignment operator BlackJackCard DrawCard(); //initialize void Initialize(); //use vector? deque? stack? void Shuffle(); const int CardsRemaining() { return cardNumber; } void OutputDeck(); //debug only, should not exist here
  • 31. private: int deckNumber; int cardNumber; vector<BlackJackCard> deck; }; const int BlackJackDeck::STANDARD_SIZE = BlackJackCard::MAX_SUIT * BlackJackCard::MAX_RANK; //52 card deck BlackJackDeck::BlackJackDeck(unsigned int num) { deckNumber = num; Initialize(); } void BlackJackDeck::Initialize()
  • 32. { deck.clear(); cardNumber = deckNumber * STANDARD_SIZE; deck.reserve(cardNumber); //generate deck BlackJackCard card; for (int i = 0; i < deckNumber; i++) { for (int suit = BlackJackCard::MIN_SUIT; suit <= BlackJackCard::MAX_SUIT; suit++) { for (int rank = BlackJackCard::MIN_RANK; rank <= BlackJackCard::MAX_RANK; rank++) { card.SetSuit(static_cast<Suit>(suit)); card.SetRank(static_cast<Rank>(rank));
  • 33. deck.push_back(card); } } } } void BlackJackDeck::Shuffle() { //just use random_shuffle lmao <algorithm> vector<BlackJackCard> tempDeck = deck; deck.clear(); int randomCard = 0; srand(time(NULL)); for (int i = 0; i < cardNumber; i++) { randomCard = rand() % (cardNumber - i);
  • 34. deck.push_back(tempDeck.at(randomCard)); tempDeck.erase(tempDeck.begin() + randomCard); } } BlackJackCard BlackJackDeck::DrawCard() { BlackJackCard card = deck.back(); deck.pop_back(); cardNumber--; return card; } //remove later void BlackJackDeck::OutputDeck() {
  • 35. cout << "nDeck Contentsn" << "===================" << endl; for (int i = 0; i < cardNumber; i++) { cout << deck.at(i).ToString() << endl; } cout << "===================" << endl; } #endif blackjackrevised2/BlackJackHand.h /* HEADER
  • 36. BlackJackHand */ #ifndef _BLACKJACK_HAND #define _BLACKJACK_HAND #include "BlackJackCard.h" #include <list> class BlackJackHand { public: //constructor BlackJackHand() { handValue = 0; isBust = false; isBlackJack = false; hasFaceDown = false;}
  • 37. void EmptyHand(); void AddCard(BlackJackCard card); void CalculateValue(); // needed to recalculate if has ace and hand is bust string ToString(); bool GetBust(){ return isBust; } bool GetFaceDown(){ return hasFaceDown; } int GetHandValue(){ return handValue; } bool isBlackJack; void FlipFirstCard(); private: list<BlackJackCard> hand; list<BlackJackCard>::iterator handIter;
  • 38. bool isBust; bool hasFaceDown; int handValue; }; //constuctor? void BlackJackHand::AddCard(BlackJackCard card) { hand.push_back(card); CalculateValue(); } void BlackJackHand::CalculateValue() {
  • 39. bool calculate = true; int aceLow = 0; //loop while (calculate) { hasFaceDown = false; handValue = 0; int aceCount = 0; for(handIter = hand.begin(); handIter != hand.end(); ++handIter) { if (handIter->GetFaceUp()) { //if card is ace ++acecount add 11 if (handIter->GetRank() == Ace)
  • 40. { if (aceLow > aceCount) { handValue += 1; } else { handValue += 11; } aceCount++; } //if card is jack, queen, king ++10 else if (handIter->GetRank() == Jack || handIter->GetRank() == Queen || handIter->GetRank() == King) { handValue += 10; } //else use enum rank int else
  • 41. { handValue += handIter->GetRank(); } } else { hasFaceDown = true; } } //if handValue > 21 and contians aces -> recalculate with one ace as value of 1 if (handValue > 21 && aceLow < aceCount) { aceLow++; } //elseif value > 21 isBust = true else
  • 42. { if (handValue > 21) { isBust = true; } calculate = false; } } } string BlackJackHand::ToString() { stringstream strOut; for(handIter = hand.begin(); handIter != hand.end(); ++handIter) { strOut << handIter->ToString() << ' '; }
  • 43. return strOut.str(); } void BlackJackHand::FlipFirstCard() { handIter = hand.begin(); handIter->FlipCard(); CalculateValue(); } void BlackJackHand::EmptyHand() { hand.clear(); isBust = false; isBlackJack = false; hasFaceDown = false; handValue = 0;
  • 45. #include"BlackJackCard.h" #include"BlackJackDeck.h" #include"BlackJackHand.h" #include"BlackJack.h" #include"ValidInput.h" usingnamespace std; enumState { MainMenu, DeckNumber, Game, Exit }; int main() { State state =MainMenu; int input =0; string error =""; int deckNumber =1; while(state !=Exit) { if(state ==MainMenu) { cout <<"Main Menu nnnn"<<"1. Startn2. Exit"<< en dl; cout << error << endl; error ="";
  • 46. ValidInput::CinGetInteger(input,"Enter Choice: ",""); switch(input) { case1: state =DeckNumber; break; case2: state =Exit; break; default: error ="Invalid Option"; } } elseif(state ==DeckNumber) { cout <<"How many decks do you want to play with? n nnn"<<"1. (1)n2. (2)n3. (4)n4. (6)n5. (8)"<< endl; cout << error << endl; error =""; ValidInput::CinGetInteger(input,"Enter Choice: ",""); switch(input) { case1: deckNumber =1; state =Game; break;
  • 47. case2: deckNumber =2; state =Game; break; case3: deckNumber =4; state =Game; break; case4: deckNumber =6; state =Game; break; case5: deckNumber =8; state =Game; break; default: error ="Invalid Option"; } } elseif(state ==Game) { BlackJack game(deckNumber); game.Run(); state =MainMenu; } system("CLS"); } return0; } blackjackrevised2/ValidInput.h
  • 48. //Nick Pierson //Validation and Utility Functions #ifndef _VALIDINPUT #define _VALIDINPUT #include <sstream> #include <string> #include <iostream> #include <cstdio> #include <cstdlib> #include <iomanip> #include <climits> // for limits of a int INT_MIN and INT_MAX #include <cfloat> // for limits of a double DBL_MIN and DBL_MAX using namespace std; namespace ValidInput
  • 49. { bool IsStringInteger(string); int StringToInteger(string); bool CinGetInteger(int& value, string preText = "Please enter an integer: ", string postText = "nPlease enter a valid integer.n"); // double GetValidDouble(const double MIN = -DBL_MAX, const double MAX = DBL_MAX); /** ClearInputBuffer function * Clears the input buffer and resets the fail state of an istream object. * * @param in (istream object by ref) - the object to clear & reset; defaults to cin. * @return none. */ void ClearInputBuffer(istream &in = cin); // function prototype
  • 50. bool IsStringInteger(string sInput) { char character = 0; int number = 0; stringstream linestream(sInput); return ((linestream >> number) && !(linestream >> character)); } int StringToInteger(string sInput) { int number = 0; if (IsStringInteger(sInput)) { stringstream linestream(sInput);
  • 51. linestream >> number; } return number; } bool CinGetInteger(int& value, string preText, string postText) { string input = ""; bool valid = true; cout << preText; cin.sync(); getline(cin, input); if (IsStringInteger(input)) { value = StringToInteger(input); }
  • 52. else { value = -1; cout << postText; valid = false; } return valid; } //THOMS CODE double GetValidDouble(const double MIN, const double MAX) { double validNumber = 0.0; // holds the user input
  • 53. cin >> validNumber; // try to get input if(cin.fail()) // if user input fails... { // reset the cin object and clear the buffer. ClearInputBuffer(); // report the problem to the user. cerr << "nInvalid input. Please try again and enter a numeric value.n"; // Try again by calling the function again (recursion) validNumber = GetValidDouble(MIN, MAX); } else if(validNumber < MIN || validNumber > MAX)// if value is outside range... { // report the problem to the user. cerr << "nInvalid input. Please try again and enter a value between " << MIN << " and " << MAX << ".n"; // Try again by call the function again (recursion)
  • 54. validNumber = GetValidDouble(MIN, MAX); } return validNumber; // returns a valid value to the calling function. } void ClearInputBuffer(istream &in) { char characterFromBuffer; // a char variable to hold input from the buffer // if the in object has failed... if(in.fail()) { in.clear(); // clear the fail state of the object characterFromBuffer = in.get(); // attempt to read a character // while the character read is not new-line or not end-of-file while (characterFromBuffer != 'n' && characterFromBuffer != EOF) { // therefore something was read from the
  • 55. buffer // attempt to read another character characterFromBuffer = in.get(); } // end of while }// end of if } // end of ClearInputBuffer } #endif