Space Walk board game
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

89 lines
1.8 KiB

  1. #include <cstring> // strlen
  2. #include <sstream> // istringstream
  3. #include "inputoutput.h"
  4. #include "selectionbox.h"
  5. SelectionBox::SelectionBox(int height, int width) :
  6. height(height),
  7. width(width) {
  8. this->update();
  9. }
  10. void SelectionBox::update() {
  11. Window::update();
  12. this->resize();
  13. }
  14. void SelectionBox::resize() {
  15. int rows = (this->getMaxRows() - this->height) / 4;
  16. int cols = this->getMaxCols() - this->width;
  17. this->setWindow(rows, cols, this->getMaxRows() - rows, 0);
  18. Window::resize();
  19. }
  20. unsigned char SelectionBox::select(std::string str, std::string *selection) {
  21. int amount = 0;
  22. while (!selection[amount].empty()) {
  23. amount++;
  24. }
  25. std::string tmpStr;
  26. int tmpInt;
  27. // Display options and get user input
  28. while(!IO::getQuit()) {
  29. this->clear();
  30. this->update();
  31. this->printSelection(str, selection);
  32. this->render();
  33. tmpStr = IO::trim(this->getStr());
  34. if (tmpStr == "") {
  35. continue;
  36. }
  37. if (this->isNumber(tmpStr)) {
  38. tmpInt = std::stoi(tmpStr);
  39. if (tmpInt > 0 && tmpInt < amount + 1) {
  40. break;
  41. }
  42. }
  43. }
  44. return (unsigned char)tmpInt - 1;
  45. }
  46. void SelectionBox::printSelection(std::string str, std::string *selection) {
  47. int y = 0;
  48. // Split and print message on newline
  49. std::istringstream strStream(str);
  50. std::string tmpStr;
  51. while (std::getline(strStream, tmpStr, '\n')) {
  52. this->print(tmpStr, y, 1);
  53. y++;
  54. }
  55. y++;
  56. int amount = 0;
  57. while (!selection[amount].empty()) {
  58. if (amount < 6) {
  59. this->print("- " + selection[amount], y, 1);
  60. }
  61. else {
  62. this->print("- " + selection[amount], y - 6, 10);
  63. }
  64. y++;
  65. amount++;
  66. }
  67. this->print("Select option number: ", this->getRows() - 3, 1);
  68. }
  69. bool SelectionBox::isNumber(const std::string &s) {
  70. std::string::const_iterator it = s.begin();
  71. while (it != s.end() && std::isdigit(*it)) it++;
  72. return !s.empty() && it == s.end();
  73. }