Skimmed the web for ideas on what to code and encountered some random blog post about Blackjack.
So here it is, my try on the game Blackjack, it's terminal based and pretty shitty.
In it's current state it doesn't support currency at all, which means you can't bet or win anything.
Neither can you split your hand, because stuff and reasons..
Since this is a multi-file project you'll find the repo, which contains everything,
here.
Main file, blackjack.cpp:
#include <iostream>
#include <string>
#include "modules/player.hpp"
#include "modules/deck.hpp"
#include "modules/hand.hpp"
using namespace std;
void displayHand(Player *player)
{
cout << player->getName() << " hand ";
for(char card : player->getHand())
{
cout << card << " ";
}
cout << " <" << player->getTotal() << ">" << endl;
}
void playerLogic(Player *player, Deck *deck)
{
// Stores the next instruction the player wants to execute
string action = "";
const string hit[] = {"Hit", "hit", "H", "h"};
const string stand[] = {"Stand", "stand", "S", "s"};
do // Start the interaction loop where the player can either Hit or Stand
{
displayHand(player);
cout << "(H)it or (S)tand? ";
cin >> action;
// Check for Hit instruction
for(string s : hit)
{
if(s.compare(action) == 0)
{
player->drawCard(deck);
action = "Hit";
}
}
// Check for Stand instruction
for(string s : stand)
{
if(s.compare(action) == 0)
{
action = "Stand";
}
}
}
while(player->getTotal() < 21 && action.compare("Hit") == 0);
displayHand(player);
}
void dealerLogic(Player *dealer, Player *player, Deck *deck)
{
/* Dealer: Keep drawing cards until either the sum is bigger or equal to
the sum of the player or we achieve a blackjack. */
while(dealer->getTotal() < 21 && player->getTotal() >= dealer->getTotal())
{
dealer->drawCard(deck);
}
displayHand(dealer);
}
int main()
{
Deck deck;
Player player;
Player dealer;
player.setName("Your");
dealer.setName("Dealer's");
dealer.drawCard(&deck);
/* Let the player only see one card of the drawn cards of the dealer, this
is usually the case in blackjack. */
displayHand(&dealer);
dealer.drawCard(&deck);
// Draw the first two cards of your hand
player.drawCard(&deck);
player.drawCard(&deck);
// Check if player drew a 21 the first time
if(player.getTotal() == 21 && dealer.getTotal() != 21)
{
displayHand(&player);
displayHand(&dealer);
cout << "You won!" << endl;
return 0;
}
playerLogic(&player, &deck);
if(player.getTotal() > 21)
{
cout << "Busted, you lose!" << endl;
return 0;
}
dealerLogic(&dealer, &player, &deck);
// Determine the winner
if(player.getTotal() == dealer.getTotal())
{
cout << "You and Dealer tied!" << endl;
}
else if(dealer.getTotal() < player.getTotal())
{
cout << "You won!" << endl;
}
else if(dealer.getTotal() > 21)
{
cout << "Dealer busted, you win!" << endl;
}
else if(dealer.getTotal() > player.getTotal())
{
cout << "Dealer won!" << endl;
}
return 0;
}