die.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // die.hpp
  3. // dice-roll
  4. //
  5. // Created by Sam Jaffe on 12/1/18.
  6. // Copyright © 2018 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <iosfwd>
  10. #include <string>
  11. #include <vector>
  12. namespace dice {
  13. enum class sign { PLUS = 1, MINUS = -1, ZERO = 0 };
  14. template <typename T> static sign sgn(T val) {
  15. return sign((T(0) < val) - (val < T(0)));
  16. }
  17. int sgn(sign);
  18. std::string str(sign);
  19. struct die {
  20. sign sgn;
  21. int num, sides;
  22. };
  23. struct mod {
  24. operator int() const;
  25. sign sign;
  26. int value;
  27. };
  28. /**
  29. * In some cases, the roller is not interested in the actual value of the dice
  30. * rolled, but only if they pass some metric.
  31. * This object allows us to perform that check, and then conveniently obfuscate
  32. * the numbers rolled so that the player cannot intuit their odds of success in
  33. * the short term.
  34. */
  35. struct difficulty_class {
  36. enum class test { None, Less, LessOrEqual, Greater, GreaterOrEqual };
  37. bool operator()(int value) const;
  38. test comp{test::None};
  39. int against{0};
  40. };
  41. // Default value: 1{+0}
  42. struct dice {
  43. int num{1};
  44. std::vector<die> of{};
  45. std::vector<mod> modifier{+0};
  46. difficulty_class dc{};
  47. };
  48. /**
  49. * @brief A generator function to turn a string representation of a dice roll into a C++ object
  50. * @param strdice A string representation of a dice roll, represented as one of the
  51. * following expression classes:
  52. * Die = [1-9]?\d*d[1-9]\d*
  53. * SingleRoll: ($Die|\d+)((+|-)($Die|\d+))*
  54. * RepeatRoll: [1-9]\d*\{$SingleRoll\}
  55. * @return a dice object representing the roll
  56. * @throws dice::unexpected_token if a parse failure occurs
  57. */
  58. dice from_string(std::string const & strdice);
  59. std::ostream & operator<<(std::ostream & out, dice const & d);
  60. std::istream & operator>>(std::istream & out, dice & d);
  61. }