(You must include the file "Words.txt" in the same folder as the program.)
- Code: Select all
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using std::string;
class hangman
{
public:
hangman(); // prompt names.
void readWords(); //read words from a txt file and store them into a vector.
void setWord();// sets a random word from the vector
void promptUser(); // main function, prompts user for characters.
std::string getWord() { return theWord; } // accessor
std::string getWordC() { return theWordC; } // accessor
bool get_status() { return game_over; } // accessor
private:
bool game_over; // Game finished ?
std::string words;
std::vector<string> allWords; // vector to store the words from the .txt
std::ifstream file;
std::string pone; // player one's name
int random;
std::string theWord; // chosen word
std::string theWordC; // The chosen word concealed.
char letter; // letter user has chosen
int tries;
};
int main()
{
bool cont = 1;
srand((unsigned)time(0)); // make sure word is random every time.
hangman game; // create instance of hangman called game.
game.readWords(); // read the words from the text file
game.setWord(); // set a random word
while (cont && !game.get_status())
{
game.promptUser();
}
char f;
std::cin >> f;
return 0;
}
hangman::hangman() : tries(0), game_over(0)
{
std::cout << "Player one, enter your name: ";
std::cin >> pone;
}
void hangman::readWords()
{
file.open("words.txt");
if (!file )
{
std::cout << "Unable to open file";
}
while (file >> words )
{
allWords.push_back(words);
}
file.close();
}
void hangman::setWord()
{
random = (rand()%10)+1; // 1 - 10
for ( int i = 0; i != random; i++)
{
theWord = allWords[random];
}
std::string temp(theWord.size(), '_');
theWordC = temp;
}
void hangman::promptUser()
{
const time_t elapsed = clock()/CLOCKS_PER_SEC;
std::cout << "TRIES: " << tries << "\t" << "TIME ELAPSED: " << clock()/CLOCKS_PER_SEC << std::endl;
std::cout << "WORD SO FAR: " << theWordC << std::endl;
if ( clock()/CLOCKS_PER_SEC >= 50 || tries == 30 )
{
std::cout << "Game over :(" << std::endl;
game_over = 1;
}
std::cout << pone << ", guess a letter: ";
std::cin >> letter;
if ( letter != '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' )
{
std::cout << "wrong input, please try again." << std::endl;
}
tries++;
for ( int i = 0; i != theWord.size(); i++ )
{
if ( letter == theWord[i] )
{
theWordC[i] = letter;
}
}
if (theWordC == theWord)
{
std::cout << "Congratulations !, you win the word was: " << getWord() << std::endl;
game_over = 1;
}
}
