HangmanWidget.C 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright (C) 2011 Emweb bvba, Heverlee, Belgium
  3. *
  4. * See the LICENSE file for terms of use.
  5. */
  6. #include "HangmanWidget.h"
  7. #include <Wt/WBreak>
  8. #include <Wt/WComboBox>
  9. #include <Wt/WPushButton>
  10. #include <Wt/WText>
  11. #include <boost/lexical_cast.hpp>
  12. #include "Session.h"
  13. #include "Dictionary.h"
  14. #include "WordWidget.h"
  15. #include "ImagesWidget.h"
  16. #include "LettersWidget.h"
  17. using namespace Wt;
  18. namespace {
  19. const int MaxGuesses = 9;
  20. }
  21. HangmanWidget::HangmanWidget(const std::string &name, WContainerWidget *parent)
  22. : WContainerWidget(parent),
  23. name_(name),
  24. badGuesses_(0)
  25. {
  26. setContentAlignment(AlignCenter);
  27. title_ = new WText(tr("hangman.readyToPlay"), this);
  28. word_ = new WordWidget(this);
  29. statusText_ = new WText(this);
  30. images_ = new ImagesWidget(MaxGuesses, this);
  31. letters_ = new LettersWidget(this);
  32. letters_->letterPushed().connect(this, &HangmanWidget::registerGuess);
  33. language_ = new WComboBox(this);
  34. language_->addItem(tr("hangman.englishWords").arg(18957));
  35. language_->addItem(tr("hangman.dutchWords").arg(1688));
  36. new WBreak(this);
  37. newGameButton_ = new WPushButton(tr("hangman.newGame"), this);
  38. newGameButton_->clicked().connect(this, &HangmanWidget::newGame);
  39. letters_->hide();
  40. }
  41. void HangmanWidget::newGame()
  42. {
  43. WString title(tr("hangman.guessTheWord"));
  44. title_->setText(title.arg(name_));
  45. language_->hide();
  46. newGameButton_->hide();
  47. /*
  48. * Choose a new secret word and reset the game
  49. */
  50. Dictionary dictionary = (Dictionary) language_->currentIndex();
  51. word_->init(RandomWord(dictionary));
  52. letters_->reset();
  53. badGuesses_ = 0;
  54. images_->showImage(badGuesses_);
  55. statusText_->setText("");
  56. }
  57. void HangmanWidget::registerGuess(char c)
  58. {
  59. if (badGuesses_ < MaxGuesses) {
  60. bool correct = word_->guess(c);
  61. if (!correct) {
  62. ++badGuesses_;
  63. images_->showImage(badGuesses_);
  64. }
  65. }
  66. if (badGuesses_ == MaxGuesses) {
  67. WString status(tr("hangman.youHang"));
  68. statusText_->setText(status.arg(word_->word()));
  69. letters_->hide();
  70. language_->show();
  71. newGameButton_->show();
  72. scoreUpdated_.emit(-10);
  73. } else if (word_->won()) {
  74. statusText_->setText(tr("hangman.youWin"));
  75. images_->showImage(ImagesWidget::HURRAY);
  76. letters_->hide();
  77. language_->show();
  78. newGameButton_->show();
  79. scoreUpdated_.emit(20 - badGuesses_);
  80. }
  81. }