rapido.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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.users[i.username].stats = this.users[i.username].stats || [];
  112. this.users[i.username].stats.push({
  113. speed: i.fps,
  114. time: i.time
  115. });
  116. this.bot.sendMsg(this.room, i.pts +" points pour " +i.username +", qui cumule un total de " +this.users[i.username].score +" points !");
  117. });
  118. } else {
  119. this.bot.sendMsg(this.room, "Bah alors ? " +this.wordRequest.join(", ") +" vous fichez quoi ?");
  120. }
  121. this.endWord();
  122. if (this.setProgression >= this.config.WORD_IN_SET) {
  123. this.bot.sendMsg(this.room, "fin du temps réglementaire, tapez !rapido pour une prochaine partie.");
  124. var stats = [];
  125. for (var i in this.users) {
  126. var userStats = this.users[i].stats;
  127. if (userStats && userStats.length) {
  128. var stat = { name: i, avgSpeed: 0, avgTime: 0 };
  129. userStats.forEach(j => {
  130. stat.avgSpeed += j.speed / userStats.length;
  131. stat.avgTime += j.time / userStats.length;
  132. }, this);
  133. stats.push(stat);
  134. }
  135. }
  136. if (stats.length) {
  137. stats.sort((i, j) => j.avgSpeed - i.avgSpeed);
  138. var index = 0;
  139. var scoreLines = arrayPad(stats.map(i => [ ((++index) +"."), i.name, ("Vitesse: " +(Math.round(i.avgSpeed * 100) / 100)), ("Temps: " +Math.round(i.avgTime) +"ms") ]));
  140. this.bot.sendMsg(this.room, "Moyennes des joueurs:");
  141. for (var i =0, len = scoreLines.length; i < len; i += 2)
  142. this.bot.sendMsg(this.room, ((scoreLines[i] || "") +" - " +(scoreLines[i +1] || "")));
  143. this.bot.sendMsg(this.room, "Scores:");
  144. this.sendScore();
  145. }
  146. }
  147. else
  148. this.startNextWordTimer();
  149. }
  150. Rapido.prototype.startNewSet = function() {
  151. this.setProgression = 0;
  152. for (var i in this.users)
  153. this.users[i].stats = [];
  154. this.startNextWordTimer();
  155. }
  156. Rapido.prototype.startNextWordTimer = function() {
  157. var _this = this;
  158. this.currentWord = this.words[Math.floor(Math.random() * this.words.length)];
  159. console.log(this.currentWord);
  160. _this.bot.sendMsg(this.room, "Attention attention, prochain mot dans " +Math.floor(this.config.NEXT_WORD_DELAY / 1000) +" secondes");
  161. if (this.setProgression == 0)
  162. _this.bot.sendMsg(this.room, "Rappel : il faut taper le plus vite possible en minuscule et sans espaces le mot proposé");
  163. setTimeout(() => {
  164. var wordEsc = _this.currentWord.replace(/(\w)/g, ' $1').toUpperCase().trimStart();
  165. _this.bot.sendMsg(_this.room, wordEsc);
  166. _this.wordStart = Date.now();
  167. _this.wordTimeout = setTimeout(_this.onWordTimeout.bind(_this), Math.floor(1000 * this.currentWord.length / this.config.WORD_TIMEO_FPS));
  168. }, this.config.NEXT_WORD_DELAY);
  169. }
  170. Rapido.prototype.sendScore = function() {
  171. var scores = [];
  172. for (var i in this.users)
  173. scores.push({name: this.users[i].name, score: this.users[i].score});
  174. if (scores.length == 0) {
  175. this.bot.sendMsg(this.room, "Pas de points pour le moment");
  176. return;
  177. }
  178. scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
  179. var index = 0;
  180. var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
  181. if (scoreLines[0].length < 30) {
  182. // merge score lines 2 by 2
  183. var tmp = [];
  184. for (var i =0, len = scoreLines.length; i < len; i += 2)
  185. tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
  186. scoreLines = tmp;
  187. }
  188. scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
  189. }
  190. Rapido.prototype.computeScore = function(ellapsed, word, index) {
  191. const fps = 1000 * word.length / ellapsed;
  192. console.log({
  193. fps: fps,
  194. ellapsed: ellapsed,
  195. word: word
  196. });
  197. var base = 2 +(index == 0 ? 2 : 0);
  198. for (var i =0, len = this.config.SCORE_MAP.length; i < len; ++i) {
  199. var scoreItem = this.config.SCORE_MAP[i];
  200. if (fps >= scoreItem[0])
  201. return base +scoreItem[1];
  202. }
  203. return base;
  204. }
  205. Rapido.prototype.onMessageInternal = function(username, user, msg) {
  206. const lmsg = msg.toLowerCase();
  207. msg = lmsg.substr(0, 1) + msg.substr(1);
  208. if (lmsg === "!next") {
  209. this.bot.sendMsg(this.room, "La commande !next a été remplacé par !rapido.");
  210. } else if (lmsg === "!rapido") {
  211. if (this.wordRequest.indexOf(username) === -1)
  212. this.wordRequest.push(username);
  213. if (!this.currentWord && this.wordRequest.length >= this.config.MIN_PLAYERS)
  214. this.startNewSet();
  215. }
  216. else if (lmsg.startsWith("!score")) {
  217. this.sendScore();
  218. }
  219. else if (this.currentWord && this.wordStart && msg === this.currentWord) {
  220. for (var i =0, len = this.currentPoints.length; i < len; ++i)
  221. if (this.currentPoints[i].username == username)
  222. return;
  223. this.currentPoints.push({ username: username, time: Date.now()});
  224. this.bot.sendMsg(this.room, "Ok pour " +username);
  225. }
  226. else if (lmsg.startsWith("!help")) {
  227. 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");
  228. }
  229. };
  230. module.exports = Rapido;