]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/azgame.rb
ae410e87a16144c4408954e0766ba44f48d84794
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / azgame.rb
1 # vim: set et sw=2:\r
2 # A-Z Game: guess the word by reducing the interval of allowed ones\r
3 #\r
4 # Author: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>\r
5 #\r
6 # (C) 2006 Giuseppe Bilotta\r
7 #\r
8 # TODO allow manual addition of words\r
9 \r
10 AZ_RULES = {\r
11   :italian => {\r
12     :good => /s\.f\.|s\.m\.|agg\.|v\.tr\.|v\.(pronom\.)?intr\./, # avv\.|pron\.|cong\.\r
13     :bad => /var\./,\r
14     :first => 'abaco',\r
15     :last => 'zuzzurellone',\r
16     :url => "http://www.demauroparavia.it/%s",\r
17     :wapurl => "http://wap.demauroparavia.it/index.php?lemma=%s"\r
18   },\r
19   :english => {\r
20     :good => /(?:singular )?noun|verb|adj/,\r
21     :first => 'abacus',\r
22     :last => 'zuni',\r
23     :url => "http://www.chambersharrap.co.uk/chambers/features/chref/chref.py/main?query=%s&title=21st"\r
24   }\r
25 }\r
26 \r
27 class AzGame\r
28 \r
29   attr_reader :range, :word\r
30   attr_accessor :tries, :total_tries, :winner\r
31   def initialize(plugin, lang, word)\r
32     @plugin = plugin\r
33     @lang = lang.to_sym\r
34     @word = word.downcase\r
35     @range = [AZ_RULES[lang][:first].dup, AZ_RULES[lang][:last].dup]\r
36     @total_tries = 0\r
37     @tries = Hash.new(0)\r
38     @winner = nil\r
39     def @range.to_s\r
40       return "%s -- %s" % self\r
41     end\r
42   end\r
43 \r
44   def check(word)\r
45     w = word.downcase\r
46     debug "checking #{w} for #{@word} in #{@range}"\r
47     return [:bingo, nil] if w == @word\r
48     return [:out, @range] if w < @range.first or w > @range.last\r
49     return [:ignore, @range] if w == @range.first or w == @range.last\r
50     return [:noexist, @range] unless @plugin.send("is_#{@lang}?", w)\r
51     debug "we like it"\r
52     if w < @word\r
53       @range.first.replace(w)\r
54     else\r
55       @range.last.replace(w)\r
56     end\r
57     return [:in, @range]\r
58   end\r
59 \r
60 # TODO scoring: base score is t = ceil(100*exp(-(n-1)^2/50))+p for n attempts\r
61 #               done by p players; players that didn't win but contributed\r
62 #               with a attempts will get t*a/n points\r
63 \r
64   include Math\r
65 \r
66   def score\r
67     n = @total_tries\r
68     p = @tries.keys.length\r
69     t = (100*exp(-(n-1)**2/50**2)).ceil + p\r
70     debug "Total score: #{t}"\r
71     ret = Hash.new\r
72     @tries.each { |k, a|\r
73       ret[k] = [t*a/n, "%d %s" % [a, a > 1 ? "tries" : "try"]]\r
74     }\r
75     if @winner\r
76       debug "replacing winner score of %d with %d" % [ret[@winner].first, t]\r
77       tries = ret[@winner].last\r
78       ret[@winner] = [t, "winner, #{tries}"]\r
79     end\r
80     return ret.sort_by { |h| h.last.first }.reverse\r
81   end\r
82 \r
83 end\r
84 \r
85 class AzGamePlugin < Plugin\r
86 \r
87   def initialize\r
88     super\r
89     # if @registry.has_key?(:games)\r
90     #   @games = @registry[:games]\r
91     # else\r
92       @games = Hash.new\r
93     # end\r
94     if @registry.has_key?(:wordcache) and @registry[:wordcache]\r
95       @wordcache = @registry[:wordcache]\r
96     else\r
97       @wordcache = Hash.new\r
98     end\r
99     debug "\n\n\nA-Z wordcache: #{@wordcache.inspect}\n\n\n"\r
100   end\r
101 \r
102   def save\r
103     # @registry[:games] = @games\r
104     @registry[:wordcache] = @wordcache\r
105   end\r
106 \r
107   def listen(m)\r
108     return unless m.kind_of?(PrivMessage)\r
109     return if m.channel.nil? or m.address?\r
110     k = m.channel.downcase.to_s # to_sym?\r
111     return unless @games.key?(k)\r
112     return if m.params\r
113     word = m.plugin.downcase\r
114     return unless word =~ /^[a-z]+$/\r
115     word_check(m, k, word)\r
116   end\r
117 \r
118   def word_check(m, k, word)\r
119     isit = @games[k].check(word)\r
120     case isit.first\r
121     when :bingo\r
122       m.reply "#{Bold}BINGO!#{Bold}: the word was #{Underline}#{word}#{Underline}. Congrats, #{Bold}#{m.sourcenick}#{Bold}!"\r
123       @games[k].total_tries += 1\r
124       @games[k].tries[m.source] += 1\r
125       @games[k].winner = m.source\r
126       ar = @games[k].score.inject([]) { |res, kv|\r
127         res.push("%s: %d (%s)" % kv.flatten)\r
128       }\r
129       m.reply "The game was won after #{@games[k].total_tries} tries. Scores for this game:    #{ar.join('; ')}"\r
130       @games.delete(k)\r
131     when :out\r
132       m.reply "#{word} is not in the range #{Bold}#{isit.last}#{Bold}" if m.address?\r
133     when :noexist\r
134       m.reply "#{word} doesn't exist or is not acceptable for the game"\r
135     when :in\r
136       m.reply "close, but no cigar. New range: #{Bold}#{isit.last}#{Bold}"\r
137       @games[k].total_tries += 1\r
138       @games[k].tries[m.source] += 1\r
139     when :ignore\r
140       m.reply "#{word} is already one of the range extrema: #{isit.last}" if m.address?\r
141     else\r
142       m.reply "hm, something went wrong while verifying #{word}"\r
143     end\r
144   end\r
145 \r
146   def manual_word_check(m, params)\r
147     k = m.channel.downcase.to_s\r
148     word = params[:word].downcase\r
149     if not @games.key?(k)\r
150       m.reply "no A-Z game running here, can't check if #{word} is valid, can I?"\r
151       return\r
152     end\r
153     if word !~ /^[a-z]+$/\r
154       m.reply "I only accept single words composed by letters only, sorry"\r
155       return\r
156     end\r
157     word_check(m, k, word)\r
158   end\r
159 \r
160   def stop_game(m, params)\r
161     return if m.channel.nil? # Shouldn't happen, but you never know\r
162     k = m.channel.downcase.to_s # to_sym?\r
163     if @games.key?(k)\r
164       m.reply "the word in #{Bold}#{@games[k].range}#{Bold} was:   #{Bold}#{@games[k].word}"\r
165       ar = @games[k].score.inject([]) { |res, kv|\r
166         res.push("%s: %d (%s)" % kv.flatten)\r
167       }\r
168       m.reply "The game was cancelled after #{@games[k].total_tries} tries. Scores for this game would have been:    #{ar.join('; ')}"\r
169       @games.delete(k)\r
170     else\r
171       m.reply "no A-Z game running in this channel ..."\r
172     end\r
173   end\r
174 \r
175   def start_game(m, params)\r
176     return if m.channel.nil? # Shouldn't happen, but you never know\r
177     k = m.channel.downcase.to_s # to_sym?\r
178     unless @games.key?(k)\r
179       lang = (params[:lang] || @bot.config['core.language']).to_sym\r
180       method = 'random_pick_'+lang.to_s\r
181       m.reply "let me think ..."\r
182       if AZ_RULES.has_key?(lang) and self.respond_to?(method)\r
183         word = self.send(method)\r
184         if word.empty?\r
185           m.reply "couldn't think of anything ..."\r
186           return\r
187         end\r
188       else\r
189         m.reply "I can't play A-Z in #{lang}, sorry"\r
190         return\r
191       end\r
192       m.reply "got it!"\r
193       @games[k] = AzGame.new(self, lang, word)\r
194     end\r
195     tr = @games[k].total_tries\r
196     m.reply "A-Z: #{Bold}#{@games[k].range}#{Bold}" + (tr > 0 ? " (after #{tr} tries)" : "")\r
197     return\r
198   end\r
199 \r
200   def wordlist(m, params)\r
201     pars = params[:params]\r
202     lang = (params[:lang] || @bot.config['core.language']).to_sym\r
203     wc = @wordcache[lang] || Hash.new rescue Hash.new\r
204     cmd = params[:cmd].to_sym rescue :count\r
205     case cmd\r
206     when :count\r
207       m.reply "I have #{wc.size > 0 ? wc.size : 'no'} #{lang} words in my cache"\r
208     when :show, :list\r
209       if pars.empty?\r
210         m.reply "provide a regexp to match"\r
211         return\r
212       end\r
213       begin\r
214         regex = /#{pars[0]}/\r
215         matches = wc.keys.map { |k|\r
216           k.to_s\r
217         }.grep(regex)\r
218       rescue\r
219         matches = []\r
220       end\r
221       if matches.size == 0\r
222         m.reply "no #{lang} word I know match #{pars[0]}"\r
223       elsif matches.size > 25\r
224         m.reply "more than 25 #{lang} words I know match #{pars[0]}, try a stricter matching"\r
225       else\r
226         m.reply "#{matches.join(', ')}"\r
227       end\r
228     when :info\r
229       if pars.empty?\r
230         m.reply "provide a word"\r
231         return\r
232       end\r
233       word = pars[0].downcase.to_sym\r
234       if not wc.key?(word)\r
235         m.reply "I don't know any #{lang} word #{word}"\r
236         return\r
237       end\r
238       tr = "#{word} learned from #{wc[word][:who]}"\r
239       (tr << " on #{wc[word][:when]}") if wc[word].key?(:when)\r
240       m.reply tr\r
241     when :delete\r
242       if pars.empty?\r
243         m.reply "provide a word"\r
244         return\r
245       end\r
246       word = pars[0].downcase.to_sym\r
247       if not wc.key?(word)\r
248         m.reply "I don't know any #{lang} word #{word}"\r
249         return\r
250       end\r
251       wc.delete(word)\r
252       @bot.okay m.replyto\r
253     when :add\r
254       if pars.empty?\r
255         m.reply "provide a word"\r
256         return\r
257       end\r
258       word = pars[0].downcase.to_sym\r
259       if wc.key?(word)\r
260         m.reply "I already know the #{lang} word #{word}"\r
261         return\r
262       end\r
263       wc[word] = { :who => m.sourcenick, :when => Time.now }\r
264       @bot.okay m.replyto\r
265     else\r
266     end\r
267   end\r
268 \r
269   def is_italian?(word)\r
270     unless @wordcache.key?(:italian)\r
271       @wordcache[:italian] = Hash.new\r
272     end\r
273     wc = @wordcache[:italian]\r
274     return true if wc.key?(word.to_sym)\r
275     rules = AZ_RULES[:italian]\r
276     p = @bot.httputil.get_cached(rules[:wapurl] % word)\r
277     if not p\r
278       error "could not connect!"\r
279       return false\r
280     end\r
281     debug p\r
282     p.scan(/<anchor>#{word} - (.*?)<go href="lemma.php\?ID=([^"]*?)"/) { |qual, url|\r
283       debug "new word #{word} of type #{qual}"\r
284       if qual =~ rules[:good] and qual !~ rules[:bad]\r
285         wc[word.to_sym] = {:who => :dict}\r
286         return true\r
287       end\r
288       next\r
289     }\r
290     return false\r
291   end\r
292 \r
293   def random_pick_italian(min=nil,max=nil)\r
294     # Try to pick a random word between min and max\r
295     word = String.new\r
296     min = min.to_s\r
297     max = max.to_s\r
298     if min > max\r
299       m.reply "#{min} > #{max}"\r
300       return word\r
301     end\r
302     rules = AZ_RULES[:italian]\r
303     min = rules[:first] if min.empty?\r
304     max = rules[:last]  if max.empty?\r
305     debug "looking for word between #{min.inspect} and #{max.inspect}"\r
306     return word if min.empty? or max.empty?\r
307     begin\r
308       while (word <= min or word >= max or word !~ /^[a-z]+$/)\r
309         debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"\r
310         # TODO for the time being, skip words with extended characters\r
311         unless @wordcache.key?(:italian)\r
312           @wordcache[:italian] = Hash.new\r
313         end\r
314         wc = @wordcache[:italian]\r
315 \r
316         if wc.size > 0\r
317           cache_or_url = rand(2)\r
318           if cache_or_url == 0\r
319             debug "getting word from wordcache"\r
320             word = wc.keys[rand(wc.size)].to_s\r
321             next\r
322           end\r
323         end\r
324 \r
325         # TODO when doing ranges, adapt this choice\r
326         l = ('a'..'z').to_a[rand(26)]\r
327         debug "getting random word from dictionary, starting with letter #{l}"\r
328         first = rules[:url] % "lettera_#{l}_0_50"\r
329         p = @bot.httputil.get_cached(first)\r
330         max_page = p.match(/ \/ (\d+)<\/label>/)[1].to_i\r
331         pp = rand(max_page)+1\r
332         debug "getting random word from dictionary, starting with letter #{l}, page #{pp}"\r
333         p = @bot.httputil.get_cached(first+"&pagina=#{pp}") if pp > 1\r
334         lemmi = Array.new\r
335         good = rules[:good]\r
336         bad =  rules[:bad]\r
337         # We look for a lemma composed by a single word and of length at least two\r
338         p.scan(/<li><a href="([^"]+?)" title="consulta il lemma ([^ "][^ "]+?)">.*?&nbsp;(.+?)<\/li>/) { |url, prelemma, tipo|\r
339           lemma = prelemma.downcase.to_sym\r
340           debug "checking lemma #{lemma} (#{prelemma}) of type #{tipo} from url #{url}"\r
341           next if wc.key?(lemma)\r
342           case tipo\r
343           when good\r
344             if tipo =~ bad\r
345               debug "refusing, #{bad}"\r
346               next\r
347             end\r
348             debug "good one"\r
349             lemmi << lemma\r
350             wc[lemma] = {:who => :dict}\r
351           else\r
352             debug "refusing, not #{good}"\r
353           end\r
354         }\r
355         word = lemmi[rand(lemmi.length)].to_s\r
356       end\r
357     rescue => e\r
358       error "error #{e.inspect} while looking up a word"\r
359       error e.backtrace.join("\n")\r
360     end\r
361     return word\r
362   end\r
363 \r
364   def is_english?(word)\r
365     unless @wordcache.key?(:english)\r
366       @wordcache[:english] = Hash.new\r
367     end\r
368     wc = @wordcache[:english]\r
369     return true if wc.key?(word.to_sym)\r
370     rules = AZ_RULES[:english]\r
371     p = @bot.httputil.get_cached(rules[:url] % URI.escape(word))\r
372     if not p\r
373       error "could not connect!"\r
374       return false\r
375     end\r
376     debug p\r
377     if p =~ /<span class="(?:hwd|srch)">#{word}<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i\r
378       debug "new word #{word}"\r
379         wc[word.to_sym] = {:who => :dict}\r
380         return true\r
381     end\r
382     return false\r
383   end\r
384 \r
385   def random_pick_english(min=nil,max=nil)\r
386     # Try to pick a random word between min and max\r
387     word = String.new\r
388     min = min.to_s\r
389     max = max.to_s\r
390     if min > max\r
391       m.reply "#{min} > #{max}"\r
392       return word\r
393     end\r
394     rules = AZ_RULES[:english]\r
395     min = rules[:first] if min.empty?\r
396     max = rules[:last]  if max.empty?\r
397     debug "looking for word between #{min.inspect} and #{max.inspect}"\r
398     return word if min.empty? or max.empty?\r
399     begin\r
400       while (word <= min or word >= max or word !~ /^[a-z]+$/)\r
401         debug "looking for word between #{min} and #{max} (prev: #{word.inspect})"\r
402         # TODO for the time being, skip words with extended characters\r
403         unless @wordcache.key?(:english)\r
404           @wordcache[:english] = Hash.new\r
405         end\r
406         wc = @wordcache[:english]\r
407 \r
408         if wc.size > 0\r
409           cache_or_url = rand(2)\r
410           if cache_or_url == 0\r
411             debug "getting word from wordcache"\r
412             word = wc.keys[rand(wc.size)].to_s\r
413             next\r
414           end\r
415         end\r
416 \r
417         # TODO when doing ranges, adapt this choice\r
418         l = ('a'..'z').to_a[rand(26)]\r
419         ll = ('a'..'z').to_a[rand(26)]\r
420         random = [l,ll].join('*') + '*'\r
421         debug "getting random word from dictionary, matching #{random}"\r
422         p = @bot.httputil.get_cached(rules[:url] % URI.escape(random))\r
423         debug p\r
424         lemmi = Array.new\r
425         good = rules[:good]\r
426         # We look for a lemma composed by a single word and of length at least two\r
427         p.scan(/<span class="(?:hwd|srch)">(.*?)<\/span>([^\n]+?)<span class="psa">#{rules[:good]}<\/span>/i) { |prelemma, discard|\r
428           lemma = prelemma.downcase\r
429           debug "checking lemma #{lemma} (#{prelemma}) and discarding #{discard}"\r
430           next if wc.key?(lemma.to_sym)\r
431           if lemma =~ /^[a-z]+$/\r
432             debug "good one"\r
433             lemmi << lemma\r
434             wc[lemma.to_sym] = {:who => :dict}\r
435           else\r
436             debug "funky characters, not good"\r
437           end\r
438         }\r
439         next if lemmi.empty?\r
440         word = lemmi[rand(lemmi.length)]\r
441       end\r
442     rescue => e\r
443       error "error #{e.inspect} while looking up a word"\r
444       error e.backtrace.join("\n")\r
445     end\r
446     return word\r
447   end\r
448 \r
449   def help(plugin, topic="")\r
450     case topic\r
451     when 'manage'\r
452       return "az [lang] word [count|list|add|delete] => manage the az wordlist for language lang (defaults to current bot language)"\r
453     when 'cancel'\r
454       return "az cancel => abort current game"\r
455     when 'check'\r
456       return 'az check <word> => checks <word> against current game'\r
457     when 'rules'\r
458       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
459     when 'play'\r
460       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
461     end\r
462     return "az topics: play, rules, cancel, manage, check"\r
463   end\r
464 \r
465 end\r
466 \r
467 plugin = AzGamePlugin.new\r
468 plugin.map 'az [:lang] word :cmd *params', :action=>'wordlist', :defaults => { :lang => nil, :cmd => 'count', :params => [] }, :auth_path => '!az::edit!'\r
469 plugin.map 'az cancel', :action=>'stop_game', :private => false\r
470 plugin.map 'az check :word', :action => 'manual_word_check', :private => false\r
471 plugin.map 'az [play] [:lang]', :action=>'start_game', :private => false, :defaults => { :lang => nil }\r
472 \r