rapido.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. const
  2. fs = require("fs"),
  3. readline = require("readline"),
  4. arrayPad = require('./strpad.js').arrayPad;
  5. Object.assign(global, require("./config.js"));
  6. function initWordList(filename) {
  7. return new Promise((ok, ko) => {
  8. console.log("Reloading dictionnary");
  9. var stream = fs.createReadStream(filename),
  10. reader = readline.createInterface({input: stream}),
  11. words = [];
  12. reader.on("line", w => {
  13. words.push(w);
  14. });
  15. reader.on("close", () => {
  16. if (!words.length) {
  17. ko();
  18. return;
  19. }
  20. ok(words);
  21. });
  22. });
  23. }
  24. function Rapido(config) {
  25. this.config = config;
  26. }
  27. Rapido.prototype.init = function(bot, chanName) {
  28. this.room = chanName;
  29. this.bot = bot;
  30. this.init = false;
  31. this.users = {};
  32. this.wordRequest = [];
  33. this.resetScoresWrapper();
  34. }
  35. Rapido.prototype.onSelfJoin = function() {
  36. this.init = true;
  37. this.reloadDb();
  38. }
  39. Rapido.prototype.onJoin = function(nick) { }
  40. Rapido.prototype.onNameList = function(nicks) { }
  41. Rapido.prototype.onNickPart = function(nick) { }
  42. Rapido.prototype.onRemMode = function(user, mode) { }
  43. Rapido.prototype.onAddMode = function(user, mode) { }
  44. Rapido.prototype.onRename = function(oldNick, newNick) {
  45. if (this.users[oldNick.toLowerCase()]) {
  46. this.users[newNick.toLowerCase()] = this.users[oldNick.toLowerCase()];
  47. delete this.users[oldNick.toLowerCase()];
  48. }
  49. }
  50. Rapido.prototype.onMessage = function(user, text) {
  51. if (this.config.DISABLED)
  52. return;
  53. this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
  54. }
  55. Rapido.prototype.reloadDb = function() {
  56. var _this = this;
  57. this.reloading = true;
  58. initWordList(this.config.DICTIONARY_PATH).then(words => {
  59. _this.reloading = false;
  60. _this.words = words;
  61. _this.bot.sendMsg(this.room, words.length +" words loaded from database");
  62. _this.endWord();
  63. }).catch(err => {
  64. console.error(err);
  65. _this.bot.sendMsg(this.room, err);
  66. });
  67. }
  68. Rapido.prototype.resetScoresWrapper = function() {
  69. const now = Date.now(),
  70. nextTick = Math.floor((now / this.config.GAME_DURATION) +1) *this.config.GAME_DURATION,
  71. _this = this;
  72. setTimeout(() => {
  73. _this.resetScores();
  74. _this.resetScoresWrapper();
  75. }, nextTick -now);
  76. }
  77. Rapido.prototype.resetScores = function() {
  78. if (Object.keys(this.users).length > 0) {
  79. this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
  80. this.sendScore();
  81. }
  82. this.users = {};
  83. }
  84. Rapido.prototype.endWord = function() {
  85. clearTimeout(this.wordTimeout);
  86. this.currentWord = null;
  87. this.currentPoints = [];
  88. this.wordRequest = [];
  89. this.wordStart= 0;
  90. }
  91. Rapido.prototype.onWordTimeout = function() {
  92. if (this.currentPoints.length) {
  93. this.currentPoints = this.currentPoints.map((i, index) => {
  94. const time = i.time -this.wordStart;
  95. return {
  96. username: i.username,
  97. time: time,
  98. fps: Math.floor(100000 * this.currentWord.length / time) / 100,
  99. pts: this.computeScore(time, this.currentWord, index)
  100. };
  101. });
  102. this.currentPoints.forEach(i => {
  103. this.bot.sendMsg(this.room, "Mot trouvé en " +i.time +"ms (" +i.fps +" touches par seconde) par " +i.username);
  104. });
  105. this.currentPoints.forEach(i => {
  106. this.users[i.username] = this.users[i.username] || this.bot.createUser(i.username);
  107. this.users[i.username].score += i.pts;
  108. this.bot.sendMsg(this.room, i.pts +" points pour " +i.username +", qui cumule un total de " +this.users[i.username].score +" points !");
  109. });
  110. } else {
  111. this.bot.sendMsg(this.room, "Bah alors ? " +this.wordRequest.join(", ") +" vous fichez quoi ?");
  112. this.bot.sendMsg(this.room, "fin du temps réglementaire, tapez !next pour une prochaine partie.");
  113. }
  114. this.endWord();
  115. }
  116. Rapido.prototype.startNextWordTimer = function() {
  117. var _this = this;
  118. this.currentWord = this.words[Math.floor(Math.random() * this.words.length)];
  119. console.log(this.currentWord);
  120. _this.bot.sendMsg(this.room, "Attention attention, prochain mot dans " +Math.floor(this.config.NEXT_WORD_DELAY / 1000) +" secondes");
  121. _this.bot.sendMsg(this.room, "Rappel : il faut taper le plus vite possible en minuscule et sans espaces le mot proposé");
  122. setTimeout(() => {
  123. var wordEsc = _this.currentWord.replace(/(\w)/g, ' $1').toUpperCase().trimStart();
  124. _this.bot.sendMsg(_this.room, wordEsc);
  125. _this.wordStart = Date.now();
  126. _this.wordTimeout = setTimeout(_this.onWordTimeout.bind(_this), Math.floor(1000 * this.currentWord.length / this.config.WORD_TIMEO_FPS));
  127. }, this.config.NEXT_WORD_DELAY);
  128. }
  129. Rapido.prototype.sendScore = function() {
  130. var scores = [];
  131. for (var i in this.users)
  132. scores.push({name: this.users[i].name, score: this.users[i].score});
  133. if (scores.length == 0) {
  134. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  135. return;
  136. }
  137. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  138. var index = 0;
  139. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  140. if (scoreLines[0].length < 30) {
  141. // merge score lines 2 by 2
  142. var tmp = [];
  143. for (var i =0, len = scoreLines.length; i < len; i += 2)
  144. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  145. scoreLines = tmp;
  146. }
  147. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  148. }
  149. Rapido.prototype.computeScore = function(ellapsed, word, index) {
  150. const fps = 1000 * word.length / ellapsed;
  151. console.log({
  152. fps: fps,
  153. ellapsed: ellapsed,
  154. word: word
  155. });
  156. var base = 2 +(index == 0 ? 2 : 0);
  157. for (var i =0, len = this.config.SCORE_MAP.length; i < len; ++i) {
  158. var scoreItem = this.config.SCORE_MAP[i];
  159. if (fps >= scoreItem[0])
  160. return base +scoreItem[1];
  161. }
  162. return base;
  163. }
  164. Rapido.prototype.onMessageInternal = function(username, user, msg) {
  165. const lmsg = msg.toLowerCase();
  166. if (lmsg === "!next") {
  167. if (this.wordRequest.indexOf(username) === -1)
  168. this.wordRequest.push(username);
  169. if (!this.currentWord && this.wordRequest.length >= this.config.MIN_PLAYERS)
  170. this.startNextWordTimer();
  171. }
  172. else if (lmsg.startsWith("!score")) {
  173. this.sendScore();
  174. }
  175. else if (this.currentWord && this.wordStart && msg === this.currentWord) {
  176. for (var i =0, len = this.currentPoints.length; i < len; ++i)
  177. if (this.currentPoints[i].username == username)
  178. return;
  179. this.currentPoints.push({ username: username, time: Date.now()});
  180. this.bot.sendMsg(this.room, "Ok pour " +username);
  181. }
  182. else if (lmsg.startsWith("!aide")) {
  183. this.bot.sendMsg(this.room, "Besoin d'aide ? Les règles ainsi que les commandes utiles sont ici : https://git.knacki.info/irc.knacki.info/ircbot-quizz/src/master/rapido.md");
  184. }
  185. };
  186. module.exports = Rapido;