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 #{RandomWord::SITE}\n"+
249 "hangman play with wordlist <wordlist> => hangman with random word from <wordlist>"
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)
371 _("you've killed the poor guy :(")
374 str << _(" go #{Bold}again#{Bold}?")
376 game.scores.each do |user, score|
377 str << " #{user.nick}: "
379 Irc.color(:green)+'+'
384 str << score.round.to_s
388 m.reply str, :nick => true
391 m.reply _("wondering what that means? try ´%{prefix}define´") % {
392 :prefix => @bot.config['core.address_prefix']
396 @stats.save_gamestats(game)
398 elsif @settings[target] && m.message =~ /^(?:again|more!?$)/i
399 start(m, @settings[target])
403 def prepare_guess_regex(game)
404 Regexp.new("^#{game.characters.map { |c|
405 game.guesses.include?(c) || c !~ Hangman::LETTER ? c : '[^\W0-9_]'
409 def game_status(game)
410 str = "%{word} %{face}" % {
411 :word => game.over? ? "#{Bold}#{game.word}#{Bold}" : game.to_s,
413 :misses => game.misses.map { |e| e.upcase }.join(" ")
416 str << " %{misses}" % {
417 :misses => game.misses.map { |e| e.upcase }.join(" ")
418 } unless game.misses.empty?
427 stats = if m.private?
428 @stats.priv_reg[target]
430 @stats.player_stats(target)[m.source]
433 unless stats.played.zero?
434 m.reply _("you got %{score} points after %{games} games") % {
435 :score => stats.score.round,
436 :games => stats.played
439 m.reply _("you haven't played hangman, how about playing it right now? :)")
442 return unless m.public?
445 stats = @stats.player_stats(target)[nick]
447 unless stats.played.zero?
448 m.reply _("%{nick} has %{score} points after %{games} games") % {
450 :score => stats.score.round,
451 :games => stats.played
454 m.reply _("%{nick} hasn't played hangman :(") % {
463 stats = @stats.chan_stats(target)
466 m.reply _("%{games} games have been played on %{channel}") % {
467 :games => stats['played'],
468 :channel => target.to_s
475 def define(m, params)
476 if game = @games.previous(m.replyto)
477 return unless res = Google.define(game.word)
478 m.reply "#{Bold}#{game.word}#{Bold} -- #{res}"
483 plugin = HangmanPlugin.new
484 plugin.map "hangman [play] with wordlist *wordlist", :action => 'start'
485 plugin.map "hangman [play] on :channel with word *word", :action => 'start'
486 plugin.map "hangman [play] [random] [with [:adj] length [:relation :size]]",
488 :requirements => { :adj => /min|max/, :relation => /<|<=|>=|>|==/, :size => /\d+/ }
490 plugin.map "hangman stop", :action => 'stop'
492 plugin.map "hangman score [:nick]", :action => 'score'
493 plugin.map "hangman stats", :action => 'stats'
494 plugin.map "define", :action => 'define'