4 # :title: A-Z Game Plugin for rbot
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Author:: Yaohan Chen <yaohan.chen@gmail.com>: Japanese support
9 # Copyright:: (C) 2006 Giuseppe Bilotta
10 # Copyright:: (C) 2007 GIuseppe Bilotta, Yaohan Chen
14 # A-Z Game: guess the word by reducing the interval of allowed ones
16 # TODO allow manual addition of words
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)
28 @range = [@rules[:first].dup, @rules[:last].dup]
29 @listener = @rules[:listener]
31 @total_failed = 0 # not used, reported, updated
33 @failed = Hash.new(0) # not used, not reported, updated
36 return "%s -- %s" % self
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
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]}"
51 File.open(@rules[:addfile], "a") do |f|
55 error "failed to add #{w} to #{@rules[:addfile]}"
63 @check_method = "is_#{@lang}?"
64 @check = Proc.new { |w| @plugin.send(@check_method, w) }
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)
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)
86 elsif w > @word and w < @range.last
87 @range.last.replace(w)
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
101 p = @tries.keys.length
102 t = (100*exp(-((n-1)**2)/(50.0**2))).ceil + p
103 debug "Total score: #{t}"
106 ret[k] = [t*a/n, n_("%{count} try", "%{count} tries", a) % {:count => a}]
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}]
113 return ret.sort_by { |h| h.last.first }.reverse
118 class AzGamePlugin < Plugin
122 # if @registry.has_key?(:games)
123 # @games = @registry[:games]
127 if @registry.has_key?(:wordcache) and @registry[:wordcache]
128 @wordcache = @registry[:wordcache]
130 @wordcache = Hash.new
132 debug "A-Z wordcache: #{@wordcache.pretty_inspect}"
136 :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.
139 :last => 'zuzzurellone',
140 :url => "http://www.demauroparavia.it/%s",
141 :wapurl => "http://wap.demauroparavia.it/index.php?lemma=%s",
142 :listener => /^[a-z]+$/
145 :good => /(?:singular )?noun|verb|adj/,
148 :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st",
149 :listener => /^[a-z]+$/
153 @autoadd_base = datafile "autoadd-"
156 def initialize_wordlist(params)
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}
168 if(words.length >= 4) # something to guess
178 debug "#{lang} wordlist loaded, #{rules[:list].length} lines; first word: #{rules[:first]}, last word: #{rules[:last]}"
186 # @registry[:games] = @games
187 @registry[:wordcache] = @wordcache
191 return if m.channel.nil? or m.address?
192 k = m.channel.downcase.to_s # to_sym?
193 return unless @games.key?(k)
195 word = m.plugin.downcase
196 return unless word =~ @games[k].listener
197 word_check(m, k, word)
200 def word_check(m, k, word)
201 # Not really safe ... what happens
203 isit = @games[k].check(word)
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)
213 m.reply _("The game was won after %{tries} tries. Scores for this game: %{scores}") % {:tries => @games[k].total_tries, :scores => ar.join('; ')}
216 m.reply _("%{word} is not in the range %{bold}%{range}%{bold}") % {:word => word, :bold => Bold, :range => isit.last} if m.address?
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
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
230 m.reply _("%{word} is already one of the range extrema: %{range}") % {:word => word, :range => isit.last} if m.address?
232 m.reply _("hm, something went wrong while verifying %{word}")
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?")
245 m.reply _("I only accept single words composed by letters only, sorry")
248 word_check(m, k, word)
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?
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)
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('; ')}
262 m.reply _("no A-Z game running in this channel ...")
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)
276 m.reply _("couldn't think of anything ...")
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)
284 m.reply _("couldn't think of anything ...")
288 @games[k] = AzGame.new(self, lang, rules, word)
290 m.reply _("I can't play A-Z in %{lang}, sorry") % {:lang => lang}
294 tr = @games[k].total_tries
295 # this message building code is rewritten to make translation easier
299 f_tr = @games[k].total_failed
301 tr_msg = _(" (after %{total_tries} and %{invalid_tries})") %
302 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
304 :invalid_tries => n_("%{count} invalid try", "%{count} invalid tries", tr) %
307 tr_msg = _(" (after %{total_tries})") %
308 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
313 m.reply _("A-Z: %{bold}%{range}%{bold}") % {:bold => Bold, :range => @games[k].range} + tr_msg
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
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}
327 m.reply _("provide a regexp to match")
332 matches = wc.keys.map { |k|
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]}
343 m.reply "#{matches.join(', ')}"
347 m.reply _("provide a word")
350 word = pars[0].downcase.to_sym
352 m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}
355 if wc[word].key?(:when)
356 tr = _("%{word} learned from %{user} on %{date}") % {:word => word, :user => wc[word][:who], :date => wc[word][:when]}
358 tr = _("%{word} learned from %{user}") % {:word => word, :user => wc[word][:who]}
363 m.reply _("provide a word")
366 word = pars[0].downcase.to_sym
368 m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}
375 m.reply _("provide a word")
378 word = pars[0].downcase.to_sym
380 m.reply _("I already know the %{lang} word %{word}")
383 wc[word] = { :who => m.sourcenick, :when => Time.now }
389 # return integer between min and max, inclusive
390 def rand_between(min, max)
391 rand(max - min + 1) + min
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}"
408 def is_italian?(word)
409 unless @wordcache.key?(:italian)
410 @wordcache[:italian] = Hash.new
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)
417 error "could not connect!"
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}
432 def random_pick_italian(min=nil,max=nil)
433 # Try to pick a random word between min and max
438 m.reply "#{min} > #{max}"
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?
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
453 wc = @wordcache[:italian]
456 cache_or_url = rand(2)
458 debug "getting word from wordcache"
459 word = wc.keys[rand(wc.size)].to_s
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
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 ([^ "][^ "]+?)">.*? (.+?)<\/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)
484 debug "refusing, #{bad}"
489 wc[lemma] = {:who => :dict}
491 debug "refusing, not #{good}"
494 word = lemmi[rand(lemmi.length)].to_s
497 error "error #{e.inspect} while looking up a word"
498 error e.backtrace.join("\n")
503 def is_english?(word)
504 unless @wordcache.key?(:english)
505 @wordcache[:english] = Hash.new
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))
512 error "could not connect!"
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}
524 def random_pick_english(min=nil,max=nil)
525 # Try to pick a random word between min and max
530 m.reply "#{min} > #{max}"
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?
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
545 wc = @wordcache[:english]
548 cache_or_url = rand(2)
550 debug "getting word from wordcache"
551 word = wc.keys[rand(wc.size)].to_s
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))
565 # We look for a lemma composed by a single word and of length at least two
566 p.scan(/<span class="(?:hwd|srch)">(.*?)<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i) { |prelemma, discard|
567 lemma = prelemma.downcase
568 debug "checking lemma #{lemma} (#{prelemma}) and discarding #{discard}"
569 next if wc.key?(lemma.to_sym)
570 if lemma =~ /^[a-z]+$/
573 wc[lemma.to_sym] = {:who => :dict}
575 debug "funky characters, not good"
579 word = lemmi[rand(lemmi.length)]
582 error "error #{e.inspect} while looking up a word"
583 error e.backtrace.join("\n")
588 def help(plugin, topic="")
591 return _("az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)")
593 return _("az cancel => abort current game")
595 return _('az check <word> => checks <word> against current game')
597 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 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")
604 _("az topics: play, rules, cancel, manage, check"),
605 _("available languages: %{langs}") % { :langs => langs.join(", ") },
606 wls.empty? ? nil : _("available wordlists: %{wls}") % { :wls => wls.join(", ") },
613 plugin = AzGamePlugin.new
614 plugin.map 'az [:lang] word :cmd *params', :action=>'wordlist', :defaults => { :lang => nil, :cmd => 'count', :params => [] }, :auth_path => '!az::edit!'
615 plugin.map 'az cancel', :action=>'stop_game', :private => false
616 plugin.map 'az check :word', :action => 'manual_word_check', :private => false
617 plugin.map 'az [play] [:lang] [autoadd :addlang]', :action=>'start_game', :private => false, :defaults => { :lang => nil, :addlang => nil }