main.cxx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // main.cxx
  3. // curses_dice
  4. //
  5. // Created by Sam Jaffe on 7/23/24.
  6. // Copyright © 2024 Sam Jaffe. All rights reserved.
  7. //
  8. #include <sstream>
  9. #include <ncurses-wrapper/cli.h>
  10. #include <ncurses-wrapper/color.h>
  11. #include <ncurses-wrapper/window.h>
  12. #include "dice-roll/die.h"
  13. #include "dice-roll/exception.h"
  14. #include "dice-roll/io.h"
  15. #include "dice-roll/roll.h"
  16. using namespace curses;
  17. ColorPair color(bool good, bool bad) {
  18. if (good) {
  19. return ColorPair{Color::GREEN, Color::DEFAULT};
  20. } else if (bad) {
  21. return ColorPair{Color::RED, Color::DEFAULT};
  22. } else {
  23. return ColorPair{Color::DEFAULT, Color::DEFAULT};
  24. }
  25. }
  26. ColorPair color(bool good) { return color(good, !good); }
  27. void print(curses::Window & window, int roll, int sides) {
  28. if (auto scope = window.with(color(roll == sides, roll == 1))) {
  29. window.printf("%d", roll);
  30. }
  31. }
  32. namespace dice {
  33. curses::Window & operator<<(curses::Window & window, outcome o) {
  34. if (auto scope = window.with(color(o == outcome::PASS))) {
  35. window.printf("%s", o == outcome::PASS ? "PASS" : "FAIL");
  36. }
  37. return window;
  38. }
  39. curses::Window & operator<<(curses::Window & window, die_outcome const & r) {
  40. if (auto scope = window.with(color(r.roll == r.sides, r.roll == 1))) {
  41. window.printf("%d", r.roll);
  42. }
  43. return window;
  44. }
  45. }
  46. void eval(curses::Window & window, std::string line) try {
  47. using ::dice::operator<<;
  48. dice::dice const d = dice::from_string(line);
  49. std::vector<dice::dice_roll> const rs = dice::roller()(d);
  50. window << std::make_pair(d, rs) << '\n';
  51. } catch (dice::unexpected_token const & ut) {
  52. window.printf("Error in roll: '%s': %s\n %s\n", line.c_str(),
  53. ut.what(), ut.pointer(line.size() + 1).c_str());
  54. }
  55. int main(int, const char **) {
  56. Cli("> ", WithColor).loop(&eval);
  57. return 0;
  58. }