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 # Since we're called threaded, bail out early if a winner
\r
44 # was assigned already
\r
45 return [:ignore, nil] if @winner
\r
46 return [:bingo, nil] if w == @word
\r
47 return [:out, @range] if w < @range.first or w > @range.last
\r
48 return [:ignore, @range] if w == @range.first or w == @range.last
\r
49 # This is potentially slow (for languages that check online)
\r
50 return [:noexist, @range] unless @plugin.send("is_#{@lang}?", w)
\r
52 # Check again if there was a winner in the mean time,
\r
53 # and bail out if there was
\r
54 return [:ignore, nil] if @winner
\r
55 if w < @word and w > @range.first
\r
56 @range.first.replace(w)
\r
57 return [:in, @range]
\r
58 elsif w > @word and w < @range.last
\r
59 @range.last.replace(w)
\r
60 return [:in, @range]
\r
62 return [:out, @range]
\r
65 # TODO scoring: base score is t = ceil(100*exp(-((n-1)^2)/(50^2)))+p for n attempts
\r
66 # done by p players; players that didn't win but contributed
\r
67 # with a attempts will get t*a/n points
\r
73 p = @tries.keys.length
\r
74 t = (100*exp(-((n-1)**2)/(50.0**2))).ceil + p
\r
75 debug "Total score: #{t}"
\r
77 @tries.each { |k, a|
\r
78 ret[k] = [t*a/n, n_("%{count} try", "%{count} tries", a) % {:count => a}]
\r
81 debug "replacing winner score of %d with %d" % [ret[@winner].first, t]
\r
82 tries = ret[@winner].last
\r
83 ret[@winner] = [t, _("winner, %{tries}") % {:tries => tries}]
\r
85 return ret.sort_by { |h| h.last.first }.reverse
\r
90 class AzGamePlugin < Plugin
\r
94 # if @registry.has_key?(:games)
\r
95 # @games = @registry[:games]
\r
99 if @registry.has_key?(:wordcache) and @registry[:wordcache]
\r
100 @wordcache = @registry[:wordcache]
\r
102 @wordcache = Hash.new
\r
104 debug "A-Z wordcache: #{@wordcache.pretty_inspect}"
\r
108 :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.
\r
111 :last => 'zuzzurellone',
\r
112 :url => "http://www.demauroparavia.it/%s",
\r
113 :wapurl => "http://wap.demauroparavia.it/index.php?lemma=%s",
\r
114 :listener => /^[a-z]+$/
\r
117 :good => /(?:singular )?noun|verb|adj/,
\r
118 :first => 'abacus',
\r
120 :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st",
\r
121 :listener => /^[a-z]+$/
\r
125 japanese_wordlist = "#{@bot.botclass}/azgame/wordlist-japanese"
\r
126 if File.exist?(japanese_wordlist)
\r
127 words = File.readlines(japanese_wordlist) \
\r
128 .map {|line| line.strip} .uniq
\r
129 if(words.length >= 4) # something to guess
\r
130 @rules[:japanese] = {
\r
133 :first => words[0],
\r
134 :last => words[-1],
\r
135 :listener => /^\S+$/
\r
137 debug "Japanese wordlist loaded, #{@rules[:japanese][:list].length} lines; first word: #{@rules[:japanese][:first]}, last word: #{@rules[:japanese][:last]}"
\r
143 # @registry[:games] = @games
\r
144 @registry[:wordcache] = @wordcache
\r
148 return unless m.kind_of?(PrivMessage)
\r
149 return if m.channel.nil? or m.address?
\r
150 k = m.channel.downcase.to_s # to_sym?
\r
151 return unless @games.key?(k)
\r
153 word = m.plugin.downcase
\r
154 return unless word =~ @games[k].listener
\r
155 word_check(m, k, word)
\r
158 def word_check(m, k, word)
\r
159 # Not really safe ... what happens
\r
161 isit = @games[k].check(word)
\r
164 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
165 @games[k].total_tries += 1
\r
166 @games[k].tries[m.source] += 1
\r
167 @games[k].winner = m.source
\r
168 ar = @games[k].score.inject([]) { |res, kv|
\r
169 res.push("%s: %d (%s)" % kv.flatten)
\r
171 m.reply _("The game was won after %{tries} tries. Scores for this game: %{scores}") % {:tries => @games[k].total_tries, :scores => ar.join('; ')}
\r
174 m.reply _("%{word} is not in the range %{bold}%{range}%{bold}") % {:word => word, :bold => Bold, :range => isit.last} if m.address?
\r
176 # bail out early if the game was won in the mean time
\r
177 return if !@games[k] or @games[k].winner
\r
178 m.reply _("%{word} doesn't exist or is not acceptable for the game") % {:word => word}
\r
179 @games[k].total_failed += 1
\r
180 @games[k].failed[m.source] += 1
\r
182 # bail out early if the game was won in the mean time
\r
183 return if !@games[k] or @games[k].winner
\r
184 m.reply _("close, but no cigar. New range: %{bold}%{range}%{bold}") % {:bold => Bold, :range => isit.last}
\r
185 @games[k].total_tries += 1
\r
186 @games[k].tries[m.source] += 1
\r
188 m.reply _("%{word} is already one of the range extrema: %{range}") % {:word => word, :range => isit.last} if m.address?
\r
190 m.reply _("hm, something went wrong while verifying %{word}")
\r
195 def manual_word_check(m, params)
\r
196 k = m.channel.downcase.to_s
\r
197 word = params[:word].downcase
\r
198 if not @games.key?(k)
\r
199 m.reply _("no A-Z game running here, can't check if %{word} is valid, can I?")
\r
203 m.reply _("I only accept single words composed by letters only, sorry")
\r
206 word_check(m, k, word)
\r
209 def stop_game(m, params)
\r
210 return if m.channel.nil? # Shouldn't happen, but you never know
\r
211 k = m.channel.downcase.to_s # to_sym?
\r
213 m.reply _("the word in %{bold}%{range}%{bold} was: %{bold}%{word}%{bold}") % {:bold => Bold, :range => @games[k].range, :word => @games[k].word}
\r
214 ar = @games[k].score.inject([]) { |res, kv|
\r
215 res.push("%s: %d (%s)" % kv.flatten)
\r
217 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
220 m.reply _("no A-Z game running in this channel ...")
\r
224 def start_game(m, params)
\r
225 return if m.channel.nil? # Shouldn't happen, but you never know
\r
226 k = m.channel.downcase.to_s # to_sym?
\r
227 unless @games.key?(k)
\r
228 lang = (params[:lang] || @bot.config['core.language']).to_sym
\r
229 method = 'random_pick_'+lang.to_s
\r
230 m.reply _("let me think ...")
\r
231 if @rules.has_key?(lang) and self.respond_to?(method)
\r
232 word = self.send(method)
\r
234 m.reply _("couldn't think of anything ...")
\r
238 m.reply _("I can't play A-Z in %{lang}, sorry") % {:lang => lang}
\r
241 m.reply _("got it!")
\r
242 @games[k] = AzGame.new(self, lang, @rules[lang], word)
\r
244 tr = @games[k].total_tries
\r
245 # this message building code is rewritten to make translation easier
\r
249 f_tr = @games[k].total_failed
\r
251 tr_msg = _(" (after %{total_tries} and %{invalid_tries})") %
\r
252 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
\r
254 :invalid_tries => n_("%{count} invalid try", "%{count} invalid tries", tr) %
\r
257 tr_msg = _(" (after %{total_tries})") %
\r
258 { :total_tries => n_("%{count} try", "%{count} tries", tr) %
\r
263 m.reply _("A-Z: %{bold}%{range}%{bold}") % {:bold => Bold, :range => @games[k].range} + tr_msg
\r
267 def wordlist(m, params)
\r
268 pars = params[:params]
\r
269 lang = (params[:lang] || @bot.config['core.language']).to_sym
\r
270 wc = @wordcache[lang] || Hash.new rescue Hash.new
\r
271 cmd = params[:cmd].to_sym rescue :count
\r
274 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
277 m.reply _("provide a regexp to match")
\r
281 regex = /#{pars[0]}/
\r
282 matches = wc.keys.map { |k|
\r
288 if matches.size == 0
\r
289 m.reply _("no %{lang} word I know match %{pattern}") % {:lang => lang, :pattern => pars[0]}
\r
290 elsif matches.size > 25
\r
291 m.reply _("more than 25 %{lang} words I know match %{pattern}, try a stricter matching") % {:lang => lang, :pattern => pars[0]}
\r
293 m.reply "#{matches.join(', ')}"
\r
297 m.reply _("provide a word")
\r
300 word = pars[0].downcase.to_sym
\r
301 if not wc.key?(word)
\r
302 m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}
\r
305 if wc[word].key?(:when)
\r
306 tr = _("%{word} learned from %{user} on %{date}") % {:word => word, :user => wc[word][:who], :date => wc[word][:when]}
\r
308 tr = _("%{word} learned from %{user}") % {:word => word, :user => wc[word][:who]}
\r
313 m.reply _("provide a word")
\r
316 word = pars[0].downcase.to_sym
\r
317 if not wc.key?(word)
\r
318 m.reply _("I don't know any %{lang} word %{word}") % {:lang => lang, :word => word}
\r
322 @bot.okay m.replyto
\r
325 m.reply _("provide a word")
\r
328 word = pars[0].downcase.to_sym
\r
330 m.reply _("I already know the %{lang} word %{word}")
\r
333 wc[word] = { :who => m.sourcenick, :when => Time.now }
\r
334 @bot.okay m.replyto
\r
339 def is_japanese?(word)
\r
340 @rules[:japanese][:list].include?(word)
\r
343 # return integer between min and max, inclusive
\r
344 def rand_between(min, max)
\r
345 rand(max - min + 1) + min
\r
348 def random_pick_japanese(min=nil, max=nil)
\r
349 rules = @rules[:japanese]
\r
350 min = rules[:first] if min.nil_or_empty?
\r
351 max = rules[:last] if max.nil_or_empty?
\r
352 debug "Randomly picking word between #{min} and #{max}"
\r
353 min_index = rules[:list].index(min)
\r
354 max_index = rules[:list].index(max)
\r
355 debug "Index between #{min_index} and #{max_index}"
\r
356 index = rand_between(min_index + 1, max_index - 1)
\r
357 debug "Index generated: #{index}"
\r
358 word = rules[:list][index]
\r
359 debug "Randomly picked #{word}"
\r
363 def is_italian?(word)
\r
364 unless @wordcache.key?(:italian)
\r
365 @wordcache[:italian] = Hash.new
\r
367 wc = @wordcache[:italian]
\r
368 return true if wc.key?(word.to_sym)
\r
369 rules = @rules[:italian]
\r
370 p = @bot.httputil.get(rules[:wapurl] % word, :open_timeout => 60, :read_timeout => 60)
\r
372 error "could not connect!"
\r
376 p.scan(/<anchor>#{word} - (.*?)<go href="lemma.php\?ID=([^"]*?)"/) { |qual, url|
\r
377 debug "new word #{word} of type #{qual}"
\r
378 if qual =~ rules[:good] and qual !~ rules[:bad]
\r
379 wc[word.to_sym] = {:who => :dict}
\r
387 def random_pick_italian(min=nil,max=nil)
\r
388 # Try to pick a random word between min and max
\r
393 m.reply "#{min} > #{max}"
\r
396 rules = @rules[:italian]
\r
397 min = rules[:first] if min.empty?
\r
398 max = rules[:last] if max.empty?
\r
399 debug "looking for word between #{min.inspect} and #{max.inspect}"
\r
400 return word if min.empty? or max.empty?
\r
402 while (word <= min or word >= max or word !~ /^[a-z]+$/)
\r
403 debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"
\r
404 # TODO for the time being, skip words with extended characters
\r
405 unless @wordcache.key?(:italian)
\r
406 @wordcache[:italian] = Hash.new
\r
408 wc = @wordcache[:italian]
\r
411 cache_or_url = rand(2)
\r
412 if cache_or_url == 0
\r
413 debug "getting word from wordcache"
\r
414 word = wc.keys[rand(wc.size)].to_s
\r
419 # TODO when doing ranges, adapt this choice
\r
420 l = ('a'..'z').to_a[rand(26)]
\r
421 debug "getting random word from dictionary, starting with letter #{l}"
\r
422 first = rules[:url] % "lettera_#{l}_0_50"
\r
423 p = @bot.httputil.get(first)
\r
424 max_page = p.match(/ \/ (\d+)<\/label>/)[1].to_i
\r
425 pp = rand(max_page)+1
\r
426 debug "getting random word from dictionary, starting with letter #{l}, page #{pp}"
\r
427 p = @bot.httputil.get(first+"&pagina=#{pp}") if pp > 1
\r
429 good = rules[:good]
\r
431 # We look for a lemma composed by a single word and of length at least two
\r
432 p.scan(/<li><a href="([^"]+?)" title="consulta il lemma ([^ "][^ "]+?)">.*? (.+?)<\/li>/) { |url, prelemma, tipo|
\r
433 lemma = prelemma.downcase.to_sym
\r
434 debug "checking lemma #{lemma} (#{prelemma}) of type #{tipo} from url #{url}"
\r
435 next if wc.key?(lemma)
\r
439 debug "refusing, #{bad}"
\r
444 wc[lemma] = {:who => :dict}
\r
446 debug "refusing, not #{good}"
\r
449 word = lemmi[rand(lemmi.length)].to_s
\r
452 error "error #{e.inspect} while looking up a word"
\r
453 error e.backtrace.join("\n")
\r
458 def is_english?(word)
\r
459 unless @wordcache.key?(:english)
\r
460 @wordcache[:english] = Hash.new
\r
462 wc = @wordcache[:english]
\r
463 return true if wc.key?(word.to_sym)
\r
464 rules = @rules[:english]
\r
465 p = @bot.httputil.get(rules[:url] % CGI.escape(word))
\r
467 error "could not connect!"
\r
471 if p =~ /<span class="(?:hwd|srch)">#{word}<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i
\r
472 debug "new word #{word}"
\r
473 wc[word.to_sym] = {:who => :dict}
\r
479 def random_pick_english(min=nil,max=nil)
\r
480 # Try to pick a random word between min and max
\r
485 m.reply "#{min} > #{max}"
\r
488 rules = @rules[:english]
\r
489 min = rules[:first] if min.empty?
\r
490 max = rules[:last] if max.empty?
\r
491 debug "looking for word between #{min.inspect} and #{max.inspect}"
\r
492 return word if min.empty? or max.empty?
\r
494 while (word <= min or word >= max or word !~ /^[a-z]+$/)
\r
495 debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"
\r
496 # TODO for the time being, skip words with extended characters
\r
497 unless @wordcache.key?(:english)
\r
498 @wordcache[:english] = Hash.new
\r
500 wc = @wordcache[:english]
\r
503 cache_or_url = rand(2)
\r
504 if cache_or_url == 0
\r
505 debug "getting word from wordcache"
\r
506 word = wc.keys[rand(wc.size)].to_s
\r
511 # TODO when doing ranges, adapt this choice
\r
512 l = ('a'..'z').to_a[rand(26)]
\r
513 ll = ('a'..'z').to_a[rand(26)]
\r
514 random = [l,ll].join('*') + '*'
\r
515 debug "getting random word from dictionary, matching #{random}"
\r
516 p = @bot.httputil.get(rules[:url] % CGI.escape(random))
\r
519 good = rules[:good]
\r
520 # We look for a lemma composed by a single word and of length at least two
\r
521 p.scan(/<span class="(?:hwd|srch)">(.*?)<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i) { |prelemma, discard|
\r
522 lemma = prelemma.downcase
\r
523 debug "checking lemma #{lemma} (#{prelemma}) and discarding #{discard}"
\r
524 next if wc.key?(lemma.to_sym)
\r
525 if lemma =~ /^[a-z]+$/
\r
528 wc[lemma.to_sym] = {:who => :dict}
\r
530 debug "funky characters, not good"
\r
533 next if lemmi.empty?
\r
534 word = lemmi[rand(lemmi.length)]
\r
537 error "error #{e.inspect} while looking up a word"
\r
538 error e.backtrace.join("\n")
\r
543 def help(plugin, topic="")
\r
546 return _("az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)")
\r
548 return _("az cancel => abort current game")
\r
550 return _('az check <word> => checks <word> against current game')
\r
552 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
554 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
556 return _("az topics: play, rules, cancel, manage, check")
\r
561 plugin = AzGamePlugin.new
\r
562 plugin.map 'az [:lang] word :cmd *params', :action=>'wordlist', :defaults => { :lang => nil, :cmd => 'count', :params => [] }, :auth_path => '!az::edit!'
\r
563 plugin.map 'az cancel', :action=>'stop_game', :private => false
\r
564 plugin.map 'az check :word', :action => 'manual_word_check', :private => false
\r
565 plugin.map 'az [play] [:lang]', :action=>'start_game', :private => false, :defaults => { :lang => nil }
\r