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