Skip to content

Instantly share code, notes, and snippets.

@horiajurcut
Created April 15, 2019 13:32
Show Gist options
  • Save horiajurcut/81ab57f037fd4af758c91183bdf8c5f6 to your computer and use it in GitHub Desktop.
Save horiajurcut/81ab57f037fd4af758c91183bdf8c5f6 to your computer and use it in GitHub Desktop.
Hangman CPP
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
const int dictionarySize = 5;
const char* dictionary[dictionarySize] = {
"programming",
"encouragement",
"possibility",
"graphics",
"activities"
};
bool HasCharacter(const char newGuess, const std::vector<char>& guesses)
{
for (auto const& value : guesses)
{
if (value == newGuess) {
return true;
}
}
return false;
}
int GetRandomWord(const char* levels[], int start, int end)
{
srand((unsigned int)time(NULL));
int randomPick = rand() % end + start;
std::cout << "[DEBUG]: Random pick is " << randomPick << std::endl;
return randomPick;
}
int SizeOfWord(const char* word)
{
int size = 0;
while (*word != '\0')
{
++size;
++word;
}
return size;
}
bool CheckIfGuessIsCorrect(const char needle, const char* haystack)
{
while (*haystack != '\0')
{
if (*haystack == needle)
{
return true;
}
++haystack;
}
return false;
}
int DisplayHiddenLetters(const char* word, const std::vector<char>& guesses)
{
std::cout << std::endl;
std::cout << "==============================================================" << std::endl;
int countHidden = 0;
while (*word != '\0')
{
if (HasCharacter(*word, guesses))
{
std::cout << " " << *word << " ";
}
else
{
std::cout << " _ ";
++countHidden;
}
++word;
}
std::cout << std::endl;
std::cout << "==============================================================" << std::endl;
std::cout << std::endl;
return countHidden;
}
int main()
{
const char* currentWord = dictionary[GetRandomWord(dictionary, 0, 5)];
std::cout << "[DEBUG]: The word is " << currentWord << std::endl;
const int maxGuesses = SizeOfWord(currentWord) + 3;
bool isRunning = true;
int countGuesses = 0;
std::vector<char> guessedLetters;
while (isRunning)
{
char guess;
std::cout << "[YOU] Your guess is: ";
std::cin >> guess;
std::cin.get();
std::cout << std::endl;
++countGuesses;
bool isGuessCorrect = CheckIfGuessIsCorrect(guess, currentWord);
if (isGuessCorrect)
{
guessedLetters.push_back(guess);
std::cout << "CORRECT GUESS!" << std::endl;
}
else
{
std::cout << "NO LUCK! TRY AGAIN!" << std::endl;
}
int hiddenLetters = DisplayHiddenLetters(currentWord, guessedLetters);
if (countGuesses <= maxGuesses && hiddenLetters == 0)
{
isRunning = false;
std::cout << std::endl;
std::cout << "[WON] Congrats, you are a true word doctor!" << std::endl;
std::cout << std::endl;
}
else if (countGuesses == maxGuesses && hiddenLetters > 0) {
isRunning = false;
std::cout << std::endl;
std::cout << "[LOST] You ran out of guesses, better luck next time!" << std::endl;
std::cout << std::endl;
}
}
std::cin.get();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment