4 # :title: A-Z Game Plugin for rbot
\r
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
\r
7 # Author:: Yaohan Chen <yaohan.chen@gmail.com>: Japanese support
\r
9 # Copyright:: (C) 2006 Giuseppe Bilotta
\r
10 # Copyright:: (C) 2007 GIuseppe Bilotta, Yaohan Chen
\r
14 # A-Z Game: guess the word by reducing the interval of allowed ones
\r
16 # TODO allow manual addition of words
\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
26 @word = word.downcase
\r
28 @range = [@rules[:first].dup, @rules[:last].dup]
\r
29 @listener = @rules[:listener]
\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
36 return "%s -- %s" % self
\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
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
55 return [:out, @range]
\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
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
70 @tries.each { |k, a|
\r
71 ret[k] = [t*a/n, n_("%{count} try", "%{count} tries", a) % {:count => a}]
\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
78 return ret.sort_by { |h| h.last.first }.reverse
\r
83 class AzGamePlugin < Plugin
\r
87 # if @registry.has_key?(:games)
\r
88 # @games = @registry[:games]
\r
92 if @registry.has_key?(:wordcache) and @registry[:wordcache]
\r
93 @wordcache = @registry[:wordcache]
\r
95 @wordcache = Hash.new
\r
97 debug "A-Z wordcache: #{@wordcache.pretty_inspect}"
\r
101 :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.
\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
110 :good => /(?:singular )?noun|verb|adj/,
\r
111 :first => 'abacus',
\r
113 :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st",
\r
114 :listener => /^[a-z]+$/
\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
126 :first => words[0],
\r
127 :last => words[-1],
\r
128 :listener => /^\S+$/
\r
130 debug "Japanese wordlist loaded, #{@rules[:japanese][:list].length} lines; first word: #{@rules[:japanese][:first]}, last word: #{@rules[:japanese][:last]}"
\r
136 # @registry[:games] = @games
\r
137 @registry[:wordcache] = @wordcache
\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
146 word = m.plugin.downcase
\r
147 return unless word =~ @games[k].listener
\r
148 word_check(m, k, word)
\r
151 def word_check(m, k, word)
\r
152 # Not really safe ... what happens
\r
154 isit = @games[k].check(word)
\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
164 m.reply _("The game was won after %{tries} tries. Scores for this game: %{scores}") % {:tries => @games[k].total_tries, :scores => ar.join('; ')}
\r
167 m.reply _("%{word} is not in the range %{bold}%{range}%{bold}") % {:word => word, :bold => Bold, :range => isit.last} if m.address?
\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
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
177 m.reply _("%{word} is already one of the range extrema: %{range}") % {:word => word, :range => isit.last} if m.address?
\r
179 m.reply _("hm, something went wrong while verifying %{word}")
\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
192 m.reply _("I only accept single words composed by letters only, sorry")
\r
195 word_check(m, k, word)
\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
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
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
209 m.reply _("no A-Z game running in this channel ...")
\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
223 m.reply _("couldn't think of anything ...")
\r
227 m.reply _("I can't play A-Z in %{lang}, sorry") % {:lang => lang}
\r
230 m.reply _("got it!")
\r
231 @games[k] = AzGame.new(self, lang, @rules[lang], word)
\r
233 tr = @games[k].total_tries
\r
234 # this message building code is rewritten to make translation easier
\r
238 f_tr = @games[k].total_failed
\r
240 tr_msg = _(" (after %{total_tries} and %{invalid_tries})") %
\r
241 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
\r
243 :invalid_tries => n_("%{count} invalid try", "%{count} invalid tries", tr) %
\r
246 tr_msg = _(" (after %{total_tries}") %
\r
247 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
\r
252 m.reply _("A-Z: %{bold}%{range}%{bold}") % {:bold => Bold, :range => @games[k].range} + tr_msg
\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
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
266 m.reply _("provide a regexp to match")
\r
270 regex = /#{pars[0]}/
\r
271 matches = wc.keys.map { |k|
\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
282 m.reply "#{matches.join(', ')}"
\r
286 m.reply _("provide a word")
\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
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
297 tr = _("%{word} learned from %{user}") % {:word => word, :user => wc[word][:who]}
\r
302 m.reply _("provide a word")
\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
311 @bot.okay m.replyto
\r
314 m.reply _("provide a word")
\r
317 word = pars[0].downcase.to_sym
\r
319 m.reply _("I already know the %{lang} word %{word}")
\r
322 wc[word] = { :who => m.sourcenick, :when => Time.now }
\r
323 @bot.okay m.replyto
\r
328 def is_japanese?(word)
\r
329 @rules[:japanese][:list].include?(word)
\r
332 # return integer between min and max, inclusive
\r
333 def rand_between(min, max)
\r
334 rand(max - min + 1) + min
\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
352 def is_italian?(word)
\r
353 unless @wordcache.key?(:italian)
\r
354 @wordcache[:italian] = Hash.new
\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
361 error "could not connect!"
\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
376 def random_pick_italian(min=nil,max=nil)
\r
377 # Try to pick a random word between min and max
\r
382 m.reply "#{min} > #{max}"
\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
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
397 wc = @wordcache[:italian]
\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
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
418 good = rules[:good]
\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 ([^ "][^ "]+?)">.*? (.+?)<\/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
428 debug "refusing, #{bad}"
\r
433 wc[lemma] = {:who => :dict}
\r
435 debug "refusing, not #{good}"
\r
438 word = lemmi[rand(lemmi.length)].to_s
\r
441 error "error #{e.inspect} while looking up a word"
\r
442 error e.backtrace.join("\n")
\r
447 def is_english?(word)
\r
448 unless @wordcache.key?(:english)
\r
449 @wordcache[:english] = Hash.new
\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
456 error "could not connect!"
\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
468 def random_pick_english(min=nil,max=nil)
\r
469 # Try to pick a random word between min and max
\r
474 m.reply "#{min} > #{max}"
\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
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
489 wc = @wordcache[:english]
\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
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
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
517 wc[lemma.to_sym] = {:who => :dict}
\r
519 debug "funky characters, not good"
\r
522 next if lemmi.empty?
\r
523 word = lemmi[rand(lemmi.length)]
\r
526 error "error #{e.inspect} while looking up a word"
\r
527 error e.backtrace.join("\n")
\r
532 def help(plugin, topic="")
\r
535 return _("az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)")
\r
537 return _("az cancel => abort current game")
\r
539 return _('az check <word> => checks <word> against current game')
\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
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
545 return _("az topics: play, rules, cancel, manage, check")
\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