rapido.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. this.wordTimeout && clearTimeout(this.wordTimeout);
  86. this.wordTimeout = 0;
  87. this.currentWord = null;
  88. this.currentPoints = [];
  89. this.wordRequest = [];
  90. this.wordStart= 0;
  91. }
  92. Rapido.prototype.onWordTimeout = function() {
  93. this.wordTimeout = 0;
  94. ++(this.setProgression);
  95. if (this.currentPoints.length) {
  96. this.currentPoints = this.currentPoints.map((i, index) => {
  97. const time = i.time -this.wordStart;
  98. return {
  99. username: i.username,
  100. time: time,
  101. fps: Math.floor(100000 * this.currentWord.length / time) / 100,
  102. pts: this.computeScore(time, this.currentWord, index)
  103. };
  104. });
  105. this.currentPoints.forEach(i => {
  106. this.bot.sendMsg(this.room, "Mot trouvé en " +i.time +"ms (" +i.fps +" touches par seconde) par " +i.username);
  107. });
  108. this.currentPoints.forEach(i => {
  109. this.users[i.username] = this.users[i.username] || this.bot.createUser(i.username);
  110. this.users[i.username].score += i.pts;
  111. this.bot.sendMsg(this.room, i.pts +" points pour " +i.username +", qui cumule un total de " +this.users[i.username].score +" points !");
  112. });
  113. } else {
  114. this.bot.sendMsg(this.room, "Bah alors ? " +this.wordRequest.join(", ") +" vous fichez quoi ?");
  115. }
  116. this.endWord();
  117. if (this.setProgression >= this.config.WORD_IN_SET)
  118. this.bot.sendMsg(this.room, "fin du temps réglementaire, tapez !rapido pour une prochaine partie.");
  119. else
  120. this.startNextWordTimer();
  121. }
  122. Rapido.prototype.startNewSet = function() {
  123. this.setProgression = 0;
  124. this.startNextWordTimer();
  125. }
  126. Rapido.prototype.startNextWordTimer = function() {
  127. var _this = this;
  128. this.currentWord = this.words[Math.floor(Math.random() * this.words.length)];
  129. console.log(this.currentWord);
  130. _this.bot.sendMsg(this.room, "Attention attention, prochain mot dans " +Math.floor(this.config.NEXT_WORD_DELAY / 1000) +" secondes");
  131. if (this.setProgression == 0)
  132. _this.bot.sendMsg(this.room, "Rappel : il faut taper le plus vite possible en minuscule et sans espaces le mot proposé");
  133. setTimeout(() => {
  134. var wordEsc = _this.currentWord.replace(/(\w)/g, ' $1').toUpperCase().trimStart();
  135. _this.bot.sendMsg(_this.room, wordEsc);
  136. _this.wordStart = Date.now();
  137. _this.wordTimeout = setTimeout(_this.onWordTimeout.bind(_this), Math.floor(1000 * this.currentWord.length / this.config.WORD_TIMEO_FPS));
  138. }, this.config.NEXT_WORD_DELAY);
  139. }
  140. Rapido.prototype.sendScore = function() {
  141. var scores = [];
  142. for (var i in this.users)
  143. scores.push({name: this.users[i].name, score: this.users[i].score});
  144. if (scores.length == 0) {
  145. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  146. return;
  147. }
  148. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  149. var index = 0;
  150. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  151. if (scoreLines[0].length < 30) {
  152. // merge score lines 2 by 2
  153. var tmp = [];
  154. for (var i =0, len = scoreLines.length; i < len; i += 2)
  155. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  156. scoreLines = tmp;
  157. }
  158. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  159. }
  160. Rapido.prototype.computeScore = function(ellapsed, word, index) {
  161. const fps = 1000 * word.length / ellapsed;
  162. console.log({
  163. fps: fps,
  164. ellapsed: ellapsed,
  165. word: word
  166. });
  167. var base = 2 +(index == 0 ? 2 : 0);
  168. for (var i =0, len = this.config.SCORE_MAP.length; i < len; ++i) {
  169. var scoreItem = this.config.SCORE_MAP[i];
  170. if (fps >= scoreItem[0])
  171. return base +scoreItem[1];
  172. }
  173. return base;
  174. }
  175. Rapido.prototype.onMessageInternal = function(username, user, msg) {
  176. const lmsg = msg.toLowerCase();
  177. msg = lmsg.substr(0, 1) + msg.substr(1);
  178. if (lmsg === "!next") {
  179. this.bot.sendMsg(this.room, "La commande !next a été remplacé par !rapido.");
  180. } else if (lmsg === "!rapido") {
  181. if (this.wordRequest.indexOf(username) === -1)
  182. this.wordRequest.push(username);
  183. if (!this.currentWord && this.wordRequest.length >= this.config.MIN_PLAYERS)
  184. this.startNewSet();
  185. }
  186. else if (lmsg.startsWith("!score")) {
  187. this.sendScore();
  188. }
  189. else if (this.currentWord && this.wordStart && msg === this.currentWord) {
  190. for (var i =0, len = this.currentPoints.length; i < len; ++i)
  191. if (this.currentPoints[i].username == username)
  192. return;
  193. this.currentPoints.push({ username: username, time: Date.now()});
  194. this.bot.sendMsg(this.room, "Ok pour " +username);
  195. }
  196. else if (lmsg.startsWith("!help")) {
  197. 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");
  198. }
  199. };
  200. module.exports = Rapido;