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