main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. /*
  20. unsigned long score = 0;
  21. int hand = 1;
  22. int total_hands = 3;
  23. int card_number = 28;
  24. int current_streak = 0;
  25. int best_streak = 0;
  26. int active_card = 23;
  27. std::chrono::_V2::system_clock::time_point play_day;
  28. */
  29. /*
  30. Cards:
  31. 4 layers deep.
  32. https://en.wikipedia.org/wiki/Code_page_437
  33. using: \xb0, 0xb1, 0xb2, 0xdb
  34. OR: \u2591, \u2592, \u2593, \u2588
  35. Like so:
  36. ##### #####
  37. ##### #####
  38. ##### #####
  39. Cards: (Black on White, or Red on White)
  40. 8D### TH###
  41. ##D## ##H##
  42. ###D8 ###HT
  43. D, H = Red, Clubs, Spades = Black.
  44. ^ Where D = Diamonds, H = Hearts
  45. ♥, ♦, ♣, ♠
  46. \x03, \x04, \x05, \x06
  47. \u2665, \u2666, \u2663, \u2660
  48. Card layout. Actual cards are 3 lines thick.
  49. ░░░░░ ░░░░░ ░░░░░
  50. ░░░░░ ░░░░░ ░░░░░
  51. ▒▒▒▒▒░▒▒▒▒▒ #####░##### #####░#####
  52. ▒▒▒▒▒ ▒▒▒▒▒ ##### ##### ##### #####
  53. ▓▓▓▓▓▒▓▓▓▓▓▒▓▓▓▓▓ #####=#####=##### #####=#####=#####
  54. ▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓ ##### ##### ##### ##### ##### #####
  55. █████▓█████▓█████▓#####=#####=#####=#####=#####=#####=#####
  56. █████ █████ █████ ##### ##### ##### ##### ##### ##### #####
  57. █████ █████ █████ ##### ##### ##### ##### ##### ##### #####
  58. #####
  59. Player Information ##### Time in: xx Time out: xx
  60. Name: ##### Playing Day: November 3rd
  61. Hand Score : Current Streak: N
  62. Todays Score : XX Cards Remaining Longest Streak: NN
  63. Monthly Score: Playing Hand X of X Most Won: xxx Lost: xxx
  64. [4] Lf [6] Rt [Space] Play Card [Enter] Draw [D]one [H]elp [R]edraw
  65. ►, ◄, ▲, ▼
  66. \x10, \x11, \x1e, \x1f
  67. \u25ba, \u25c4, \u25b2, \u25bc
  68. The Name is <- 6 to the left.
  69. # is back of card. = is upper card showing between.
  70. There's no fancy anything here. Cards overlap the last
  71. line of the previous line/card.
  72. */
  73. door::renderFunction statusValue(door::ANSIColor status,
  74. door::ANSIColor value) {
  75. door::renderFunction rf = [status,
  76. value](const std::string &txt) -> door::Render {
  77. door::Render r(txt);
  78. door::ColorOutput co;
  79. co.pos = 0;
  80. co.len = 0;
  81. co.c = status;
  82. size_t pos = txt.find(':');
  83. if (pos == std::string::npos) {
  84. // failed to find :, render digits/numbers in value color
  85. int tpos = 0;
  86. for (char const &c : txt) {
  87. if (std::isdigit(c)) {
  88. if (co.c != value) {
  89. r.outputs.push_back(co);
  90. co.reset();
  91. co.pos = tpos;
  92. co.c = value;
  93. }
  94. } else {
  95. if (co.c != status) {
  96. r.outputs.push_back(co);
  97. co.reset();
  98. co.pos = tpos;
  99. co.c = status;
  100. }
  101. }
  102. co.len++;
  103. tpos++;
  104. }
  105. if (co.len != 0)
  106. r.outputs.push_back(co);
  107. } else {
  108. pos++; // Have : in status color
  109. co.len = pos;
  110. r.outputs.push_back(co);
  111. co.reset();
  112. co.pos = pos;
  113. co.c = value;
  114. co.len = txt.length() - pos;
  115. r.outputs.push_back(co);
  116. }
  117. return r;
  118. };
  119. return rf;
  120. }
  121. /*
  122. door::renderFunction rStatus = [](const std::string &txt) -> door::Render {
  123. door::Render r(txt);
  124. door::ColorOutput co;
  125. // default colors STATUS: value
  126. door::ANSIColor status(door::COLOR::BLUE, door::ATTR::BOLD);
  127. door::ANSIColor value(door::COLOR::YELLOW, door::ATTR::BOLD);
  128. co.pos = 0;
  129. co.len = 0;
  130. co.c = status;
  131. size_t pos = txt.find(':');
  132. if (pos == std::string::npos) {
  133. // failed to find - use entire string as status color.
  134. co.len = txt.length();
  135. r.outputs.push_back(co);
  136. } else {
  137. pos++; // Have : in status color
  138. co.len = pos;
  139. r.outputs.push_back(co);
  140. co.reset();
  141. co.pos = pos;
  142. co.c = value;
  143. co.len = txt.length() - pos;
  144. r.outputs.push_back(co);
  145. }
  146. return r;
  147. };
  148. */
  149. std::string return_current_time_and_date() {
  150. auto now = std::chrono::system_clock::now();
  151. auto in_time_t = std::chrono::system_clock::to_time_t(now);
  152. std::stringstream ss;
  153. // ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %X");
  154. ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d %r");
  155. return ss.str();
  156. }
  157. int press_a_key(door::Door &door) {
  158. door << door::reset << "Press a key to continue...";
  159. int r = door.sleep_key(door.inactivity);
  160. door << door::nl;
  161. return r;
  162. }
  163. // DOES THIS WORK?
  164. bool iequals(const string &a, const string &b) {
  165. unsigned int sz = a.size();
  166. if (b.size() != sz)
  167. return false;
  168. for (unsigned int i = 0; i < sz; ++i)
  169. if (tolower(a[i]) != tolower(b[i]))
  170. return false;
  171. return true;
  172. }
  173. // This does not seem to be working. I keep getting zero.
  174. int opt_from_string(std::string colorCode) {
  175. for (std::size_t pos = 0; pos != deck_colors.size(); ++pos) {
  176. // if (caseInsensitiveStringCompare(colorCode, deck_colors[pos]) == 0) {
  177. if (iequals(colorCode, deck_colors[pos])) {
  178. return pos;
  179. }
  180. }
  181. return 0;
  182. }
  183. int configure(door::Door &door, DBData &db) {
  184. auto menu = make_config_menu();
  185. int r = 0;
  186. bool save_deckcolor = false;
  187. const char *deckcolor = "DeckColor";
  188. std::string newColor;
  189. while (r >= 0) {
  190. if (save_deckcolor) {
  191. door << menu;
  192. db.setSetting(deckcolor, newColor);
  193. save_deckcolor = false;
  194. }
  195. r = menu.choose(door);
  196. if (r > 0) {
  197. door << door::reset << door::cls;
  198. char c = menu.which(r - 1);
  199. if (c == 'D') {
  200. // Ok, deck colors
  201. // get default
  202. std::string currentDefault = db.getSetting(deckcolor, "ALL");
  203. int currentOpt = opt_from_string(currentDefault);
  204. door << door::reset << door::cls;
  205. auto deck = make_deck_menu();
  206. deck.defaultSelection(currentOpt);
  207. int newOpt = deck.choose(door);
  208. door << door::reset << door::cls;
  209. if (newOpt >= 0) {
  210. newOpt--;
  211. newColor = stringFromColorOptions(newOpt);
  212. if (newOpt != currentOpt) {
  213. door.log() << deckcolor << " was " << currentDefault << ", "
  214. << currentOpt << ". Now " << newColor << ", " << newOpt
  215. << std::endl;
  216. save_deckcolor = true;
  217. }
  218. }
  219. }
  220. if (c == 'V') {
  221. // view settings -- Sysop Configuration
  222. door << door::reset << door::cls;
  223. door << door::ANSIColor(door::COLOR::CYAN, door::COLOR::BLACK)
  224. << "Game Settings - SysOp Configurable" << door::reset << door::nl
  225. << door::nl;
  226. for (auto cfg : config) {
  227. std::string key = cfg.first.as<std::string>();
  228. if (key[0] == '_')
  229. continue;
  230. // TODO: replace _ with ' ' in string.
  231. while (replace(key, "_", " ")) {
  232. };
  233. std::string value = cfg.second.as<std::string>();
  234. door << door::ANSIColor(door::COLOR::CYAN, door::COLOR::BLACK)
  235. << std::setw(20) << key
  236. << door::ANSIColor(door::COLOR::YELLOW, door::COLOR::BLACK,
  237. door::ATTR::BOLD)
  238. << " : "
  239. << door::ANSIColor(door::COLOR::CYAN, door::COLOR::BLACK,
  240. door::ATTR::BOLD)
  241. << value << door::reset << door::nl;
  242. }
  243. r = press_a_key(door);
  244. if (r < 0)
  245. return r;
  246. door << door::reset << door::cls;
  247. }
  248. if (c == 'Q') {
  249. return r;
  250. }
  251. }
  252. }
  253. return r;
  254. }
  255. /*
  256. door::Panel make_score_panel(door::Door &door) {
  257. const int W = 25;
  258. door::Panel p(W);
  259. p.setStyle(door::BorderStyle::NONE);
  260. door::ANSIColor statusColor(door::COLOR::WHITE, door::COLOR::BLUE,
  261. door::ATTR::BOLD);
  262. door::ANSIColor valueColor(door::COLOR::YELLOW, door::COLOR::BLUE,
  263. door::ATTR::BOLD);
  264. door::renderFunction svRender = statusValue(statusColor, valueColor);
  265. // or use renderStatus as defined above.
  266. // We'll stick with these for now.
  267. {
  268. std::string userString = "Name: ";
  269. userString += door.username;
  270. door::Line username(userString, W);
  271. username.setRender(svRender);
  272. p.addLine(std::make_unique<door::Line>(username));
  273. }
  274. {
  275. door::updateFunction scoreUpdate = [](void) -> std::string {
  276. std::string text = "Score: ";
  277. text.append(std::to_string(score));
  278. return text;
  279. };
  280. std::string scoreString = scoreUpdate();
  281. door::Line score(scoreString, W);
  282. score.setRender(svRender);
  283. score.setUpdater(scoreUpdate);
  284. p.addLine(std::make_unique<door::Line>(score));
  285. }
  286. {
  287. door::updateFunction timeUpdate = [&door](void) -> std::string {
  288. std::stringstream ss;
  289. std::string text;
  290. ss << "Time used: " << setw(3) << door.time_used << " / " << setw(3)
  291. << door.time_left;
  292. text = ss.str();
  293. return text;
  294. };
  295. std::string timeString = timeUpdate();
  296. door::Line time(timeString, W);
  297. time.setRender(svRender);
  298. time.setUpdater(timeUpdate);
  299. p.addLine(std::make_unique<door::Line>(time));
  300. }
  301. {
  302. door::updateFunction handUpdate = [](void) -> std::string {
  303. std::string text = "Playing Hand ";
  304. text.append(std::to_string(hand));
  305. text.append(" of ");
  306. text.append(std::to_string(total_hands));
  307. return text;
  308. };
  309. std::string handString = handUpdate();
  310. door::Line hands(handString, W);
  311. hands.setRender(svRender);
  312. hands.setUpdater(handUpdate);
  313. p.addLine(std::make_unique<door::Line>(hands));
  314. }
  315. return p;
  316. }
  317. */
  318. int main(int argc, char *argv[]) {
  319. door::Door door("space-ace", argc, argv);
  320. // store the door log so we can easily access it.
  321. get_logger = [&door]() -> ofstream & { return door.log(); };
  322. DBData spacedb;
  323. spacedb.setUser(door.username);
  324. if (file_exists("space-ace.yaml")) {
  325. config = YAML::LoadFile("space-ace.yaml");
  326. }
  327. bool update_config = false;
  328. // populate with "good" defaults
  329. if (!config["hands_per_day"]) {
  330. config["hands_per_day"] = 3;
  331. update_config = true;
  332. }
  333. if (!config["date_format"]) {
  334. config["date_format"] = "%B %d"; // Month day or "%b %d,%Y" Mon,d YYYY
  335. update_config = true;
  336. }
  337. if (!config["date_score"]) {
  338. config["date_score"] = "%m/%d/%Y"; // or "%Y/%0m/%0d";
  339. update_config = true;
  340. }
  341. if (!config["makeup_per_day"]) {
  342. config["makeup_per_day"] = 5;
  343. update_config = true;
  344. }
  345. if (!config["play_days_ahead"]) {
  346. config["play_days_ahead"] = 2;
  347. update_config = true;
  348. }
  349. /*
  350. if (config["hands_per_day"]) {
  351. get_logger() << "hands_per_day: " << config["hands_per_day"].as<int>()
  352. << std::endl;
  353. }
  354. */
  355. // save configuration -- something was updated
  356. if (update_config) {
  357. std::ofstream fout("space-ace.yaml");
  358. fout << config << std::endl;
  359. }
  360. // retrieve lastcall
  361. time_t last_call = std::stol(spacedb.getSetting("LastCall", "0"));
  362. // store now as lastcall
  363. time_t now =
  364. std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  365. spacedb.setSetting("LastCall", std::to_string(now));
  366. // Have they used this door before?
  367. if (last_call != 0) {
  368. door << "Welcome Back!" << door::nl;
  369. auto nowClock = std::chrono::system_clock::from_time_t(now);
  370. auto lastClock = std::chrono::system_clock::from_time_t(last_call);
  371. auto delta = nowClock - lastClock;
  372. // int days = chrono::duration_cast<chrono::days>(delta).count(); //
  373. // c++ 20
  374. int hours = chrono::duration_cast<chrono::hours>(delta).count();
  375. int days = hours / 24;
  376. int minutes = chrono::duration_cast<chrono::minutes>(delta).count();
  377. int secs = chrono::duration_cast<chrono::seconds>(delta).count();
  378. if (days > 1) {
  379. door << "It's been " << days << " days since you last played."
  380. << door::nl;
  381. } else {
  382. if (hours > 1) {
  383. door << "It's been " << hours << " hours since you last played."
  384. << door::nl;
  385. } else {
  386. if (minutes > 1) {
  387. door << "It's been " << minutes << " minutes since you last played."
  388. << door::nl;
  389. } else {
  390. door << "It's been " << secs << " seconds since you last played."
  391. << door::nl;
  392. door << "It's like you never left." << door::nl;
  393. }
  394. }
  395. }
  396. press_a_key(door);
  397. }
  398. /*
  399. // example: saving the door.log() for global use.
  400. std::function<std::ofstream &(void)> get_logger;
  401. get_logger = [&door]() -> ofstream & { return door.log(); };
  402. if (get_logger) {
  403. get_logger() << "MEOW" << std::endl;
  404. get_logger() << "hey! It works!" << std::endl;
  405. }
  406. get_logger = nullptr; // before door destruction
  407. */
  408. // https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
  409. std::random_device rd; // only used once to initialise (seed) engine
  410. std::mt19937 rng(rd());
  411. // random-number engine used (Mersenne-Twister in this case)
  412. // std::uniform_int_distribution<int> uni(min, max); // guaranteed
  413. // unbiased
  414. int mx, my; // Max screen width/height
  415. if (door.width == 0) {
  416. // screen detect failed, use sensible defaults
  417. door.width = mx = 80;
  418. door.height = my = 23;
  419. } else {
  420. mx = door.width;
  421. my = door.height;
  422. }
  423. // We assume here that the width and height aren't something crazy like
  424. // 10x15. :P (or 24x923!)
  425. display_starfield_space_ace(door, rng);
  426. // for testing inactivity timeout
  427. // door.inactivity = 10;
  428. door::Panel timeout = make_timeout(mx, my);
  429. door::Menu m = make_main_menu();
  430. door::Panel about = make_about(); // 8 lines
  431. // center the about box
  432. about.set((mx - 60) / 2, (my - 9) / 2);
  433. int r = 0;
  434. while ((r >= 0) and (r != 6)) {
  435. // starfield + menu ?
  436. display_starfield(door, rng);
  437. r = m.choose(door);
  438. // need to reset the colors. (whoops!)
  439. door << door::reset << door::cls; // door::nl;
  440. // OK! The screen is blank at this point!
  441. switch (r) {
  442. case 1: // play game
  443. {
  444. PlayCards pc(door, spacedb, rng);
  445. r = pc.play();
  446. // r = play_cards(door, spacedb, rng);
  447. }; break;
  448. case 2: // view scores
  449. {
  450. door << door::cls;
  451. auto all_scores = spacedb.getScores();
  452. for (auto it : all_scores) {
  453. time_t on_this_date = it.first;
  454. std::string nice_date = convertDateToDateScoreFormat(on_this_date);
  455. door << " *** " << nice_date << " ***" << door::nl;
  456. for (auto sd : it.second) {
  457. door << setw(15) << sd.user << " " << sd.won << " " << sd.score
  458. << door::nl;
  459. }
  460. }
  461. door << "====================" << door::nl;
  462. }
  463. r = press_a_key(door);
  464. break;
  465. case 3: // configure
  466. r = configure(door, spacedb);
  467. // r = press_a_key(door);
  468. break;
  469. case 4: // help
  470. door << "Help! Need some help here..." << door::nl;
  471. r = press_a_key(door);
  472. break;
  473. case 5: // about
  474. display_starfield(door, rng);
  475. door << about << door::nl;
  476. r = press_a_key(door);
  477. break;
  478. case 6: // quit
  479. break;
  480. }
  481. }
  482. if (r < 0) {
  483. // TIMEOUT:
  484. if (r == -1) {
  485. door.log() << "TIMEOUT" << std::endl;
  486. door << timeout << door::reset << door::nl << door::nl;
  487. } else {
  488. if (r == -3) {
  489. door.log() << "OUTTA TIME" << std::endl;
  490. door::Panel notime = make_notime(mx, my);
  491. door << notime << door::reset << door::nl;
  492. }
  493. }
  494. return 0;
  495. }
  496. door << door::nl;
  497. // door << door::reset << door::cls;
  498. display_starfield(door, rng);
  499. door << m << door::reset << door::nl;
  500. // Normal DOOR exit goes here...
  501. door << door::nl << "Returning you to the BBS, please wait..." << door::nl;
  502. get_logger = nullptr;
  503. return 0;
  504. }