summaryrefslogtreecommitdiff
path: root/data/rbot/plugins/games/hangman.rb
blob: 197d60e90bf55bff4f1980ce2f9b71cb58d3edda (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#-- vim:sw=2:et
#++
#
# :title: Hangman Plugin
#
# Author:: Raine Virta <rane@kapsi.fi>
# Copyright:: (C) 2009 Raine Virta
# License:: GPL v2
#
# Description:: Hangman game for rbot
#
# TODO:: scoring and stats
#        some sort of turn-basedness, maybe

module RandomWord
  SITE = "http://coyotecult.com/tools/randomwordgenerator.php"

  def self.get(count=1)
    res = Net::HTTP.post_form(URI.parse(SITE), {'numwords' => count})
    words = res.body.scan(%r{<a.*?\?w=(.*?)\n}).flatten

    count == 1 ? words.first : words
  end
end

class Hangman
  attr_reader :misses, :guesses, :word, :letters

  STAGES = [' (x_x) ', ' (;_;) ', ' (>_<) ', ' (-_-) ', ' (o_~) ', ' (^_^) ', '\(^o^)/']
  HEALTH = STAGES.size-1
  LETTER = /[^\W0-9_]/u

  def initialize(word, channel=nil)
    @word    = word
    @guesses = []
    @misses  = []
    @health  = HEALTH
    @solved  = false
  end

  def letters
    # array of the letters in the word
    @word.split(//u).reject { |c| c !~ LETTER  }.map { |c| c.downcase }
  end

  def face
    STAGES[@health]
  end

  def to_s
    # creates a string that presents the word with unknown letters shown as underscores
    @word.split(//).map { |c|
      @guesses.include?(c.downcase) || c !~ LETTER  ? c : "_"
    }.join
  end

  def guess(str)
    str.downcase!

    # full word guess
    if str !~ /^#{LETTER}$/u
      word.downcase == str ? @solved = true : punish
    else # single letter guess
      return false if @guesses.include?(str) # letter has been guessed before

      unless letters.include?(str)
        @misses << str
        punish
      end

      @guesses << str
    end
  end

  def over?
    won? || lost?
  end

  def won?
    (letters - @guesses).empty? || @solved
  end

  def lost?
    @health.zero?
  end

  def punish
    @health -= 1
  end
end

class HangmanPlugin < Plugin
  def initialize
    super
    @games = {}
    @settings = {}
  end

  def help(plugin, topic="")
    case topic
    when ""
      return "hangman game plugin - topics: play, stop"
    when "play"
      return "hangman play on <channel> with word <word> => use in private chat with the bot to start a game with custom word\n"+
             "hangman play random [with [max|min] length [<|>|== <length>]] => hangman with a random word from #{RandomWord::SITE}\n"+
             "hangman play with wordlist <wordlist> => hangman with random word from <wordlist>"
    when "stop"
      return "hangman stop => quits the current game"
    end
  end

  def get_word(params)
    if params[:word]
      params[:word].join(" ")
    elsif params[:wordlist]
      begin
        wordlist = Wordlist.get(params[:wordlist].join("/"), :spaces => true)
      rescue
        raise "no such wordlist"
      end

      wordlist[rand(wordlist.size)]
    else # getting a random word
      words = RandomWord::get(100)

      if adj = params[:adj]
        words = words.sort_by { |e| e.size }

        if adj == "max"
          words.last
        else
          words.first
        end
      elsif params[:relation] && params[:size]
        words = words.select { |w| w.size.send(params[:relation], params[:size].to_i) }

        unless words.empty?
          words.first
        else
          m.reply "suitable word not found in the set"
          nil
        end
      else
        words.first
      end
    end
  end

  def start(m, params)
    begin
      word = get_word(params) || return
    rescue => e
      m.reply e.message
      return
    end

    if (params[:channel] || m.public?)
      target = if m.public?
        m.channel.to_s
      else
        params[:channel]
      end

      # is the bot on the channel?
      unless @bot.server.channels.names.include?(target.to_s)
        m.reply "i'm not on that channel"
        return
      end

      if @games.has_key?(target)
        m.reply "there's already a hangman game in progress on the channel"
        return
      end

      @bot.say target, "#{m.source} has started a hangman -- join the fun!"
    else
      target = m.source.to_s
    end

    @games[target]    = Hangman.new(word)
    @settings[target] = params

    @bot.say target, game_status(@games[target])
  end

  def stop(m, params)
    source = if m.public?
      m.channel
    else
      m.source
    end

    if @games.has_key?(source.to_s)
      @bot.say source, "oh well, the answer would've been #{Bold}#{@games[source.to_s].word}#{Bold}"
      @games.delete(source.to_s)
    end
  end

  def message(m)
    source = if m.public?
      m.channel.to_s
    else
      m.source.to_s
    end

    if game = @games[source]
      if m.message =~ /^[^\W0-9_]$/u || m.message =~ prepare_guess_regex(game)
        return unless game.guess(m.message)

        m.reply game_status(game)
      end

      if game.over?
        if game.won?
          str = "you nailed it!"
        elsif game.lost?
          str = "you've killed the poor guy :("
        end

        m.reply "#{str} go #{Bold}again#{Bold}?"

        @games.delete(source)
      end
    elsif @settings[source] && m.message =~ /^(?:again|more!?$)/i
      start(m, @settings[source])
    end
  end

  def prepare_guess_regex(game)
    Regexp.new("^#{game.word.split(//).map { |c|
      game.guesses.include?(c) || c !~ Hangman::LETTER ? c : '[^\W0-9_]'
    }.join("")}$")
  end

  def game_status(game)
    "%{word} %{face} %{misses}" % {
      :word   => game.over? ? "#{Bold}#{game.word}#{Bold}" : game.to_s,
      :face   => game.face,
      :misses => game.misses.map { |e| e.upcase }.join(" ")
    }
  end
end

plugin = HangmanPlugin.new
plugin.map "hangman [play] with wordlist *wordlist", :action => 'start'
plugin.map "hangman [play] on :channel with word *word", :action => 'start'
plugin.map "hangman [play] [random] [with [:adj] length [:relation :size]]",
  :action => 'start',
  :requirements => { :adj => /min|max/, :relation => /<|<=|>=|>|==/, :size => /\d+/ }

plugin.map "hangman stop", :action => 'stop'