]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/games/azgame.rb
azgame: missing closing parenthesis in message
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / games / azgame.rb
1 #-- vim:sw=2:et\r
2 #++\r
3 #\r
4 # :title: A-Z Game Plugin for rbot\r
5 #\r
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>\r
7 # Author:: Yaohan Chen <yaohan.chen@gmail.com>: Japanese support\r
8 #\r
9 # Copyright:: (C) 2006 Giuseppe Bilotta\r
10 # Copyright:: (C) 2007 GIuseppe Bilotta, Yaohan Chen\r
11 #\r
12 # License:: GPL v2\r
13 #\r
14 # A-Z Game: guess the word by reducing the interval of allowed ones\r
15 #\r
16 # TODO allow manual addition of words\r
17 \r
18 class AzGame\r
19 \r
20   attr_reader :range, :word\r
21   attr_reader :lang, :rules, :listener\r
22   attr_accessor :tries, :total_tries, :total_failed, :failed, :winner\r
23   def initialize(plugin, lang, rules, word)\r
24     @plugin = plugin\r
25     @lang = lang.to_sym\r
26     @word = word.downcase\r
27     @rules = rules\r
28     @range = [@rules[:first].dup, @rules[:last].dup]\r
29     @listener = @rules[:listener]\r
30     @total_tries = 0\r
31     @total_failed = 0 # not used, reported, updated\r
32     @tries = Hash.new(0)\r
33     @failed = Hash.new(0) # not used, not reported, updated\r
34     @winner = nil\r
35     def @range.to_s\r
36       return "%s -- %s" % self\r
37     end\r
38   end\r
39 \r
40   def check(word)\r
41     w = word.downcase\r
42     debug "checking #{w} for #{@word} in #{@range}"\r
43     return [:bingo, nil] if w == @word\r
44     return [:out, @range] if w < @range.first or w > @range.last\r
45     return [:ignore, @range] if w == @range.first or w == @range.last\r
46     return [:noexist, @range] unless @plugin.send("is_#{@lang}?", w)\r
47     debug "we like it"\r
48     if w < @word\r
49       @range.first.replace(w)\r
50     else\r
51       @range.last.replace(w)\r
52     end\r
53     return [:in, @range]\r
54   end\r
55 \r
56 # TODO scoring: base score is t = ceil(100*exp(-((n-1)^2)/(50^2)))+p for n attempts\r
57 #               done by p players; players that didn't win but contributed\r
58 #               with a attempts will get t*a/n points\r
59 \r
60   include Math\r
61 \r
62   def score\r
63     n = @total_tries\r
64     p = @tries.keys.length\r
65     t = (100*exp(-((n-1)**2)/(50.0**2))).ceil + p\r
66     debug "Total score: #{t}"\r
67     ret = Hash.new\r
68     @tries.each { |k, a|\r
69       ret[k] = [t*a/n, n_("%{count} try", "%{count} tries", a) % {:count => a}]\r
70     }\r
71     if @winner\r
72       debug "replacing winner score of %d with %d" % [ret[@winner].first, t]\r
73       tries = ret[@winner].last\r
74       ret[@winner] = [t, _("winner, %{tries}") % {:tries => tries}]\r
75     end\r
76     return ret.sort_by { |h| h.last.first }.reverse\r
77   end\r
78 \r
79 end\r
80 \r
81 class AzGamePlugin < Plugin\r
82 \r
83   def initialize\r
84     super\r
85     # if @registry.has_key?(:games)\r
86     #   @games = @registry[:games]\r
87     # else\r
88       @games = Hash.new\r
89     # end\r
90     if @registry.has_key?(:wordcache) and @registry[:wordcache]\r
91       @wordcache = @registry[:wordcache]\r
92     else\r
93       @wordcache = Hash.new\r
94     end\r
95     debug "A-Z wordcache: #{@wordcache.pretty_inspect}"\r
96 \r
97     @rules = {\r
98       :italian => {\r
99       :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.\r
100       :bad => /var\./,\r
101       :first => 'abaco',\r
102       :last => 'zuzzurellone',\r
103       :url => "http://www.demauroparavia.it/%s",\r
104       :wapurl => "http://wap.demauroparavia.it/index.php?lemma=%s",\r
105       :listener => /^[a-z]+$/\r
106     },\r
107     :english => {\r
108       :good => /(?:singular )?noun|verb|adj/,\r
109       :first => 'abacus',\r
110       :last => 'zuni',\r
111       :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st",\r
112       :listener => /^[a-z]+$/\r
113     },\r
114     }\r
115     \r
116     japanese_wordlist = "#{@bot.botclass}/azgame/wordlist-japanese"\r
117     if File.exist?(japanese_wordlist)\r
118       words = File.readlines(japanese_wordlist) \\r
119                              .map {|line| line.strip} .uniq\r
120       if(words.length >= 4) # something to guess\r
121         @rules[:japanese] = {\r
122             :good => /^\S+$/,\r
123             :list => words,\r
124             :first => words[0],\r
125             :last => words[-1],\r
126             :listener => /^\S+$/\r
127         }\r
128         debug "Japanese wordlist loaded, #{@rules[:japanese][:list].length} lines; first word: #{@rules[:japanese][:first]}, last word: #{@rules[:japanese][:last]}"\r
129       end\r
130     end\r
131   end\r
132 \r
133   def save\r
134     # @registry[:games] = @games\r
135     @registry[:wordcache] = @wordcache\r
136   end\r
137 \r
138   def listen(m)\r
139     return unless m.kind_of?(PrivMessage)\r
140     return if m.channel.nil? or m.address?\r
141     k = m.channel.downcase.to_s # to_sym?\r
142     return unless @games.key?(k)\r
143     return if m.params\r
144     word = m.plugin.downcase\r
145     return unless word =~ @games[k].listener\r
146     word_check(m, k, word)\r
147   end\r
148 \r
149   def word_check(m, k, word)\r
150     isit = @games[k].check(word)\r
151     case isit.first\r
152     when :bingo\r
153       m.reply _("%{bold}BINGO!%{bold} the word was %{underline}%{word}%{underline}. Congrats, %{bold}%{player}%{bold}!") % {:bold => Bold, :underline => Underline, :word => word, :player => m.sourcenick}\r
154       @games[k].total_tries += 1\r
155       @games[k].tries[m.source] += 1\r
156       @games[k].winner = m.source\r
157       ar = @games[k].score.inject([]) { |res, kv|\r
158         res.push("%s: %d (%s)" % kv.flatten)\r
159       }\r
160       m.reply _("The game was won after %{tries} tries. Scores for this game:    %{scores}") % {:tries => @games[k].total_tries, :scores => ar.join('; ')}\r
161       @games.delete(k)\r
162     when :out\r
163       m.reply _("%{word} is not in the range %{bold}%{range}%{bold}") % {:word => word, :bold => Bold, :range => isit.last} if m.address?\r
164     when :noexist\r
165       m.reply _("%{word} doesn't exist or is not acceptable for the game") % {:word => word}\r
166       @games[k].total_failed += 1\r
167       @games[k].failed[m.source] += 1\r
168     when :in\r
169       m.reply _("close, but no cigar. New range: %{bold}%{range}%{bold}") % {:bold => Bold, :range => isit.last}\r
170       @games[k].total_tries += 1\r
171       @games[k].tries[m.source] += 1\r
172     when :ignore\r
173       m.reply _("%{word} is already one of the range extrema: %{range}") % {:word => word, :range => isit.last} if m.address?\r
174     else\r
175       m.reply _("hm, something went wrong while verifying %{word}")\r
176     end\r
177   end\r
178 \r
179   def manual_word_check(m, params)\r
180     k = m.channel.downcase.to_s\r
181     word = params[:word].downcase\r
182     if not @games.key?(k)\r
183       m.reply _("no A-Z game running here, can't check if %{word} is valid, can I?")\r
184       return\r
185     end\r
186     if word !~ /^\S+$/\r
187       m.reply _("I only accept single words composed by letters only, sorry")\r
188       return\r
189     end\r
190     word_check(m, k, word)\r
191   end\r
192 \r
193   def stop_game(m, params)\r
194     return if m.channel.nil? # Shouldn't happen, but you never know\r
195     k = m.channel.downcase.to_s # to_sym?\r
196     if @games.key?(k)\r
197       m.reply _("the word in %{bold}%{range}%{bold} was:   %{bold}%{word}%{bold}") % {:bold => Bold, :range => @games[k].range, :word => @games[k].word}\r
198       ar = @games[k].score.inject([]) { |res, kv|\r
199         res.push("%s: %d (%s)" % kv.flatten)\r
200       }\r
201       m.reply _("The game was cancelled after %{tries} tries. Scores for this game would have been:    %{scores}") % {:tries => @games[k].total_tries, :scores => ar.join('; ')}\r
202       @games.delete(k)\r
203     else\r
204       m.reply _("no A-Z game running in this channel ...")\r
205     end\r
206   end\r
207 \r
208   def start_game(m, params)\r
209     return if m.channel.nil? # Shouldn't happen, but you never know\r
210     k = m.channel.downcase.to_s # to_sym?\r
211     unless @games.key?(k)\r
212       lang = (params[:lang] || @bot.config['core.language']).to_sym\r
213       method = 'random_pick_'+lang.to_s\r
214       m.reply _("let me think ...")\r
215       if @rules.has_key?(lang) and self.respond_to?(method)\r
216         word = self.send(method)\r
217         if word.empty?\r
218           m.reply _("couldn't think of anything ...")\r
219           return\r
220         end\r
221       else\r
222         m.reply _("I can't play A-Z in %{lang}, sorry") % {:lang => lang}\r
223         return\r
224       end\r
225       m.reply _("got it!")\r
226       @games[k] = AzGame.new(self, lang, @rules[lang], word)\r
227     end\r
228     tr = @games[k].total_tries\r
229     # this message building code is rewritten to make translation easier\r
230     if tr == 0\r
231       tr_msg = ''\r
232     else\r
233       f_tr = @games[k].total_failed\r
234       if f_tr > 0\r
235         tr_msg = _(" (after %{total_tries} and %{invalid_tries})") %\r
236            { :total_tries => n_("%{count} try", "%{count} tries", tr) %\r
237                              {:count => tr},\r
238              :invalid_tries => n_("%{count} invalid try", "%{count} invalid tries", tr) %\r
239                                {:count => f_tr} }\r
240       else\r
241         tr_msg = _(" (after %{total_tries}") %\r
242                  { :total_tries => n_("%{count} try", "%{count} tries", tr) %\r
243                              {:count => tr}}\r
244       end\r
245     end\r
246 \r
247     m.reply _("A-Z: %{bold}%{range}%{bold}") % {:bold => Bold, :range => @games[k].range} + tr_msg\r
248     return\r
249   end\r
250 \r
251   def wordlist(m, params)\r
252     pars = params[:params]\r
253     lang = (params[:lang] || @bot.config['core.language']).to_sym\r
254     wc = @wordcache[lang] || Hash.new rescue Hash.new\r
255     cmd = params[:cmd].to_sym rescue :count\r
256     case cmd\r
257     when :count\r
258       m.reply n_("I have %{count} %{lang} word in my cache", "I have %{count} %{lang} words in my cache", wc.size) % {:count => wc.size, :lang => lang}\r
259     when :show, :list\r
260       if pars.empty?\r
261         m.reply _("provide a regexp to match")\r
262         return\r
263       end\r
264       begin\r
265         regex = /#{pars[0]}/\r
266         matches = wc.keys.map { |k|\r
267           k.to_s\r
268         }.grep(regex)\r
269       rescue\r
270         matches = []\r
271       end\r
272       if matches.size == 0\r
273         m.reply _("no %{lang} word I know match %{pattern}") % {:lang => lang, :pattern => pars[0]}\r
274       elsif matches.size > 25\r
275         m.reply _("more than 25 %{lang} words I know match %{pattern}, try a stricter matching") % {:lang => lang, :pattern => pars[0]}\r
276       else\r
277         m.reply "#{matches.join(', ')}"\r
278       end\r
279     when :info\r
280       if pars.empty?\r
281         m.reply _("provide a word")\r
282         return\r
283       end\r
284       word = pars[0].downcase.to_sym\r
285       if not wc.key?(word)\r
286         m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}\r
287         return\r
288       end\r
289       if wc[word].key?(:when)\r
290         tr = _("%{word} learned from %{user} on %{date}") % {:word => word, :user => wc[word][:who], :date => wc[word][:when]}\r
291       else\r
292         tr = _("%{word} learned from %{user}") % {:word => word, :user => wc[word][:who]} \r
293       end\r
294       m.reply tr\r
295     when :delete \r
296       if pars.empty?\r
297         m.reply _("provide a word")\r
298         return\r
299       end\r
300       word = pars[0].downcase.to_sym\r
301       if not wc.key?(word)\r
302         m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}\r
303         return\r
304       end\r
305       wc.delete(word)\r
306       @bot.okay m.replyto\r
307     when :add\r
308       if pars.empty?\r
309         m.reply _("provide a word")\r
310         return\r
311       end\r
312       word = pars[0].downcase.to_sym\r
313       if wc.key?(word)\r
314         m.reply _("I already know the %{lang} word %{word}")\r
315         return\r
316       end\r
317       wc[word] = { :who => m.sourcenick, :when => Time.now }\r
318       @bot.okay m.replyto\r
319     else\r
320     end\r
321   end\r
322 \r
323   def is_japanese?(word)\r
324     @rules[:japanese][:list].include?(word)\r
325   end\r
326   \r
327   # return integer between min and max, inclusive\r
328   def rand_between(min, max)\r
329     rand(max - min + 1) + min\r
330   end\r
331   \r
332   def random_pick_japanese(min=nil, max=nil)\r
333     rules = @rules[:japanese]\r
334     min = rules[:first] if min.nil_or_empty?\r
335     max = rules[:last]  if max.nil_or_empty?\r
336     debug "Randomly picking word between #{min} and #{max}"\r
337     min_index = rules[:list].index(min)\r
338     max_index = rules[:list].index(max)\r
339     debug "Index between #{min_index} and #{max_index}"\r
340     index = rand_between(min_index + 1, max_index - 1)\r
341     debug "Index generated: #{index}"\r
342     word = rules[:list][index]\r
343     debug "Randomly picked #{word}"\r
344     word\r
345   end\r
346 \r
347   def is_italian?(word)\r
348     unless @wordcache.key?(:italian)\r
349       @wordcache[:italian] = Hash.new\r
350     end\r
351     wc = @wordcache[:italian]\r
352     return true if wc.key?(word.to_sym)\r
353     rules = @rules[:italian]\r
354     p = @bot.httputil.get(rules[:wapurl] % word)\r
355     if not p\r
356       error "could not connect!"\r
357       return false\r
358     end\r
359     debug p\r
360     p.scan(/<anchor>#{word} - (.*?)<go href="lemma.php\?ID=([^"]*?)"/) { |qual, url|\r
361       debug "new word #{word} of type #{qual}"\r
362       if qual =~ rules[:good] and qual !~ rules[:bad]\r
363         wc[word.to_sym] = {:who => :dict}\r
364         return true\r
365       end\r
366       next\r
367     }\r
368     return false\r
369   end\r
370 \r
371   def random_pick_italian(min=nil,max=nil)\r
372     # Try to pick a random word between min and max\r
373     word = String.new\r
374     min = min.to_s\r
375     max = max.to_s\r
376     if min > max\r
377       m.reply "#{min} > #{max}"\r
378       return word\r
379     end\r
380     rules = @rules[:italian]\r
381     min = rules[:first] if min.empty?\r
382     max = rules[:last]  if max.empty?\r
383     debug "looking for word between #{min.inspect} and #{max.inspect}"\r
384     return word if min.empty? or max.empty?\r
385     begin\r
386       while (word <= min or word >= max or word !~ /^[a-z]+$/)\r
387         debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"\r
388         # TODO for the time being, skip words with extended characters\r
389         unless @wordcache.key?(:italian)\r
390           @wordcache[:italian] = Hash.new\r
391         end\r
392         wc = @wordcache[:italian]\r
393 \r
394         if wc.size > 0\r
395           cache_or_url = rand(2)\r
396           if cache_or_url == 0\r
397             debug "getting word from wordcache"\r
398             word = wc.keys[rand(wc.size)].to_s\r
399             next\r
400           end\r
401         end\r
402 \r
403         # TODO when doing ranges, adapt this choice\r
404         l = ('a'..'z').to_a[rand(26)]\r
405         debug "getting random word from dictionary, starting with letter #{l}"\r
406         first = rules[:url] % "lettera_#{l}_0_50"\r
407         p = @bot.httputil.get(first)\r
408         max_page = p.match(/ \/ (\d+)<\/label>/)[1].to_i\r
409         pp = rand(max_page)+1\r
410         debug "getting random word from dictionary, starting with letter #{l}, page #{pp}"\r
411         p = @bot.httputil.get(first+"&pagina=#{pp}") if pp > 1\r
412         lemmi = Array.new\r
413         good = rules[:good]\r
414         bad =  rules[:bad]\r
415         # We look for a lemma composed by a single word and of length at least two\r
416         p.scan(/<li><a href="([^"]+?)" title="consulta il lemma ([^ "][^ "]+?)">.*?&nbsp;(.+?)<\/li>/) { |url, prelemma, tipo|\r
417           lemma = prelemma.downcase.to_sym\r
418           debug "checking lemma #{lemma} (#{prelemma}) of type #{tipo} from url #{url}"\r
419           next if wc.key?(lemma)\r
420           case tipo\r
421           when good\r
422             if tipo =~ bad\r
423               debug "refusing, #{bad}"\r
424               next\r
425             end\r
426             debug "good one"\r
427             lemmi << lemma\r
428             wc[lemma] = {:who => :dict}\r
429           else\r
430             debug "refusing, not #{good}"\r
431           end\r
432         }\r
433         word = lemmi[rand(lemmi.length)].to_s\r
434       end\r
435     rescue => e\r
436       error "error #{e.inspect} while looking up a word"\r
437       error e.backtrace.join("\n")\r
438     end\r
439     return word\r
440   end\r
441 \r
442   def is_english?(word)\r
443     unless @wordcache.key?(:english)\r
444       @wordcache[:english] = Hash.new\r
445     end\r
446     wc = @wordcache[:english]\r
447     return true if wc.key?(word.to_sym)\r
448     rules = @rules[:english]\r
449     p = @bot.httputil.get(rules[:url] % CGI.escape(word))\r
450     if not p\r
451       error "could not connect!"\r
452       return false\r
453     end\r
454     debug p\r
455     if p =~ /<span class="(?:hwd|srch)">#{word}<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i\r
456       debug "new word #{word}"\r
457         wc[word.to_sym] = {:who => :dict}\r
458         return true\r
459     end\r
460     return false\r
461   end\r
462 \r
463   def random_pick_english(min=nil,max=nil)\r
464     # Try to pick a random word between min and max\r
465     word = String.new\r
466     min = min.to_s\r
467     max = max.to_s\r
468     if min > max\r
469       m.reply "#{min} > #{max}"\r
470       return word\r
471     end\r
472     rules = @rules[:english]\r
473     min = rules[:first] if min.empty?\r
474     max = rules[:last]  if max.empty?\r
475     debug "looking for word between #{min.inspect} and #{max.inspect}"\r
476     return word if min.empty? or max.empty?\r
477     begin\r
478       while (word <= min or word >= max or word !~ /^[a-z]+$/)\r
479         debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"\r
480         # TODO for the time being, skip words with extended characters\r
481         unless @wordcache.key?(:english)\r
482           @wordcache[:english] = Hash.new\r
483         end\r
484         wc = @wordcache[:english]\r
485 \r
486         if wc.size > 0\r
487           cache_or_url = rand(2)\r
488           if cache_or_url == 0\r
489             debug "getting word from wordcache"\r
490             word = wc.keys[rand(wc.size)].to_s\r
491             next\r
492           end\r
493         end\r
494 \r
495         # TODO when doing ranges, adapt this choice\r
496         l = ('a'..'z').to_a[rand(26)]\r
497         ll = ('a'..'z').to_a[rand(26)]\r
498         random = [l,ll].join('*') + '*'\r
499         debug "getting random word from dictionary, matching #{random}"\r
500         p = @bot.httputil.get(rules[:url] % CGI.escape(random))\r
501         debug p\r
502         lemmi = Array.new\r
503         good = rules[:good]\r
504         # We look for a lemma composed by a single word and of length at least two\r
505         p.scan(/<span class="(?:hwd|srch)">(.*?)<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i) { |prelemma, discard|\r
506           lemma = prelemma.downcase\r
507           debug "checking lemma #{lemma} (#{prelemma}) and discarding #{discard}"\r
508           next if wc.key?(lemma.to_sym)\r
509           if lemma =~ /^[a-z]+$/\r
510             debug "good one"\r
511             lemmi << lemma\r
512             wc[lemma.to_sym] = {:who => :dict}\r
513           else\r
514             debug "funky characters, not good"\r
515           end\r
516         }\r
517         next if lemmi.empty?\r
518         word = lemmi[rand(lemmi.length)]\r
519       end\r
520     rescue => e\r
521       error "error #{e.inspect} while looking up a word"\r
522       error e.backtrace.join("\n")\r
523     end\r
524     return word\r
525   end\r
526 \r
527   def help(plugin, topic="")\r
528     case topic\r
529     when 'manage'\r
530       return _("az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)")\r
531     when 'cancel'\r
532       return _("az cancel => abort current game")\r
533     when 'check'\r
534       return _('az check <word> => checks <word> against current game')\r
535     when 'rules'\r
536       return _("try to guess the word the bot is thinking of; if you guess wrong, the bot will use the new word to restrict the range of allowed words: eventually, the range will be so small around the correct word that you can't miss it")\r
537     when 'play'\r
538       return _("az => start a game if none is running, show the current word range otherwise; you can say 'az <language>' if you want to play in a language different from the current bot default")\r
539     end\r
540     return _("az topics: play, rules, cancel, manage, check")\r
541   end\r
542 \r
543 end\r
544 \r
545 plugin = AzGamePlugin.new\r
546 plugin.map 'az [:lang] word :cmd *params', :action=>'wordlist', :defaults => { :lang => nil, :cmd => 'count', :params => [] }, :auth_path => '!az::edit!'\r
547 plugin.map 'az cancel', :action=>'stop_game', :private => false\r
548 plugin.map 'az check :word', :action => 'manual_word_check', :private => false\r
549 plugin.map 'az [play] [:lang]', :action=>'start_game', :private => false, :defaults => { :lang => nil }\r
550 \r