main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. #include "door.h"
  2. #include "yaml-cpp/yaml.h"
  3. #include <chrono> // chrono::system_clock
  4. #include <ctime> // localtime
  5. #include <iomanip> // put_time
  6. #include <iostream>
  7. #include <random>
  8. #include <string>
  9. #include "db.h"
  10. #include "deck.h"
  11. #include "play.h"
  12. #include "utils.h"
  13. #include "version.h"
  14. #include <algorithm> // transform
  15. // configuration here -- access via extern
  16. YAML::Node config;
  17. door::ANSIColor stringToANSIColor(std::string colorCode);
  18. std::function<std::ofstream &(void)> get_logger;
  19. std::function<void(void)> cls_display_starfield;
  20. /**
  21. * @brief Make renderFunction that colors status: value
  22. *
  23. * "status:" text is status color, the rest is value color.
  24. *
  25. * If ":" is not located in the string, text is displayed in status
  26. * color, digits are displayed in value color.
  27. *
  28. * @param status
  29. * @param value
  30. * @return door::renderFunction
  31. */
  32. door::renderFunction statusValue(door::ANSIColor status,
  33. door::ANSIColor value) {
  34. door::renderFunction rf = [status,
  35. value](const std::string &txt) -> door::Render {
  36. door::Render r(txt);
  37. door::ColorOutput co;
  38. co.pos = 0;
  39. co.len = 0;
  40. co.c = status;
  41. size_t pos = txt.find(':');
  42. if (pos == std::string::npos) {
  43. // failed to find :, render digits/numbers in value color
  44. int tpos = 0;
  45. for (char const &c : txt) {
  46. if (std::isdigit(c)) {
  47. if (co.c != value) {
  48. r.outputs.push_back(co);
  49. co.reset();
  50. co.pos = tpos;
  51. co.c = value;
  52. }
  53. } else {
  54. if (co.c != status) {
  55. r.outputs.push_back(co);
  56. co.reset();
  57. co.pos = tpos;
  58. co.c = status;
  59. }
  60. }
  61. co.len++;
  62. tpos++;
  63. }
  64. if (co.len != 0)
  65. r.outputs.push_back(co);
  66. } else {
  67. pos++; // Have : in status color
  68. co.len = pos;
  69. r.outputs.push_back(co);
  70. co.reset();
  71. co.pos = pos;
  72. co.c = value;
  73. co.len = txt.length() - pos;
  74. r.outputs.push_back(co);
  75. }
  76. return r;
  77. };
  78. return rf;
  79. }
  80. std::string return_current_time_and_date() {
  81. auto now = std::chrono::system_clock::now();
  82. auto in_time_t = std::chrono::system_clock::to_time_t(now);
  83. std::stringstream ss;
  84. // ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
  85. ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %r");
  86. return ss.str();
  87. }
  88. int press_a_key(door::Door &door) {
  89. door << door::reset << "Press a key to continue...";
  90. int r = door.sleep_key(door.inactivity);
  91. door << door::nl;
  92. return r;
  93. }
  94. // This does not seem to be working. I keep getting zero.
  95. int opt_from_string(std::string colorCode) {
  96. for (std::size_t pos = 0; pos != deck_colors.size(); ++pos) {
  97. // if (caseInsensitiveStringCompare(colorCode, deck_colors[pos]) == 0) {
  98. if (iequals(colorCode, deck_colors[pos])) {
  99. return pos;
  100. }
  101. }
  102. return 0;
  103. }
  104. int configure(door::Door &door, DBData &db) {
  105. auto menu = make_config_menu();
  106. int r = 0;
  107. bool save_deckcolor = false;
  108. const char *deckcolor = "DeckColor";
  109. std::string newColor;
  110. while (r >= 0) {
  111. if (save_deckcolor) {
  112. door << menu;
  113. db.setSetting(deckcolor, newColor);
  114. save_deckcolor = false;
  115. }
  116. if (cls_display_starfield)
  117. cls_display_starfield();
  118. else
  119. door << door::reset << door::cls;
  120. r = menu.choose(door);
  121. if (r > 0) {
  122. door << door::reset << door::cls;
  123. char c = menu.which(r - 1);
  124. if (c == 'D') {
  125. // Ok, deck colors
  126. // get default
  127. std::string currentDefault = db.getSetting(deckcolor, "ALL");
  128. int currentOpt = opt_from_string(currentDefault);
  129. door << door::reset << door::cls;
  130. auto deck = make_deck_menu();
  131. deck.defaultSelection(currentOpt);
  132. if (cls_display_starfield)
  133. cls_display_starfield();
  134. else
  135. door << door::reset << door::cls;
  136. int newOpt = deck.choose(door);
  137. door << door::reset << door::cls;
  138. if (newOpt >= 0) {
  139. newOpt--;
  140. newColor = stringFromColorOptions(newOpt);
  141. if (newOpt != currentOpt) {
  142. door.log() << deckcolor << " was " << currentDefault << ", "
  143. << currentOpt << ". Now " << newColor << ", " << newOpt
  144. << std::endl;
  145. save_deckcolor = true;
  146. }
  147. }
  148. }
  149. if (c == 'V') {
  150. // view settings -- Sysop Configuration
  151. if (cls_display_starfield)
  152. cls_display_starfield();
  153. else
  154. door << door::reset << door::cls;
  155. door << door::Goto(1, 1);
  156. door << door::ANSIColor(door::COLOR::CYAN, door::COLOR::BLACK)
  157. << "Game Settings - SysOp Configurable" << door::reset << door::nl
  158. << door::nl;
  159. for (auto cfg : config) {
  160. std::string key = cfg.first.as<std::string>();
  161. if (key[0] == '_')
  162. continue;
  163. // TODO: replace _ with ' ' in string.
  164. while (replace(key, "_", " ")) {
  165. };
  166. std::string value = cfg.second.as<std::string>();
  167. door << door::ANSIColor(door::COLOR::CYAN, door::COLOR::BLACK,
  168. door::ATTR::BOLD)
  169. << std::setw(20) << key
  170. << door::ANSIColor(door::COLOR::YELLOW, door::COLOR::BLACK,
  171. door::ATTR::BOLD)
  172. << " : "
  173. << door::ANSIColor(door::COLOR::CYAN, door::COLOR::BLACK,
  174. door::ATTR::BOLD)
  175. << value << door::reset << door::nl;
  176. }
  177. r = press_a_key(door);
  178. if (r < 0)
  179. return r;
  180. door << door::reset << door::cls;
  181. }
  182. if (c == 'Q') {
  183. return r;
  184. }
  185. }
  186. }
  187. return r;
  188. }
  189. /*
  190. door::Panel make_score_panel(door::Door &door) {
  191. const int W = 25;
  192. door::Panel p(W);
  193. p.setStyle(door::BorderStyle::NONE);
  194. door::ANSIColor statusColor(door::COLOR::WHITE, door::COLOR::BLUE,
  195. door::ATTR::BOLD);
  196. door::ANSIColor valueColor(door::COLOR::YELLOW, door::COLOR::BLUE,
  197. door::ATTR::BOLD);
  198. door::renderFunction svRender = statusValue(statusColor, valueColor);
  199. // or use renderStatus as defined above.
  200. // We'll stick with these for now.
  201. {
  202. std::string userString = "Name: ";
  203. userString += door.username;
  204. door::Line username(userString, W);
  205. username.setRender(svRender);
  206. p.addLine(std::make_unique<door::Line>(username));
  207. }
  208. {
  209. door::updateFunction scoreUpdate = [](void) -> std::string {
  210. std::string text = "Score: ";
  211. text.append(std::to_string(score));
  212. return text;
  213. };
  214. std::string scoreString = scoreUpdate();
  215. door::Line score(scoreString, W);
  216. score.setRender(svRender);
  217. score.setUpdater(scoreUpdate);
  218. p.addLine(std::make_unique<door::Line>(score));
  219. }
  220. {
  221. door::updateFunction timeUpdate = [&door](void) -> std::string {
  222. std::stringstream ss;
  223. std::string text;
  224. ss << "Time used: " << setw(3) << door.time_used << " / " << setw(3)
  225. << door.time_left;
  226. text = ss.str();
  227. return text;
  228. };
  229. std::string timeString = timeUpdate();
  230. door::Line time(timeString, W);
  231. time.setRender(svRender);
  232. time.setUpdater(timeUpdate);
  233. p.addLine(std::make_unique<door::Line>(time));
  234. }
  235. {
  236. door::updateFunction handUpdate = [](void) -> std::string {
  237. std::string text = "Playing Hand ";
  238. text.append(std::to_string(hand));
  239. text.append(" of ");
  240. text.append(std::to_string(total_hands));
  241. return text;
  242. };
  243. std::string handString = handUpdate();
  244. door::Line hands(handString, W);
  245. hands.setRender(svRender);
  246. hands.setUpdater(handUpdate);
  247. p.addLine(std::make_unique<door::Line>(hands));
  248. }
  249. return p;
  250. }
  251. */
  252. int main(int argc, char *argv[]) {
  253. door::Door door("space-ace", argc, argv);
  254. // store the door log so we can easily access it.
  255. get_logger = [&door]() -> ofstream & { return door.log(); };
  256. std::random_device rd;
  257. std::mt19937 rng(rd());
  258. cls_display_starfield = [&door, &rng]() -> void {
  259. display_starfield(door, rng);
  260. };
  261. DBData spacedb;
  262. spacedb.setUser(door.username);
  263. if (file_exists("space-ace.yaml")) {
  264. config = YAML::LoadFile("space-ace.yaml");
  265. }
  266. bool update_config = false;
  267. // populate with "good" defaults
  268. if (!config["hands_per_day"]) {
  269. config["hands_per_day"] = 3;
  270. update_config = true;
  271. }
  272. if (!config["date_format"]) {
  273. config["date_format"] = "%B %d"; // Month day or "%b %d,%Y" Mon,d YYYY
  274. update_config = true;
  275. }
  276. if (!config["date_score"]) {
  277. config["date_score"] = "%m/%d/%Y"; // or "%Y/%0m/%0d";
  278. update_config = true;
  279. }
  280. if (!config["makeup_per_day"]) {
  281. config["makeup_per_day"] = 5;
  282. update_config = true;
  283. }
  284. if (!config["play_days_ahead"]) {
  285. config["play_days_ahead"] = 2;
  286. update_config = true;
  287. }
  288. if (!config["date_monthly"]) {
  289. config["date_monthly"] = "%B %Y";
  290. update_config = true;
  291. }
  292. /*
  293. if (config["hands_per_day"]) {
  294. get_logger() << "hands_per_day: " << config["hands_per_day"].as<int>()
  295. << std::endl;
  296. }
  297. */
  298. // save configuration -- something was updated
  299. if (update_config) {
  300. std::ofstream fout("space-ace.yaml");
  301. fout << config << std::endl;
  302. }
  303. // retrieve lastcall
  304. time_t last_call = std::stol(spacedb.getSetting("LastCall", "0"));
  305. std::chrono::_V2::system_clock::time_point now =
  306. std::chrono::system_clock::now();
  307. // store now as lastcall
  308. time_t now_t = std::chrono::system_clock::to_time_t(now);
  309. spacedb.setSetting("LastCall", std::to_string(now_t));
  310. // run maint
  311. {
  312. std::chrono::_V2::system_clock::time_point maint_date = now;
  313. firstOfMonthDate(maint_date);
  314. spacedb.expireScores(std::chrono::system_clock::to_time_t(maint_date));
  315. }
  316. // Have they used this door before?
  317. if (last_call != 0) {
  318. door << "Welcome Back!" << door::nl;
  319. auto nowClock = std::chrono::system_clock::from_time_t(now_t);
  320. auto lastClock = std::chrono::system_clock::from_time_t(last_call);
  321. auto delta = nowClock - lastClock;
  322. // int days = chrono::duration_cast<chrono::days>(delta).count(); //
  323. // c++ 20
  324. int hours = chrono::duration_cast<chrono::hours>(delta).count();
  325. int days = hours / 24;
  326. int minutes = chrono::duration_cast<chrono::minutes>(delta).count();
  327. int secs = chrono::duration_cast<chrono::seconds>(delta).count();
  328. if (days > 1) {
  329. door << "It's been " << days << " days since you last played."
  330. << door::nl;
  331. } else {
  332. if (hours > 1) {
  333. door << "It's been " << hours << " hours since you last played."
  334. << door::nl;
  335. } else {
  336. if (minutes > 1) {
  337. door << "It's been " << minutes << " minutes since you last played."
  338. << door::nl;
  339. } else {
  340. door << "It's been " << secs << " seconds since you last played."
  341. << door::nl;
  342. door << "It's like you never left." << door::nl;
  343. }
  344. }
  345. }
  346. press_a_key(door);
  347. }
  348. /*
  349. // example: saving the door.log() for global use.
  350. std::function<std::ofstream &(void)> get_logger;
  351. get_logger = [&door]() -> ofstream & { return door.log(); };
  352. if (get_logger) {
  353. get_logger() << "MEOW" << std::endl;
  354. get_logger() << "hey! It works!" << std::endl;
  355. }
  356. get_logger = nullptr; // before door destruction
  357. */
  358. // https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
  359. // random-number engine used (Mersenne-Twister in this case)
  360. // std::uniform_int_distribution<int> uni(min, max); // guaranteed
  361. // unbiased
  362. int mx, my; // Max screen width/height
  363. if (door.width == 0) {
  364. // screen detect failed, use sensible defaults
  365. door.width = mx = 80;
  366. door.height = my = 23;
  367. } else {
  368. mx = door.width;
  369. my = door.height;
  370. }
  371. // We assume here that the width and height aren't something crazy like
  372. // 10x15. :P (or 24x923!)
  373. display_starfield_space_ace(door, rng);
  374. // for testing inactivity timeout
  375. // door.inactivity = 10;
  376. door::Panel timeout = make_timeout(mx, my);
  377. door::Menu m = make_main_menu();
  378. door::Panel about = make_about(); // 8 lines
  379. // center the about box
  380. about.set((mx - 60) / 2, (my - 9) / 2);
  381. int r = 0;
  382. while ((r >= 0) and (r != 6)) {
  383. // starfield + menu ?
  384. display_starfield(door, rng);
  385. r = m.choose(door);
  386. // need to reset the colors. (whoops!)
  387. door << door::reset << door::cls; // door::nl;
  388. // OK! The screen is blank at this point!
  389. switch (r) {
  390. case 1: // play game
  391. {
  392. PlayCards pc(door, spacedb, rng);
  393. r = pc.play();
  394. // r = play_cards(door, spacedb, rng);
  395. }; break;
  396. case 2: // view scores
  397. {
  398. // door << door::cls;
  399. display_starfield(door, rng);
  400. door << door::Goto(1, 2);
  401. auto monthly_scores = spacedb.getMonthlyScores(10);
  402. if (!monthly_scores.empty()) {
  403. door << "The TOP monthly Scores:" << door::nl;
  404. }
  405. for (auto it : monthly_scores) {
  406. time_t date = it.date;
  407. std::string nice_date = convertDateToMonthlyFormat(date);
  408. door << nice_date << " " << std::setw(18) << it.user << " " << it.score
  409. << door::nl;
  410. }
  411. door << door::nl;
  412. // I probably want JUST the top 10 here!
  413. auto all_scores = spacedb.getScores();
  414. if (!all_scores.empty()) {
  415. door << "The Top Scores for this Month:" << door::nl;
  416. }
  417. for (auto it : all_scores) {
  418. std::string nice_date = convertDateToDateScoreFormat(it.date);
  419. door << " *** " << nice_date << setw(15) << it.user << " " << it.won
  420. << " " << it.score << door::nl;
  421. }
  422. door << "====================" << door::nl;
  423. }
  424. r = press_a_key(door);
  425. break;
  426. case 3: // configure
  427. r = configure(door, spacedb);
  428. // r = press_a_key(door);
  429. break;
  430. case 4: // help
  431. door << "Help! Need some help here..." << door::nl;
  432. r = press_a_key(door);
  433. break;
  434. case 5: // about
  435. display_starfield(door, rng);
  436. door << about << door::nl;
  437. r = press_a_key(door);
  438. break;
  439. case 6: // quit
  440. break;
  441. }
  442. }
  443. if (r < 0) {
  444. // TIMEOUT:
  445. if (r == -1) {
  446. door.log() << "TIMEOUT" << std::endl;
  447. door << timeout << door::reset << door::nl << door::nl;
  448. } else {
  449. if (r == -3) {
  450. door.log() << "OUTTA TIME" << std::endl;
  451. door::Panel notime = make_notime(mx, my);
  452. door << notime << door::reset << door::nl;
  453. }
  454. }
  455. return 0;
  456. }
  457. door << door::nl;
  458. // door << door::reset << door::cls;
  459. display_starfield(door, rng);
  460. door << m << door::reset << door::nl;
  461. // Normal DOOR exit goes here...
  462. door << door::nl << "Returning you to the BBS, please wait..." << door::nl;
  463. get_logger = nullptr;
  464. cls_display_starfield = nullptr;
  465. return 0;
  466. }