I made a simple Blackjack/21 game in C++. It does not use any fancy graphics, just the console output. It is as simple as it can get.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
void printData(int pTotal, int dCard) {
std::cout << "\nYour total is " << pTotal;
std::cout << "\nDealer has a " << dCard << " showing.\n";
}
int getCard() {
return std::rand() % 11 + 2;
}
void turn(int& pTotal, char choice, bool& stay) {
// If the user wants to hit
if (choice == 'H' || choice == 'h') {
// If the user hits 21 or above
if ((pTotal += getCard()) >= 21) {
std::cout << "Your total is " << pTotal;
stay = true;
}
return;
}
// Since the only other option can be to stay, then stay
stay = true;
}
int main() {
bool stay;
char choice = NULL;
while (true) {
std::cout << "================================";
stay = false;
// Initialize srand and get random card numbers
std::srand(std::time(0));
int dCard = getCard();
int pTotal = getCard() + getCard();
int dTotal = dCard + getCard();
// Player's turn
while (!stay) {
printData(pTotal, dCard);
std::cout << "[H]it or [S]tay?\n";
std::cin >> choice;
turn(pTotal, choice, stay);
}
stay = false;
std::cout << "\n\nIt is now the dealer's turn!\n";
// Dealer's turn
while (dTotal <= 21 && !stay) {
if (dTotal >= 17)
stay = true;
else
dTotal += getCard();
}
// Display winner
std::cout << "\n\nThe player has " << pTotal << ".\nThe dealer has " << dTotal << ".\n\n";
if ((std::abs(21 - pTotal)) < (std::abs(21 - dTotal))) std::cout << "The player wins!\n";
else std::cout << "The dealer wins!\n";
}
}
- Is this code efficient?
- Is the code easy to read/understand and to follow?
- Are variable names appropriate?