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