Skip to content

Instantly share code, notes, and snippets.

@tyqualters
Created June 28, 2020 20:44
Show Gist options
  • Select an option

  • Save tyqualters/bb74fbbcbc807660ab808b7ab5ec1abd to your computer and use it in GitHub Desktop.

Select an option

Save tyqualters/bb74fbbcbc807660ab808b7ab5ec1abd to your computer and use it in GitHub Desktop.
My very simple guessing game
#include <iostream>
#include <fstream>
#include <vector>
// check if input is a letter
bool isLetter(char character)
{
char alphabet[52] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(short i = 0; i < sizeof(alphabet); ++i)
if(tolower(character) == alphabet[i]) return true;
return false;
}
// check if a letter has been used or not
bool usedChar(char letter)
{
letter = tolower(letter);
static std::vector<char> vec{};
for(char a : vec)
if(a == letter) return true;
vec.push_back(letter);
return false;
}
// the game
int main(const int argc, const char* const* argv) noexcept
{
const int maxFails = 5;
int curFails = 0;
std::string word = "";
for(int i = 1; i < argc; ++i)
{
word += std::string(argv[i]);
if(i < argc) word += ' ';
}
std::string prog = "";
for(int i = 0; i < word.size(); ++i)
if(isLetter(word.at(i)))
prog += '_';
else
prog += ' ';
if(prog == word)
{
std::cout << "Pass the word via the command-line" << std::endl;
return 0;
}
std::cout << "You get " << maxFails << " failed attempts before you lose!" << std::endl;
while(prog != word)
{
std::cout << "You have: " << prog << std::endl;
std::string userInput = "";
promptUI:
while(userInput.size() <= 0 || !isLetter(userInput.at(0)))
{
std::cout << "Please enter a letter: ";
getline(std::cin, userInput);
}
if(usedChar(userInput.at(0)))
{
userInput = "";
std::cout << "That letter has already been used." << std::endl;
goto promptUI;
}
bool wasUsed = false;
for(int i = 0; i < word.size(); ++i)
if(tolower(word.at(i)) == tolower(userInput.at(0)))
{
prog.at(i) = word.at(i);
wasUsed = true;
}
if(wasUsed)
std::cout << "Yup! That was a letter!" << std::endl;
else
{
std::cout << "Nope! Wasn't a letter. Try again." << std::endl;
if(maxFails > 0)
if(++curFails < maxFails)
std::cout << "You have " << (maxFails - curFails) << " fails left!" << std::endl;
else
{
std::cout << "You ran out of fails! Here was the answer:" << std::endl << word << std::endl;
return 0;
}
}
std::cout << std::endl;
}
std::cout << "Answer: " << prog << std::endl;
std::cout << "Yay! You got it!" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment