#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
usingnamespace std;
constint MAX_TRIES = 5;
int letterFill (char, string, string&);
int main()
{
string name;
char letter;
int num_of_wrong_guesses = 0;
int amount;
string word;
cout << "Welcome to Hangman \n" << endl;
// Entering the amount of words to be used.
std::cout << "How many words do you have? (Please enter a number between 2 and 10)" << std::endl;
cin >> amount;
// Entering the words needed for gameplay.
string words;
cout << "\n Please enter " << amount << " words" << endl;
getline (cin, words);
cout << "\n Thank you. Now lets play Hangman!" << endl;
// instert a code to choose a word at random
srand(time(NULL));
int n = rand() % 10;
word = words[n];
// code for actual gameplay
string unknown(word.length(), '*');
cout << "\n Each letter is represented by an asterisk.";
cout << "\n You have to type only one letter in each try.";
cout << "\n You have " << MAX_TRIES << " tries to guess your word";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n Guess a letter: ";
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "Sorry, that letter isn't there!" << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You have found a letter!" << endl;
}
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
if (word == unknown)
{
cout << word << endl;
cout << "You got it right!";
break;
}
}
// Game over
if (num_of_wrong_guesses == MAX_TRIES)
{
cout << "\n Sorry, you lose... you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.ignore();
cin.get();
return 0;
}
int letterFill(char guess, string secretword, string &guessword)
{
int i;
int matches = 0;
int len = secretword.length();
for (i = 0, i < len; i++;)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
#include <iostream>
#include <string>
#include <vector>
#include <random>
#include <chrono>
int main()
{
std::vector<std::string> words;
std::string input;
std::cout << "Enter your words (use QUIT to quit): ";
while (true)
{
std::cin >> input;
if (input == "QUIT")
{
break;
}
words.push_back(input);
}
std::cout << "\nYou added " << words.size() << " words.\n";
// create a default random engine seeding it with the current system clock time
std::default_random_engine URNG (static_cast<unsignedint> (std::chrono::system_clock::now().time_since_epoch().count()));
// create a distribution to choose a random word
std::uniform_int_distribution<> dis(0, words.size() - 1);
std::string word = words[dis(URNG)];
std::cout << "\nThe chosen word is '" << word << "'\n";
}
Enter your words (use QUIT to quit): now is the time for all good QUIT
You added 7 words.
The chosen word is 'all'