2 # A-Z Game: guess the word by reducing the interval of allowed ones
\r
4 # Author: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
\r
5 # Author: Yaohan Chen <yaohan.chen@gmail.com>: Japanese support
\r
7 # (C) 2006 Giuseppe Bilotta
\r
8 # (C) 2007 Yaohan Chen
\r
10 # TODO allow manual addition of words
\r
14 attr_reader :range, :word
\r
15 attr_reader :lang, :rules, :listener
\r
16 attr_accessor :tries, :total_tries, :total_failed, :failed, :winner
\r
17 def initialize(plugin, lang, rules, word)
\r
20 @word = word.downcase
\r
22 @range = [@rules[:first].dup, @rules[:last].dup]
\r
23 @listener = @rules[:listener]
\r
25 @total_failed = 0 # not used, reported, updated
\r
26 @tries = Hash.new(0)
\r
27 @failed = Hash.new(0) # not used, not reported, updated
\r
30 return "%s -- %s" % self
\r
36 debug "checking #{w} for #{@word} in #{@range}"
\r
37 return [:bingo, nil] if w == @word
\r
38 return [:out, @range] if w < @range.first or w > @range.last
\r
39 return [:ignore, @range] if w == @range.first or w == @range.last
\r
40 return [:noexist, @range] unless @plugin.send("is_#{@lang}?", w)
\r
43 @range.first.replace(w)
\r
45 @range.last.replace(w)
\r
47 return [:in, @range]
\r
50 # TODO scoring: base score is t = ceil(100*exp(-(n-1)^2/50))+p for n attempts
\r
51 # done by p players; players that didn't win but contributed
\r
52 # with a attempts will get t*a/n points
\r
58 p = @tries.keys.length
\r
59 t = (100*exp(-(n-1)**2/50**2)).ceil + p
\r
60 debug "Total score: #{t}"
\r
62 @tries.each { |k, a|
\r
63 ret[k] = [t*a/n, "%d %s" % [a, a > 1 ? "tries" : "try"]]
\r
66 debug "replacing winner score of %d with %d" % [ret[@winner].first, t]
\r
67 tries = ret[@winner].last
\r
68 ret[@winner] = [t, "winner, #{tries}"]
\r
70 return ret.sort_by { |h| h.last.first }.reverse
\r
75 class AzGamePlugin < Plugin
\r
79 # if @registry.has_key?(:games)
\r
80 # @games = @registry[:games]
\r
84 if @registry.has_key?(:wordcache) and @registry[:wordcache]
\r
85 @wordcache = @registry[:wordcache]
\r
87 @wordcache = Hash.new
\r
89 debug "\n\n\nA-Z wordcache: #{@wordcache.inspect}\n\n\n"
\r
93 :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.
\r
96 :last => 'zuzzurellone',
\r
97 :url => "http://www.demauroparavia.it/%s",
\r
98 :wapurl => "http://wap.demauroparavia.it/index.php?lemma=%s",
\r
99 :listener => /^[a-z]+$/
\r
102 :good => /(?:singular )?noun|verb|adj/,
\r
103 :first => 'abacus',
\r
105 :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st",
\r
106 :listener => /^[a-z]+$/
\r
110 japanese_wordlist = "#{@bot.botclass}/azgame/wordlist-japanese"
\r
111 if File.exist?(japanese_wordlist)
\r
112 words = File.readlines(japanese_wordlist) \
\r
113 .map {|line| line.strip} .uniq
\r
114 if(words.length >= 4) # something to guess
\r
115 @rules[:japanese] = {
\r
118 :first => words[0],
\r
119 :last => words[-1],
\r
120 :listener => /^\S+$/
\r
122 debug "Japanese wordlist loaded, #{@rules[:japanese][:list].length} lines; first word: #{@rules[:japanese][:first]}, last word: #{@rules[:japanese][:last]}"
\r
128 # @registry[:games] = @games
\r
129 @registry[:wordcache] = @wordcache
\r
133 return unless m.kind_of?(PrivMessage)
\r
134 return if m.channel.nil? or m.address?
\r
135 k = m.channel.downcase.to_s # to_sym?
\r
136 return unless @games.key?(k)
\r
138 word = m.plugin.downcase
\r
139 return unless word =~ @games[k].listener
\r
140 word_check(m, k, word)
\r
143 def word_check(m, k, word)
\r
144 isit = @games[k].check(word)
\r
147 m.reply "#{Bold}BINGO!#{Bold}: the word was #{Underline}#{word}#{Underline}. Congrats, #{Bold}#{m.sourcenick}#{Bold}!"
\r
148 @games[k].total_tries += 1
\r
149 @games[k].tries[m.source] += 1
\r
150 @games[k].winner = m.source
\r
151 ar = @games[k].score.inject([]) { |res, kv|
\r
152 res.push("%s: %d (%s)" % kv.flatten)
\r
154 m.reply "The game was won after #{@games[k].total_tries} tries. Scores for this game: #{ar.join('; ')}"
\r
157 m.reply "#{word} is not in the range #{Bold}#{isit.last}#{Bold}" if m.address?
\r
159 m.reply "#{word} doesn't exist or is not acceptable for the game"
\r
160 @games[k].total_failed += 1
\r
161 @games[k].failed[m.source] += 1
\r
163 m.reply "close, but no cigar. New range: #{Bold}#{isit.last}#{Bold}"
\r
164 @games[k].total_tries += 1
\r
165 @games[k].tries[m.source] += 1
\r
167 m.reply "#{word} is already one of the range extrema: #{isit.last}" if m.address?
\r
169 m.reply "hm, something went wrong while verifying #{word}"
\r
173 def manual_word_check(m, params)
\r
174 k = m.channel.downcase.to_s
\r
175 word = params[:word].downcase
\r
176 if not @games.key?(k)
\r
177 m.reply "no A-Z game running here, can't check if #{word} is valid, can I?"
\r
181 m.reply "I only accept single words composed by letters only, sorry"
\r
184 word_check(m, k, word)
\r
187 def stop_game(m, params)
\r
188 return if m.channel.nil? # Shouldn't happen, but you never know
\r
189 k = m.channel.downcase.to_s # to_sym?
\r
191 m.reply "the word in #{Bold}#{@games[k].range}#{Bold} was: #{Bold}#{@games[k].word}"
\r
192 ar = @games[k].score.inject([]) { |res, kv|
\r
193 res.push("%s: %d (%s)" % kv.flatten)
\r
195 m.reply "The game was cancelled after #{@games[k].total_tries} tries. Scores for this game would have been: #{ar.join('; ')}"
\r
198 m.reply "no A-Z game running in this channel ..."
\r
202 def start_game(m, params)
\r
203 return if m.channel.nil? # Shouldn't happen, but you never know
\r
204 k = m.channel.downcase.to_s # to_sym?
\r
205 unless @games.key?(k)
\r
206 lang = (params[:lang] || @bot.config['core.language']).to_sym
\r
207 method = 'random_pick_'+lang.to_s
\r
208 m.reply "let me think ..."
\r
209 if @rules.has_key?(lang) and self.respond_to?(method)
\r
210 word = self.send(method)
\r
212 m.reply "couldn't think of anything ..."
\r
216 m.reply "I can't play A-Z in #{lang}, sorry"
\r
220 @games[k] = AzGame.new(self, lang, @rules[lang], word)
\r
222 tr = @games[k].total_tries
\r
227 tr_msg = " (after 1 try"
\r
229 tr_msg = " (after #{tr} tries"
\r
232 unless tr_msg.empty?
\r
233 f_tr = @games[k].total_failed
\r
238 tr_msg << " and 1 invalid try)"
\r
240 tr_msg << " and #{f_tr} invalid tries)"
\r
244 m.reply "A-Z: #{Bold}#{@games[k].range}#{Bold}" + tr_msg
\r
248 def wordlist(m, params)
\r
249 pars = params[:params]
\r
250 lang = (params[:lang] || @bot.config['core.language']).to_sym
\r
251 wc = @wordcache[lang] || Hash.new rescue Hash.new
\r
252 cmd = params[:cmd].to_sym rescue :count
\r
255 m.reply "I have #{wc.size > 0 ? wc.size : 'no'} #{lang} words in my cache"
\r
258 m.reply "provide a regexp to match"
\r
262 regex = /#{pars[0]}/
\r
263 matches = wc.keys.map { |k|
\r
269 if matches.size == 0
\r
270 m.reply "no #{lang} word I know match #{pars[0]}"
\r
271 elsif matches.size > 25
\r
272 m.reply "more than 25 #{lang} words I know match #{pars[0]}, try a stricter matching"
\r
274 m.reply "#{matches.join(', ')}"
\r
278 m.reply "provide a word"
\r
281 word = pars[0].downcase.to_sym
\r
282 if not wc.key?(word)
\r
283 m.reply "I don't know any #{lang} word #{word}"
\r
286 tr = "#{word} learned from #{wc[word][:who]}"
\r
287 (tr << " on #{wc[word][:when]}") if wc[word].key?(:when)
\r
291 m.reply "provide a word"
\r
294 word = pars[0].downcase.to_sym
\r
295 if not wc.key?(word)
\r
296 m.reply "I don't know any #{lang} word #{word}"
\r
300 @bot.okay m.replyto
\r
303 m.reply "provide a word"
\r
306 word = pars[0].downcase.to_sym
\r
308 m.reply "I already know the #{lang} word #{word}"
\r
311 wc[word] = { :who => m.sourcenick, :when => Time.now }
\r
312 @bot.okay m.replyto
\r
317 def is_japanese?(word)
\r
318 @rules[:japanese][:list].include?(word)
\r
321 # return integer between min and max, inclusive
\r
322 def rand_between(min, max)
\r
323 rand(max - min + 1) + min
\r
326 def random_pick_japanese(min=nil, max=nil)
\r
327 rules = @rules[:japanese]
\r
328 min = rules[:first] if min.nil_or_empty?
\r
329 max = rules[:last] if max.nil_or_empty?
\r
330 debug "Randomly picking word between #{min} and #{max}"
\r
331 min_index = rules[:list].index(min)
\r
332 max_index = rules[:list].index(max)
\r
333 debug "Index between #{min_index} and #{max_index}"
\r
334 index = rand_between(min_index + 1, max_index - 1)
\r
335 debug "Index generated: #{index}"
\r
336 word = rules[:list][index]
\r
337 debug "Randomly picked #{word}"
\r
341 def is_italian?(word)
\r
342 unless @wordcache.key?(:italian)
\r
343 @wordcache[:italian] = Hash.new
\r
345 wc = @wordcache[:italian]
\r
346 return true if wc.key?(word.to_sym)
\r
347 rules = @rules[:italian]
\r
348 p = @bot.httputil.get_cached(rules[:wapurl] % word)
\r
350 error "could not connect!"
\r
354 p.scan(/<anchor>#{word} - (.*?)<go href="lemma.php\?ID=([^"]*?)"/) { |qual, url|
\r
355 debug "new word #{word} of type #{qual}"
\r
356 if qual =~ rules[:good] and qual !~ rules[:bad]
\r
357 wc[word.to_sym] = {:who => :dict}
\r
365 def random_pick_italian(min=nil,max=nil)
\r
366 # Try to pick a random word between min and max
\r
371 m.reply "#{min} > #{max}"
\r
374 rules = @rules[:italian]
\r
375 min = rules[:first] if min.empty?
\r
376 max = rules[:last] if max.empty?
\r
377 debug "looking for word between #{min.inspect} and #{max.inspect}"
\r
378 return word if min.empty? or max.empty?
\r
380 while (word <= min or word >= max or word !~ /^[a-z]+$/)
\r
381 debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"
\r
382 # TODO for the time being, skip words with extended characters
\r
383 unless @wordcache.key?(:italian)
\r
384 @wordcache[:italian] = Hash.new
\r
386 wc = @wordcache[:italian]
\r
389 cache_or_url = rand(2)
\r
390 if cache_or_url == 0
\r
391 debug "getting word from wordcache"
\r
392 word = wc.keys[rand(wc.size)].to_s
\r
397 # TODO when doing ranges, adapt this choice
\r
398 l = ('a'..'z').to_a[rand(26)]
\r
399 debug "getting random word from dictionary, starting with letter #{l}"
\r
400 first = rules[:url] % "lettera_#{l}_0_50"
\r
401 p = @bot.httputil.get_cached(first)
\r
402 max_page = p.match(/ \/ (\d+)<\/label>/)[1].to_i
\r
403 pp = rand(max_page)+1
\r
404 debug "getting random word from dictionary, starting with letter #{l}, page #{pp}"
\r
405 p = @bot.httputil.get_cached(first+"&pagina=#{pp}") if pp > 1
\r
407 good = rules[:good]
\r
409 # We look for a lemma composed by a single word and of length at least two
\r
410 p.scan(/<li><a href="([^"]+?)" title="consulta il lemma ([^ "][^ "]+?)">.*? (.+?)<\/li>/) { |url, prelemma, tipo|
\r
411 lemma = prelemma.downcase.to_sym
\r
412 debug "checking lemma #{lemma} (#{prelemma}) of type #{tipo} from url #{url}"
\r
413 next if wc.key?(lemma)
\r
417 debug "refusing, #{bad}"
\r
422 wc[lemma] = {:who => :dict}
\r
424 debug "refusing, not #{good}"
\r
427 word = lemmi[rand(lemmi.length)].to_s
\r
430 error "error #{e.inspect} while looking up a word"
\r
431 error e.backtrace.join("\n")
\r
436 def is_english?(word)
\r
437 unless @wordcache.key?(:english)
\r
438 @wordcache[:english] = Hash.new
\r
440 wc = @wordcache[:english]
\r
441 return true if wc.key?(word.to_sym)
\r
442 rules = @rules[:english]
\r
443 p = @bot.httputil.get_cached(rules[:url] % URI.escape(word))
\r
445 error "could not connect!"
\r
449 if p =~ /<span class="(?:hwd|srch)">#{word}<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i
\r
450 debug "new word #{word}"
\r
451 wc[word.to_sym] = {:who => :dict}
\r
457 def random_pick_english(min=nil,max=nil)
\r
458 # Try to pick a random word between min and max
\r
463 m.reply "#{min} > #{max}"
\r
466 rules = @rules[:english]
\r
467 min = rules[:first] if min.empty?
\r
468 max = rules[:last] if max.empty?
\r
469 debug "looking for word between #{min.inspect} and #{max.inspect}"
\r
470 return word if min.empty? or max.empty?
\r
472 while (word <= min or word >= max or word !~ /^[a-z]+$/)
\r
473 debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"
\r
474 # TODO for the time being, skip words with extended characters
\r
475 unless @wordcache.key?(:english)
\r
476 @wordcache[:english] = Hash.new
\r
478 wc = @wordcache[:english]
\r
481 cache_or_url = rand(2)
\r
482 if cache_or_url == 0
\r
483 debug "getting word from wordcache"
\r
484 word = wc.keys[rand(wc.size)].to_s
\r
489 # TODO when doing ranges, adapt this choice
\r
490 l = ('a'..'z').to_a[rand(26)]
\r
491 ll = ('a'..'z').to_a[rand(26)]
\r
492 random = [l,ll].join('*') + '*'
\r
493 debug "getting random word from dictionary, matching #{random}"
\r
494 p = @bot.httputil.get_cached(rules[:url] % URI.escape(random))
\r
497 good = rules[:good]
\r
498 # We look for a lemma composed by a single word and of length at least two
\r
499 p.scan(/<span class="(?:hwd|srch)">(.*?)<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i) { |prelemma, discard|
\r
500 lemma = prelemma.downcase
\r
501 debug "checking lemma #{lemma} (#{prelemma}) and discarding #{discard}"
\r
502 next if wc.key?(lemma.to_sym)
\r
503 if lemma =~ /^[a-z]+$/
\r
506 wc[lemma.to_sym] = {:who => :dict}
\r
508 debug "funky characters, not good"
\r
511 next if lemmi.empty?
\r
512 word = lemmi[rand(lemmi.length)]
\r
515 error "error #{e.inspect} while looking up a word"
\r
516 error e.backtrace.join("\n")
\r
521 def help(plugin, topic="")
\r
524 return "az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)"
\r
526 return "az cancel => abort current game"
\r
528 return 'az check <word> => checks <word> against current game'
\r
530 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
532 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
534 return "az topics: play, rules, cancel, manage, check"
\r
539 plugin = AzGamePlugin.new
\r
540 plugin.map 'az [:lang] word :cmd *params', :action=>'wordlist', :defaults => { :lang => nil, :cmd => 'count', :params => [] }, :auth_path => '!az::edit!'
\r
541 plugin.map 'az cancel', :action=>'stop_game', :private => false
\r
542 plugin.map 'az check :word', :action => 'manual_word_check', :private => false
\r
543 plugin.map 'az [play] [:lang]', :action=>'start_game', :private => false, :defaults => { :lang => nil }
\r