die.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 <memory>
  11. #include <vector>
  12. namespace dice {
  13. enum 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. // Default value: 1{+0}
  29. struct dice {
  30. int num{1};
  31. std::vector<die> of{};
  32. std::vector<mod> modifier{+0};
  33. };
  34. /**
  35. * @brief A generator function to turn a string representation of a dice roll into a C++ object
  36. * @param strdice A string representation of a dice roll, represented as one of the
  37. * following expression classes:
  38. * Die = [1-9]?\d*d[1-9]\d*
  39. * SingleRoll: ($Die|\d+)((+|-)($Die|\d+))*
  40. * RepeatRoll: [1-9]\d*\{$SingleRoll\}
  41. * @return a dice object representing the roll
  42. * @throws dice::unexpected_token if a parse failure occurs
  43. */
  44. dice from_string(std::string const & strdice);
  45. std::ostream & operator<<(std::ostream & out, dice const & d);
  46. std::istream & operator>>(std::istream & out, dice & d);
  47. }