die.h 1.8 KB

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