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 = Proc.new { |w| @rules[:list].include?(w) }
41 @check_method = "is_#{@lang}?"
42 @check = Proc.new { |w| @plugin.send(@check_method, w) }
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)
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)
64 elsif w > @word and w < @range.last
65 @range.last.replace(w)
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
79 p = @tries.keys.length
80 t = (100*exp(-((n-1)**2)/(50.0**2))).ceil + p
81 debug "Total score: #{t}"
84 ret[k] = [t*a/n, n_("%{count} try", "%{count} tries", a) % {:count => a}]
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}]
91 return ret.sort_by { |h| h.last.first }.reverse
96 class AzGamePlugin < Plugin
100 # if @registry.has_key?(:games)
101 # @games = @registry[:games]
105 if @registry.has_key?(:wordcache) and @registry[:wordcache]
106 @wordcache = @registry[:wordcache]
108 @wordcache = Hash.new
110 debug "A-Z wordcache: #{@wordcache.pretty_inspect}"
114 :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.
117 :last => 'zuzzurellone',
118 :url => "http://www.demauroparavia.it/%s",
119 :wapurl => "http://wap.demauroparavia.it/index.php?lemma=%s",
120 :listener => /^[a-z]+$/
123 :good => /(?:singular )?noun|verb|adj/,
126 :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st",
127 :listener => /^[a-z]+$/
131 @wordlist_base = "#{@bot.botclass}/azgame/wordlist-"
134 def initialize_wordlist(lang)
135 wordlist = @wordlist_base + lang.to_s
136 if File.exist?(wordlist)
137 words = File.readlines(wordlist).map {|line| line.strip}.uniq
138 if(words.length >= 4) # something to guess
146 debug "#{lang} wordlist loaded, #{rules[:list].length} lines; first word: #{rules[:first]}, last word: #{rules[:last]}"
154 # @registry[:games] = @games
155 @registry[:wordcache] = @wordcache
159 return if m.channel.nil? or m.address?
160 k = m.channel.downcase.to_s # to_sym?
161 return unless @games.key?(k)
163 word = m.plugin.downcase
164 return unless word =~ @games[k].listener
165 word_check(m, k, word)
168 def word_check(m, k, word)
169 # Not really safe ... what happens
171 isit = @games[k].check(word)
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)
181 m.reply _("The game was won after %{tries} tries. Scores for this game: %{scores}") % {:tries => @games[k].total_tries, :scores => ar.join('; ')}
184 m.reply _("%{word} is not in the range %{bold}%{range}%{bold}") % {:word => word, :bold => Bold, :range => isit.last} if m.address?
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
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
198 m.reply _("%{word} is already one of the range extrema: %{range}") % {:word => word, :range => isit.last} if m.address?
200 m.reply _("hm, something went wrong while verifying %{word}")
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?")
213 m.reply _("I only accept single words composed by letters only, sorry")
216 word_check(m, k, word)
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?
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)
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('; ')}
230 m.reply _("no A-Z game running in this channel ...")
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)
244 m.reply _("couldn't think of anything ...")
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)
252 m.reply _("couldn't think of anything ...")
256 @games[k] = AzGame.new(self, lang, rules, word)
258 m.reply _("I can't play A-Z in %{lang}, sorry") % {:lang => lang}
262 tr = @games[k].total_tries
263 # this message building code is rewritten to make translation easier
267 f_tr = @games[k].total_failed
269 tr_msg = _(" (after %{total_tries} and %{invalid_tries})") %
270 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
272 :invalid_tries => n_("%{count} invalid try", "%{count} invalid tries", tr) %
275 tr_msg = _(" (after %{total_tries})") %
276 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
281 m.reply _("A-Z: %{bold}%{range}%{bold}") % {:bold => Bold, :range => @games[k].range} + tr_msg
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
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}
295 m.reply _("provide a regexp to match")
300 matches = wc.keys.map { |k|
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]}
311 m.reply "#{matches.join(', ')}"
315 m.reply _("provide a word")
318 word = pars[0].downcase.to_sym
320 m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}
323 if wc[word].key?(:when)
324 tr = _("%{word} learned from %{user} on %{date}") % {:word => word, :user => wc[word][:who], :date => wc[word][:when]}
326 tr = _("%{word} learned from %{user}") % {:word => word, :user => wc[word][:who]}
331 m.reply _("provide a word")
334 word = pars[0].downcase.to_sym
336 m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}
343 m.reply _("provide a word")
346 word = pars[0].downcase.to_sym
348 m.reply _("I already know the %{lang} word %{word}")
351 wc[word] = { :who => m.sourcenick, :when => Time.now }
357 # return integer between min and max, inclusive
358 def rand_between(min, max)
359 rand(max - min + 1) + min
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}"
376 def is_italian?(word)
377 unless @wordcache.key?(:italian)
378 @wordcache[:italian] = Hash.new
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)
385 error "could not connect!"
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}
400 def random_pick_italian(min=nil,max=nil)
401 # Try to pick a random word between min and max
406 m.reply "#{min} > #{max}"
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?
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
421 wc = @wordcache[:italian]
424 cache_or_url = rand(2)
426 debug "getting word from wordcache"
427 word = wc.keys[rand(wc.size)].to_s
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
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 ([^ "][^ "]+?)">.*? (.+?)<\/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)
452 debug "refusing, #{bad}"
457 wc[lemma] = {:who => :dict}
459 debug "refusing, not #{good}"
462 word = lemmi[rand(lemmi.length)].to_s
465 error "error #{e.inspect} while looking up a word"
466 error e.backtrace.join("\n")
471 def is_english?(word)
472 unless @wordcache.key?(:english)
473 @wordcache[:english] = Hash.new
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))
480 error "could not connect!"
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}
492 def random_pick_english(min=nil,max=nil)
493 # Try to pick a random word between min and max
498 m.reply "#{min} > #{max}"
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?
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
513 wc = @wordcache[:english]
516 cache_or_url = rand(2)
518 debug "getting word from wordcache"
519 word = wc.keys[rand(wc.size)].to_s
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))
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]+$/
541 wc[lemma.to_sym] = {:who => :dict}
543 debug "funky characters, not good"
547 word = lemmi[rand(lemmi.length)]
550 error "error #{e.inspect} while looking up a word"
551 error e.backtrace.join("\n")
556 def help(plugin, topic="")
559 return _("az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)")
561 return _("az cancel => abort current game")
563 return _('az check <word> => checks <word> against current game')
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")
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")
569 offset = @wordlist_base.length
571 wls = Dir.glob(@wordlist_base + "*").map { |f| f[offset,f.length].intern rescue nil }.compact - langs
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(", ") },
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 }