| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252 |
- const
- fs = require("fs"),
- readline = require("readline"),
- arrayPad = require('./strpad.js').arrayPad;
- Object.assign(global, require("./config.js"));
- function initWordList(filename) {
- return new Promise((ok, ko) => {
- console.log("Reloading dictionnary");
- var stream = fs.createReadStream(filename),
- reader = readline.createInterface({input: stream}),
- words = [];
- reader.on("line", w => {
- words.push(w);
- });
- reader.on("close", () => {
- if (!words.length) {
- ko();
- return;
- }
- ok(words);
- });
- });
- }
- function Rapido(config) {
- this.config = config;
- }
- Rapido.prototype.init = function(bot, chanName) {
- this.room = chanName;
- this.bot = bot;
- this.init = false;
- this.users = {};
- this.wordRequest = [];
- this.resetScoresWrapper();
- }
- Rapido.prototype.onSelfJoin = function() {
- this.init = true;
- this.reloadDb();
- }
- Rapido.prototype.onJoin = function(nick) { }
- Rapido.prototype.onNameList = function(nicks) { }
- Rapido.prototype.onNickPart = function(nick) { }
- Rapido.prototype.onRemMode = function(user, mode) { }
- Rapido.prototype.onAddMode = function(user, mode) { }
- Rapido.prototype.onRename = function(oldNick, newNick) {
- if (this.users[oldNick.toLowerCase()]) {
- this.users[newNick.toLowerCase()] = this.users[oldNick.toLowerCase()];
- delete this.users[oldNick.toLowerCase()];
- }
- }
- Rapido.prototype.onMessage = function(user, text) {
- if (this.config.DISABLED)
- return;
- this.onMessageInternal(user, this.users[user.toLowerCase()], text.trimEnd().replace(/\s+/, ' '));
- }
- Rapido.prototype.reloadDb = function() {
- var _this = this;
- this.reloading = true;
- initWordList(this.config.DICTIONARY_PATH).then(words => {
- _this.reloading = false;
- _this.words = words;
- _this.bot.sendMsg(this.room, words.length +" words loaded from database");
- _this.endWord();
- }).catch(err => {
- console.error(err);
- _this.bot.sendMsg(this.room, err);
- });
- }
- Rapido.prototype.resetScoresWrapper = function() {
- const now = Date.now(),
- nextTick = Math.floor((now / this.config.GAME_DURATION) +1) *this.config.GAME_DURATION,
- _this = this;
- setTimeout(() => {
- _this.resetScores();
- _this.resetScoresWrapper();
- }, nextTick -now);
- }
- Rapido.prototype.resetScores = function() {
- if (Object.keys(this.users).length > 0) {
- this.bot.sendMsg(this.room, "Fin de la manche ! Voici les scores finaux:");
- this.sendScore();
- }
- this.users = {};
- }
- Rapido.prototype.endWord = function() {
- this.wordTimeout && clearTimeout(this.wordTimeout);
- this.wordTimeout = 0;
- this.currentWord = null;
- this.currentPoints = [];
- this.wordRequest = [];
- this.wordStart= 0;
- }
- Rapido.prototype.onWordTimeout = function() {
- this.wordTimeout = 0;
- ++(this.setProgression);
- if (this.currentPoints.length) {
- this.currentPoints = this.currentPoints.map((i, index) => {
- const time = i.time -this.wordStart;
- return {
- username: i.username,
- time: time,
- fps: Math.floor(100000 * this.currentWord.length / time) / 100,
- pts: this.computeScore(time, this.currentWord, index)
- };
- });
- this.currentPoints.forEach(i => {
- this.bot.sendMsg(this.room, "Mot trouvé en " +i.time +"ms (" +i.fps +" touches par seconde) par " +i.username);
- });
- this.currentPoints.forEach(i => {
- this.users[i.username] = this.users[i.username] || this.bot.createUser(i.username);
- this.users[i.username].score += i.pts;
- this.users[i.username].stats = this.users[i.username].stats || [];
- this.users[i.username].stats.push({
- speed: i.fps,
- time: i.time
- });
- this.bot.sendMsg(this.room, i.pts +" points pour " +i.username +", qui cumule un total de " +this.users[i.username].score +" points !");
- });
- } else {
- this.bot.sendMsg(this.room, "Bah alors ? " +this.wordRequest.join(", ") +" vous fichez quoi ?");
- }
- this.endWord();
- if (this.setProgression >= this.config.WORD_IN_SET) {
- this.bot.sendMsg(this.room, "fin du temps réglementaire, tapez !rapido pour une prochaine partie.");
- var stats = [];
- for (var i in this.users) {
- var userStats = this.users[i].stats;
- if (userStats && userStats.length) {
- var stat = { name: i, avgSpeed: 0, avgTime: 0 };
- userStats.forEach(j => {
- stat.avgSpeed += j.speed / userStats.length;
- stat.avgTime += j.time / userStats.length;
- }, this);
- stats.push(stat);
- }
- }
- if (stats.length) {
- stats.sort((i, j) => j.avgSpeed - i.avgSpeed);
- var index = 0;
- var scoreLines = arrayPad(stats.map(i => [ ((++index) +"."), i.name, ("Vitesse: " +(Math.round(i.avgSpeed * 100) / 100)), ("Temps: " +Math.round(i.avgTime) +"ms") ]));
- this.bot.sendMsg(this.room, "Moyennes des joueurs:");
- for (var i =0, len = scoreLines.length; i < len; i += 2)
- this.bot.sendMsg(this.room, ((scoreLines[i] || "") +" - " +(scoreLines[i +1] || "")));
- this.bot.sendMsg(this.room, "Scores:");
- this.sendScore();
- }
- }
- else
- this.startNextWordTimer();
- }
- Rapido.prototype.startNewSet = function() {
- this.setProgression = 0;
- for (var i in this.users)
- this.users[i].stats = [];
- this.startNextWordTimer();
- }
- Rapido.prototype.startNextWordTimer = function() {
- var _this = this;
- this.currentWord = this.words[Math.floor(Math.random() * this.words.length)];
- console.log(this.currentWord);
- _this.bot.sendMsg(this.room, "Attention attention, prochain mot dans " +Math.floor(this.config.NEXT_WORD_DELAY / 1000) +" secondes");
- if (this.setProgression == 0)
- _this.bot.sendMsg(this.room, "Rappel : il faut taper le plus vite possible en minuscule et sans espaces le mot proposé");
- setTimeout(() => {
- var wordEsc = _this.currentWord.replace(/(\w)/g, ' $1').toUpperCase().trimStart();
- _this.bot.sendMsg(_this.room, wordEsc);
- _this.wordStart = Date.now();
- _this.wordTimeout = setTimeout(_this.onWordTimeout.bind(_this), Math.floor(1000 * this.currentWord.length / this.config.WORD_TIMEO_FPS));
- }, this.config.NEXT_WORD_DELAY);
- }
- Rapido.prototype.sendScore = function() {
- var scores = [];
- for (var i in this.users)
- scores.push({name: this.users[i].name, score: this.users[i].score});
- if (scores.length == 0) {
- this.bot.sendMsg(this.room, "Pas de points pour le moment");
- return;
- }
- scores = scores.sort((a, b) => b.score - a.score).slice(0, 10);
- var index = 0;
- var scoreLines = arrayPad(scores.map(i => [ ((++index) +"."), i.name, (i.score +" points") ]));
- if (scoreLines[0].length < 30) {
- // merge score lines 2 by 2
- var tmp = [];
- for (var i =0, len = scoreLines.length; i < len; i += 2)
- tmp.push((scoreLines[i] || "") +" - " +(scoreLines[i +1] || ""));
- scoreLines = tmp;
- }
- scoreLines.forEach(i => this.bot.sendMsg(this.room, i));
- }
- Rapido.prototype.computeScore = function(ellapsed, word, index) {
- const fps = 1000 * word.length / ellapsed;
- console.log({
- fps: fps,
- ellapsed: ellapsed,
- word: word
- });
- var base = 2 +(index == 0 ? 2 : 0);
- for (var i =0, len = this.config.SCORE_MAP.length; i < len; ++i) {
- var scoreItem = this.config.SCORE_MAP[i];
- if (fps >= scoreItem[0])
- return base +scoreItem[1];
- }
- return base;
- }
- Rapido.prototype.onMessageInternal = function(username, user, msg) {
- const lmsg = msg.toLowerCase();
- msg = lmsg.substr(0, 1) + msg.substr(1);
- if (lmsg === "!next") {
- this.bot.sendMsg(this.room, "La commande !next a été remplacé par !rapido.");
- } else if (lmsg === "!rapido") {
- if (this.wordRequest.indexOf(username) === -1)
- this.wordRequest.push(username);
- if (!this.currentWord && this.wordRequest.length >= this.config.MIN_PLAYERS)
- this.startNewSet();
- }
- else if (lmsg.startsWith("!score")) {
- this.sendScore();
- }
- else if (this.currentWord && this.wordStart && msg === this.currentWord) {
- for (var i =0, len = this.currentPoints.length; i < len; ++i)
- if (this.currentPoints[i].username == username)
- return;
- this.currentPoints.push({ username: username, time: Date.now()});
- this.bot.sendMsg(this.room, "Ok pour " +username);
- }
- else if (lmsg.startsWith("!help")) {
- 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");
- }
- };
- module.exports = Rapido;
|