main.cxx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. auto roll = std::to_string(r.roll);
  42. std::string strikethrough = "\u0336";
  43. for (size_t i = 1; i <= roll.size() && r.dropped;
  44. i += 1 + strikethrough.length()) {
  45. roll.insert(i, strikethrough);
  46. }
  47. window.printf("%s", roll.c_str());
  48. }
  49. return window;
  50. }
  51. }
  52. void eval(curses::Window & window, std::string line) try {
  53. using ::dice::operator<<;
  54. dice::dice const d = dice::from_string(line);
  55. std::vector<dice::dice_roll> const rs = dice::roller()(d);
  56. window << std::make_pair(d, rs) << '\n';
  57. } catch (dice::unexpected_token const & ut) {
  58. window.printf("Error in roll: '%s': %s\n %s\n", line.c_str(),
  59. ut.what(), ut.pointer(line.size() + 1).c_str());
  60. }
  61. int main(int, const char **) {
  62. Cli("> ", WithColor).loop(&eval);
  63. return 0;
  64. }