hangman.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // hangman.cpp -- some string methods
  2. #include <iostream>
  3. #include <string>
  4. #include <cstdlib>
  5. #include <ctime>
  6. #include <cctype>
  7. using std::string;
  8. const int NUM = 26;
  9. const string wordlist[NUM] = {"apiary", "beetle", "cereal",
  10. "danger", "ensign", "florid", "garage", "health", "insult",
  11. "jackal", "keeper", "loaner", "manage", "nonce", "onset",
  12. "plaid", "quilt", "remote", "stolid", "train", "useful",
  13. "valid", "whence", "xenon", "yearn", "zippy"};
  14. int main()
  15. {
  16. using std::cout;
  17. using std::cin;
  18. using std::tolower;
  19. using std::endl;
  20. std::srand(std::time(0));
  21. char play;
  22. cout << "Will you play a word game? <y/n> ";
  23. cin >> play;
  24. play = tolower(play);
  25. while (play == 'y')
  26. {
  27. string target = wordlist[std::rand() % NUM];
  28. int length = target.length();
  29. string attempt(length, '-');
  30. string badchars;
  31. int guesses = 6;
  32. cout << "Guess my secret word. It has " << length
  33. << " letters, and you guess\n"
  34. << "one letter at a time. You get " << guesses
  35. << " wrong guesses.\n";
  36. cout << "Your word: " << attempt << endl;
  37. while (guesses > 0 && attempt != target)
  38. {
  39. char letter;
  40. cout << "Guess a letter: ";
  41. cin >> letter;
  42. if (badchars.find(letter) != string::npos
  43. || attempt.find(letter) != string::npos)
  44. {
  45. cout << "You already guessed that. Try again.\n";
  46. continue;
  47. }
  48. int loc = target.find(letter);
  49. if (loc == string::npos)
  50. {
  51. cout << "Oh, bad guess!\n";
  52. --guesses;
  53. badchars += letter; // add to string
  54. }
  55. else
  56. {
  57. cout << "Good guess!\n";
  58. attempt[loc]=letter;
  59. // check if letter appears again
  60. loc = target.find(letter, loc + 1);
  61. while (loc != string::npos)
  62. {
  63. attempt[loc]=letter;
  64. loc = target.find(letter, loc + 1);
  65. }
  66. }
  67. cout << "Your word: " << attempt << endl;
  68. if (attempt != target)
  69. {
  70. if (badchars.length() > 0)
  71. cout << "Bad choices: " << badchars << endl;
  72. cout << guesses << " bad guesses left\n";
  73. }
  74. }
  75. if (guesses > 0)
  76. cout << "That's right!\n";
  77. else
  78. cout << "Sorry, the word is " << target << ".\n";
  79. cout << "Will you play another? <y/n> ";
  80. cin >> play;
  81. play = tolower(play);
  82. }
  83. cout << "Bye\n";
  84. return 0;
  85. }