die.h 1.2 KB

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