4 # :title: Hangman Plugin
6 # Author:: Raine Virta <rane@kapsi.fi>
7 # Copyright:: (C) 2009 Raine Virta
10 # Description:: Hangman game for rbot
12 # TODO:: some sort of turn-basedness, maybe
15 SITE = "http://coyotecult.com/tools/randomwordgenerator.php"
18 res = Net::HTTP.post_form(URI.parse(SITE), {'numwords' => count})
19 words = res.body.scan(%r{<a.*?\?w=(.*?)\n}).flatten
21 count == 1 ? words.first : words
26 URL = "http://www.google.com/wml/search?hl=en&q=define:"
27 REGEX = %r{Web definitions for .*?<br/>(.*?)<br/>}
29 def self.define(phrase)
30 raw = Net::HTTP.get(URI.parse(URL+CGI.escape(phrase)))
31 res = raw.scan(REGEX).flatten.map { |e| e.strip }
33 res.empty? ? false : res.last
41 def self.correct_word_guess(game)
42 # (2 - (amt of visible chars / word length)) * (amt of chars not visible * 5)
43 length = game.word.size
44 visible = game.visible_characters.size
45 invisible = length - visible
46 score = (2-(visible/length.to_f))*(invisible*5)
51 def self.incorrect_word_guess(game)
52 incorrect_letter(game)
55 def self.correct_letter(game)
56 ((1/Math.log(game.word.size))+1) * LETTER_VALUE
59 def self.incorrect_letter(game)
60 Math.log(game.word.size) * -LETTER_VALUE
66 attr_reader :misses, :guesses, :word, :letters, :scores
68 STAGES = [' (x_x) ', ' (;_;) ', ' (>_<) ', ' (-_-) ', ' (o_~) ', ' (^_^) ', '\(^o^)/']
69 HEALTH = STAGES.size-1
82 def visible_characters
83 # array of visible characters
84 characters.reject { |c| !@guesses.include?(c) && c =~ LETTER }
88 # array of the letters in the word
89 characters.reject { |c| c !~ LETTER }.map { |c| c.downcase }
101 # creates a string that presents the word with unknown letters shown as underscores
103 @guesses.include?(c.downcase) || c !~ LETTER ? c : "_"
107 def guess(player, str)
108 @scores[player] ||= 0
112 if str !~ /^#{LETTER}$/u
113 if word.downcase == str
114 @scores[player] += Scoring::correct_word_guess(self)
117 @scores[player] += Scoring::incorrect_word_guess(self)
120 else # single letter guess
121 return false if @guesses.include?(str) # letter has been guessed before
123 unless letters.include?(str)
124 @scores[player] += Scoring::incorrect_letter(self)
128 @scores[player] += Scoring::correct_letter(self)
138 won? || lost? || @canceled
142 (letters - @guesses).empty? || @solved
164 game = all(target).last
165 game if game && !game.over?
169 @games[target] || @games[target] = []
173 all(target).select { |game| game.over? }.last
177 all(game.channel) << game
181 define_structure :HangmanPlayerStats, :played, :score
182 define_structure :HangmanPrivateStats, :played, :score
185 def initialize(registry)
189 def save_gamestats(game)
190 target = game.channel
192 if target.is_a?(User)
193 stats = priv_reg[target]
195 stats.score += game.scores.values.last.round
196 priv_reg[target] = stats
197 elsif target.is_a?(Channel)
198 stats = chan_stats(target)
201 reg = player_stats(target)
202 game.scores.each do |user, score|
205 pstats.score += score.round
211 def player_stats(channel)
212 reg = chan_reg(channel).sub_registry('player')
213 reg.set_default(HangmanPlayerStats.new(0,0))
217 def chan_stats(channel)
218 reg = chan_reg(channel).sub_registry('stats')
223 def chan_reg(channel)
224 @registry.sub_registry(channel.downcase)
228 reg = @registry.sub_registry('private')
229 reg.set_default(HangmanPrivateStats.new(0,0))
234 class HangmanPlugin < Plugin
237 @games = GameManager.new
238 @stats = StatsHandler.new(@registry)
242 def help(plugin, topic="")
245 return _("hangman game plugin - topics: play, stop")
247 return [_("hangman play on <channel> with word <word> => use in private chat with the bot to start a game with custom word\n"),
248 _("hangman play random [with [max|min] length [<|>|== <length>]] => hangman with a random word from %{site}\n"),
249 _("hangman play with wordlist <wordlist> => hangman with random word from <wordlist>")].join
251 return _("hangman stop => quits the current game")
253 return _("define => seeks a definition for the previous answer using google")
259 params[:word].join(" ")
260 elsif params[:wordlist]
262 wordlist = Wordlist.get(params[:wordlist].join("/"), :spaces => true)
264 raise _("no such wordlist")
267 wordlist[rand(wordlist.size)]
268 else # getting a random word
269 words = RandomWord::get(100)
271 if adj = params[:adj]
272 words = words.sort_by { |e| e.size }
279 elsif params[:relation] && params[:size]
280 words = words.select { |w| w.size.send(params[:relation], params[:size].to_i) }
285 m.reply _("suitable word not found in the set")
296 word = get_word(params) || return
302 if params[:channel] || m.public?
303 target = if m.public?
309 # is the bot on the channel?
310 unless @bot.server.channels.names.include?(target.to_s)
311 m.reply _("i'm not on that channel")
315 if @games.current(target)
316 m.reply _("there's already a hangman game in progress on the channel")
320 @bot.say target, _("%{nick} has started a hangman -- join the fun!") % {
327 game = Hangman.new(word)
329 class << game = Hangman.new(word)
330 attr_accessor :channel
333 game.channel = target
336 @settings[target] = params
338 @bot.say target, game_status(@games.current(target))
343 if game = @games.current(target)
344 @bot.say target, _("oh well, the answer would've been %{answer}") % {
345 :answer => Bold + game.word + Bold
349 @stats.save_gamestats(game)
351 @bot.say target, _("no ongoing game")
358 if game = @games.current(target)
359 return unless m.message =~ /^[^\W0-9_]$/u || m.message =~ prepare_guess_regex(game)
361 if game.guess(m.source, m.message)
362 m.reply game_status(game)
368 sentence = if game.won?
371 _("you've killed the poor guy :(")
374 again = _("go %{b}again%{b}?") % { :b => Bold }
377 game.scores.each do |user, score|
378 str = "#{user.nick}: "
380 Irc.color(:green)+'+'
385 str << score.round.to_s
391 m.reply _("%{sentence} %{again} %{scores}") % {
392 :sentence => sentence, :again => again, :scores => scores.join(' ')
396 m.reply _("wondering what that means? try ´%{prefix}define´") % {
397 :prefix => @bot.config['core.address_prefix']
401 @stats.save_gamestats(game)
403 elsif @settings[target] && m.message =~ /^(?:again|more!?$)/i
404 start(m, @settings[target])
408 def prepare_guess_regex(game)
409 Regexp.new("^#{game.characters.map { |c|
410 game.guesses.include?(c) || c !~ Hangman::LETTER ? c : '[^\W0-9_]'
414 def game_status(game)
415 str = "%{word} %{face}" % {
416 :word => game.over? ? "#{Bold}#{game.word}#{Bold}" : game.to_s,
418 :misses => game.misses.map { |e| e.upcase }.join(" ")
421 str << " %{misses}" % {
422 :misses => game.misses.map { |e| e.upcase }.join(" ")
423 } unless game.misses.empty?
432 stats = if m.private?
433 @stats.priv_reg[target]
435 @stats.player_stats(target)[m.source]
438 unless stats.played.zero?
439 m.reply _("you got %{score} points after %{games} games") % {
440 :score => stats.score.round,
441 :games => stats.played
444 m.reply _("you haven't played hangman, how about playing it right now? :)")
447 return unless m.public?
450 stats = @stats.player_stats(target)[nick]
452 unless stats.played.zero?
453 m.reply _("%{nick} has %{score} points after %{games} games") % {
455 :score => stats.score.round,
456 :games => stats.played
459 m.reply _("%{nick} hasn't played hangman :(") % {
468 stats = @stats.chan_stats(target)
471 m.reply _("%{games} games have been played on %{channel}") % {
472 :games => stats['played'],
473 :channel => target.to_s
480 def define(m, params)
481 if game = @games.previous(m.replyto)
482 return unless res = Google.define(game.word)
483 m.reply "#{Bold}#{game.word}#{Bold} -- #{res}"
488 plugin = HangmanPlugin.new
489 plugin.map "hangman [play] with wordlist *wordlist", :action => 'start'
490 plugin.map "hangman [play] on :channel with word *word", :action => 'start'
491 plugin.map "hangman [play] [random] [with [:adj] length [:relation :size]]",
493 :requirements => { :adj => /min|max/, :relation => /<|<=|>=|>|==/, :size => /\d+/ }
495 plugin.map "hangman stop", :action => 'stop'
497 plugin.map "hangman score [:nick]", :action => 'score'
498 plugin.map "hangman stats", :action => 'stats'
499 plugin.map "define", :action => 'define'