|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <ctime> |
| 4 | +#include <cstdlib> |
| 5 | +using namespace std; |
| 6 | +void display(const string &word, const vector<bool> &guessed) { |
| 7 | + for (size_t i = 0; i < word.size(); ++i) { |
| 8 | + if (guessed[i]) { |
| 9 | + cout << word[i]; |
| 10 | + } |
| 11 | + else { |
| 12 | + cout << " _"; |
| 13 | + } |
| 14 | + } |
| 15 | + cout << endl; |
| 16 | +} |
| 17 | +bool wordguess(const vector<bool> &guessed) { |
| 18 | + for (bool b : guessed) { |
| 19 | + if (!b) { |
| 20 | + return false; |
| 21 | + } |
| 22 | + } |
| 23 | + return true; |
| 24 | +} |
| 25 | +int main() { |
| 26 | + vector<string> words = { "om", "kanisha", "aditi", "harsh"}; |
| 27 | + srand(static_cast<unsigned int>(time(0))); |
| 28 | + string word = words[rand() % words.size()]; |
| 29 | + vector<bool> guessed(word.size(), false); |
| 30 | + int remainingAttempts = 6; |
| 31 | + cout << "Welcome to Hangman!" << endl; |
| 32 | + while (remainingAttempts > 0 && !wordguess(guessed)) { |
| 33 | + cout << "Current word: "; |
| 34 | + display(word, guessed); |
| 35 | + cout << "Remaining attempts: " << remainingAttempts << endl; |
| 36 | + cout << "Enter a letter: "; |
| 37 | + char guess; |
| 38 | + cin >> guess; |
| 39 | + bool correctguess = false; |
| 40 | + for(size_t i = 0; i < word.size(); ++i) { |
| 41 | + if (word[i] == guess && !guessed[i]) { |
| 42 | + guessed[i] = true; |
| 43 | + correctguess = true; |
| 44 | + } |
| 45 | + } |
| 46 | + if(!correctguess) { |
| 47 | + --remainingAttempts; |
| 48 | + cout << "Incorrect guess!" << endl; |
| 49 | + } |
| 50 | + else { |
| 51 | + cout << "Correct guess!" << endl; |
| 52 | + } |
| 53 | + } |
| 54 | + if(wordguess(guessed)) { |
| 55 | + cout << "Congratulations! You've guessed the word: " << word << endl; |
| 56 | + } |
| 57 | + else { |
| 58 | + cout << "Sorry, you've run out of attempts. The word was: " << word << endl; |
| 59 | + } |
| 60 | + return 0; |
| 61 | +} |
0 commit comments