die.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. struct die {
  19. sign sgn;
  20. int num, sides;
  21. };
  22. struct mod {
  23. operator int() const;
  24. sign sign;
  25. int value;
  26. };
  27. /**
  28. * In some cases, the roller is not interested in the actual value of the dice
  29. * rolled, but only if they pass some metric.
  30. * This object allows us to perform that check, and then conveniently obfuscate
  31. * the numbers rolled so that the player cannot intuit their odds of success in
  32. * the short term.
  33. */
  34. struct difficulty_class {
  35. enum class test { None, Less, LessOrEqual, Greater, GreaterOrEqual };
  36. bool operator()(int value) const;
  37. test comp{test::None};
  38. int against{0};
  39. };
  40. // Default value: 1{+0}
  41. struct dice {
  42. int num{1};
  43. std::vector<die> of{};
  44. std::vector<mod> modifier{+0};
  45. difficulty_class dc{};
  46. };
  47. /**
  48. * @brief A generator function to turn a string representation of a dice roll
  49. * into a C++ object
  50. * @param strdice A string representation of a dice roll, represented as one of
  51. * the following expression classes: Die = [1-9]?\d*d[1-9]\d* SingleRoll:
  52. * ($Die|\d+)((+|-)($Die|\d+))* RepeatRoll: [1-9]\d*\{$SingleRoll\}
  53. * @return a dice object representing the roll
  54. * @throws dice::unexpected_token if a parse failure occurs
  55. */
  56. dice from_string(std::string const & strdice);
  57. std::ostream & operator<<(std::ostream & out, sign s);
  58. std::ostream & operator<<(std::ostream & out, dice const & d);
  59. std::istream & operator>>(std::istream & out, dice & d);
  60. }