]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/quiz.rb
Make sure the quiz plugin doesn't fail when win messages haven't been found
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / quiz.rb
1 # Plugin for the Ruby IRC bot (http://linuxbrit.co.uk/rbot/)
2 #
3 # A trivia quiz game. Fast paced, featureful and fun.
4 #
5 # (c) 2006 Mark Kretschmann <markey@web.de>
6 # (c) 2006 Jocke Andersson <ajocke@gmail.com>
7 # (c) 2006 Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
8 # Licensed under GPL V2.
9
10
11 # Class for storing question/answer pairs
12 QuizBundle = Struct.new( "QuizBundle", :question, :answer )
13
14 # Class for storing player stats
15 PlayerStats = Struct.new( "PlayerStats", :score, :jokers, :jokers_time )
16 # Why do we still need jokers_time? //Firetech
17
18 # Maximum number of jokers a player can gain
19 Max_Jokers = 3
20
21 # Control codes
22 Color = "\003"
23 Bold = "\002"
24
25
26 #######################################################################
27 # CLASS Quiz
28 # One Quiz instance per channel, contains channel specific data
29 #######################################################################
30 class Quiz
31   attr_accessor :registry, :registry_conf, :questions, :question, :answer, :answer_core,
32   :first_try, :hint, :hintrange, :rank_table, :hinted
33
34   def initialize( channel, registry )
35     if channel.empty?
36       @registry = registry.sub_registry( 'private' )
37     else
38       @registry = registry.sub_registry( channel )
39     end
40     @registry_conf = @registry.sub_registry( "config" )
41
42     # Per-channel copy of the global questions table. Acts like a shuffled queue
43     # from which questions are taken, until empty. Then we refill it with questions
44     # from the global table.
45     @registry_conf["questions"] = [] unless @registry_conf.has_key?( "questions" )
46
47     # Autoask defaults to true
48     @registry_conf["autoask"] = true unless @registry_conf.has_key?( "autoask" )
49
50     @questions = @registry_conf["questions"]
51     @question = nil
52     @answer = nil
53     @answer_core = nil
54     @first_try = false
55     @hint = nil
56     @hintrange = nil
57     @hinted = false
58
59     # We keep this array of player stats for performance reasons. It's sorted by score
60     # and always synced with the registry player stats hash. This way we can do fast
61     # rank lookups, without extra sorting.
62     @rank_table = @registry.to_a.sort { |a,b| b[1].score<=>a[1].score }
63   end
64 end
65
66
67 #######################################################################
68 # CLASS QuizPlugin
69 #######################################################################
70 class QuizPlugin < Plugin
71   def initialize()
72     super
73
74     @questions = Array.new
75     @quizzes = Hash.new
76   end
77
78   # Function that returns whether a char is a "separator", used for hints
79   #
80   def is_sep( ch )
81     return case ch
82     when " " then true
83     when "." then true
84     when "," then true
85     when "-" then true
86     when "'" then true
87     when "&" then true
88     when "\"" then true
89     else false
90     end
91   end
92
93
94   # Fetches questions from a file on the server and from the wiki, then merges
95   # and transforms the questions and fills the global question table.
96   #
97   def fetch_data( m )
98     # Read the winning messages file 
99     @win_messages = Array.new
100     if File.exists? "#{@bot.botclass}/quiz/win_messages"
101       IO.foreach("#{@bot.botclass}/quiz/win_messages") { |line| @win_messages << line.chomp }
102     else
103       warning( "win_messages file not found!" )
104       # Fill the array with a least one message or code accessing it would fail
105       @win_messages << "<who> guessed right! The answer was <answer>"
106     end
107
108     # TODO: Make this configurable, and add support for more than one file (there's a size limit in linux too ;) )
109     path = "#{@bot.botclass}/quiz/quiz.rbot"
110     debug "Fetching from #{path}"
111
112     m.reply "Fetching questions from local database and wiki.."
113
114     # Local data
115     begin
116       datafile = File.new( path, File::RDONLY )
117       localdata = datafile.read
118     rescue
119       m.reply "Failed to read local database file. oioi."
120       localdata = nil
121     end
122
123     # Wiki data
124     begin
125       serverdata = @bot.httputil.get_cached( URI.parse( "http://amarok.kde.org/amarokwiki/index.php/Rbot_Quiz" ) )
126       serverdata = serverdata.split( "QUIZ DATA START\n" )[1]
127       serverdata = serverdata.split( "\nQUIZ DATA END" )[0]
128       serverdata = serverdata.gsub( /&nbsp;/, " " ).gsub( /&amp;/, "&" ).gsub( /&quot;/, "\"" )
129     rescue
130       m.reply "Failed to download wiki questions. oioi."
131       if localdata == nil
132         m.reply "No questions loaded, aborting."
133         return
134       end
135     end
136
137     @questions = []
138
139     # Fuse together and remove comments, then split
140     data = "\n\n#{localdata}\n\n#{serverdata}".gsub( /^#.*$/, "" )
141     entries = data.split( "\nQuestion: " )
142     #First entry will be empty.
143     entries.delete_at(0)
144
145     entries.each do |e|
146       p = e.split( "\n" )
147       # We'll need at least two lines of data
148       unless p.size < 2
149         # Check if question isn't empty
150         if p[0].length > 0
151           while p[1].match( /^Answer: (.*)$/ ) == nil and p.size > 2
152             # Delete all lines between the question and the answer
153             p.delete_at(1)
154           end
155           p[1] = p[1].gsub( /Answer: /, "" ).strip
156           # If the answer was found
157           if p[1].length > 0
158             # Add the data to the array
159             b = QuizBundle.new( p[0], p[1] )
160             @questions << b
161           end
162         end
163       end
164     end
165
166     m.reply "done, #{@questions.length} questions loaded."
167   end
168
169
170   # Returns new Quiz instance for channel, or existing one
171   #
172   def create_quiz( channel )
173     unless @quizzes.has_key?( channel )
174       @quizzes[channel] = Quiz.new( channel, @registry )
175     end
176
177     return @quizzes[channel]
178   end
179
180
181   def say_score( m, nick )
182     q = create_quiz( m.channel.to_s )
183
184     if q.registry.has_key?( nick )
185       score = q.registry[nick].score
186       jokers = q.registry[nick].jokers
187
188       rank = 0
189       q.rank_table.each_index { |rank| break if nick == q.rank_table[rank][0] }
190       rank += 1
191
192       m.reply "#{nick}'s score is: #{score}    Rank: #{rank}    Jokers: #{jokers}"
193     else
194       m.reply "#{nick} does not have a score yet. Lamer."
195     end
196   end
197
198
199   def help( plugin, topic="" )
200     if topic == "admin"
201       "Quiz game aministration commands (requires authentication): 'quiz autoask <on/off>' => enable/disable autoask mode. 'quiz transfer <source> <dest> [score] [jokers]' => transfer [score] points and [jokers] jokers from <source> to <dest> (default is entire score and all jokers). 'quiz setscore <player> <score>' => set <player>'s score to <score>. 'quiz setjokers <player> <jokers>' => set <player>'s number of jokers to <jokers>. 'quiz deleteplayer <player>' => delete one player from the rank table (only works when score and jokers are set to 0)."
202     else
203       "A multiplayer trivia quiz. 'quiz' => ask a question. 'quiz hint' => get a hint. 'quiz solve' => solve this question. 'quiz skip' => skip to next question. 'quiz joker' => draw a joker to win this round. 'quiz score [player]' => show score for [player] (default is yourself). 'quiz top5' => show top 5 players. 'quiz top <number>' => show top <number> players (max 50). 'quiz stats' => show some statistics. 'quiz fetch' => refetch questions from databases.\nYou can add new questions at http://amarok.kde.org/amarokwiki/index.php/Rbot_Quiz"
204     end
205   end
206
207
208   # Updates the per-channel rank table, which is kept for performance reasons.
209   # This table contains all players sorted by rank.
210   #
211   def calculate_ranks( m, q, nick )
212     if q.registry.has_key?( nick )
213       stats = q.registry[nick]
214
215       # Find player in table
216       found_player = false
217       i = 0
218       q.rank_table.each_index do |i|
219         if nick == q.rank_table[i][0]
220           found_player = true
221           break
222         end
223       end
224
225       # Remove player from old position
226       if found_player
227         old_rank = i
228         q.rank_table.delete_at( i )
229       else
230         old_rank = nil
231       end
232
233       # Insert player at new position
234       inserted = false
235       q.rank_table.each_index do |i|
236         if stats.score > q.rank_table[i][1].score
237           q.rank_table[i,0] = [[nick, stats]]
238           inserted = true
239           break
240         end
241       end
242
243       # If less than all other players' scores, append to table 
244       unless inserted
245         i += 1 unless q.rank_table.empty?
246         q.rank_table << [nick, stats]
247       end
248
249       # Print congratulations/condolences if the player's rank has changed
250       unless old_rank.nil?
251         if i < old_rank
252           m.reply "#{nick} ascends to rank #{i + 1}. Congratulations :)"
253         elsif i > old_rank
254           m.reply "#{nick} slides down to rank #{i + 1}. So Sorry! NOT. :p"
255         end
256       end
257     else
258       q.rank_table << [[nick, PlayerStats.new( 1 )]]
259     end
260   end
261
262
263   # Reimplemented from Plugin
264   #
265   def listen( m )
266     return unless m.kind_of?(PrivMessage)
267     return unless @quizzes.has_key?( m.channel.to_s )
268     q = @quizzes[m.channel.to_s]
269
270     return if q.question == nil
271
272     message = m.message.downcase.strip
273
274     if message == q.answer.downcase or message == q.answer_core.downcase
275       points = 1
276       if q.first_try
277         points += 1
278         reply = "WHOPEEE! #{m.sourcenick.to_s} got it on the first try! That's worth an extra point. Answer was: #{q.answer}"
279       elsif q.rank_table.length >= 1 and m.sourcenick.to_s == q.rank_table[0][0]
280         reply = "THE QUIZ CHAMPION defends his throne! Seems like #{m.sourcenick.to_s} is invicible! Answer was: #{q.answer}"
281       elsif q.rank_table.length >= 2 and m.sourcenick.to_s == q.rank_table[1][0]
282         reply = "THE SECOND CHAMPION is on the way up! Hurry up #{m.sourcenick.to_s}, you only need #{q.rank_table[0][1].score - q.rank_table[1][1].score - 1} points to beat the king! Answer was: #{q.answer}"
283       elsif    q.rank_table.length >= 3 and m.sourcenick.to_s == q.rank_table[2][0]
284         reply = "THE THIRD CHAMPION strikes again! Give it all #{m.sourcenick.to_s}, with #{q.rank_table[1][1].score - q.rank_table[2][1].score - 1} more points you'll reach the 2nd place! Answer was: #{q.answer}"
285       else
286         reply = @win_messages[rand( @win_messages.length )].dup
287         reply.gsub!( "<who>", m.sourcenick )
288         reply.gsub!( "<answer>", q.answer )
289       end
290
291       m.reply reply
292
293       player = nil
294       if q.registry.has_key?( m.sourcenick.to_s )
295         player = q.registry[m.sourcenick.to_s]
296       else
297         player = PlayerStats.new( 0, 0, 0 )
298       end
299
300       player.score = player.score + points
301
302       # Reward player with a joker every X points
303       if player.score % 15 == 0 and player.jokers < Max_Jokers
304         player.jokers += 1
305         m.reply "#{m.sourcenick.to_s} gains a new joker. Rejoice :)"
306       end
307
308       q.registry[m.sourcenick.to_s] = player
309       calculate_ranks( m, q, m.sourcenick.to_s )
310
311       q.question = nil
312       cmd_quiz( m, nil ) if q.registry_conf["autoask"]
313     else
314       # First try is used, and it wasn't the answer.
315       q.first_try = false
316     end
317   end
318
319
320   # Stretches an IRC nick with dots, simply to make the client not trigger a hilight,
321   # which is annoying for those not watching. Example: markey -> m.a.r.k.e.y
322   #
323   def unhilight_nick( nick )
324     new_nick = ""
325
326     0.upto( nick.length - 1 ) do |i|
327       new_nick += nick[i, 1]
328       new_nick += "." unless i == nick.length - 1
329     end
330
331     return new_nick
332   end
333
334
335   #######################################################################
336   # Command handling
337   #######################################################################
338   def cmd_quiz( m, params )
339     fetch_data( m ) if @questions.empty?
340     q = create_quiz( m.channel.to_s )
341
342     if q.question
343       m.reply "#{Bold}#{Color}03Current question: #{Color}#{Bold}#{q.question}"
344       m.reply "Hint: #{q.hint}" if q.hinted
345       return
346     end
347
348     # Fill per-channel questions buffer
349     if q.questions.empty?
350       temp = @questions.dup
351
352       temp.length.times do
353         i = rand( temp.length )
354         q.questions << temp[i]
355         temp.delete_at( i )
356       end
357     end
358
359     i = rand( q.questions.length )
360     q.question = q.questions[i].question
361     q.answer     = q.questions[i].answer.gsub( "#", "" )
362
363     begin
364       q.answer_core = /(#)(.*)(#)/.match( q.questions[i].answer )[2]
365     rescue
366       q.answer_core = nil
367     end
368     q.answer_core = q.answer.dup if q.answer_core == nil
369
370     # Check if core answer is numerical and tell the players so, if that's the case
371     # The rather obscure statement is needed because to_i and to_f returns 99(.0) for "99 red balloons", and 0 for "balloon"
372     q.question += "#{Color}07 (Numerical answer)#{Color}" if q.answer_core.to_i.to_s == q.answer_core or q.answer_core.to_f.to_s == q.answer_core
373
374     q.questions.delete_at( i )
375
376     q.first_try = true
377
378     q.hint = ""
379     (0..q.answer_core.length-1).each do |index|
380       if is_sep(q.answer_core[index,1])
381         q.hint << q.answer_core[index]
382       else
383         q.hint << "^"
384       end
385     end
386     q.hinted = false
387
388     # Generate array of unique random range
389     q.hintrange = (0..q.answer_core.length-1).sort_by{rand}
390
391     m.reply "#{Bold}#{Color}03Question: #{Color}#{Bold}" + q.question
392   end
393
394
395   def cmd_solve( m, params )
396     return unless @quizzes.has_key?( m.channel.to_s )
397     q = @quizzes[m.channel.to_s]
398
399     m.reply "The correct answer was: #{q.answer}"
400
401     q.question = nil
402
403     cmd_quiz( m, nil ) if q.registry_conf["autoask"]
404   end
405
406
407   def cmd_hint( m, params )
408     return unless @quizzes.has_key?( m.channel.to_s )
409     q = @quizzes[m.channel.to_s]
410
411     if q.question == nil
412       m.reply "#{m.sourcenick.to_s}: Get a question first!"
413     else
414       num_chars = case q.hintrange.length    # Number of characters to reveal
415       when 25..1000 then 7
416       when 20..1000 then 6
417       when 16..1000 then 5
418       when 12..1000 then 4
419       when  8..1000 then 3
420       when  5..1000 then 2
421       when  1..1000 then 1
422       end
423
424       num_chars.times do
425         begin
426           index = q.hintrange.pop
427           # New hint char until the char isn't a "separator" (space etc.)
428         end while is_sep(q.answer_core[index,1])
429         q.hint[index] = q.answer_core[index]
430       end
431       m.reply "Hint: #{q.hint}"
432       q.hinted = true
433
434       if q.hint == q.answer_core
435         m.reply "#{Bold}#{Color}04BUST!#{Color}#{Bold} This round is over. #{Color}04Minus one point for #{m.sourcenick.to_s}#{Color}."
436
437         stats = nil
438         if q.registry.has_key?( m.sourcenick.to_s )
439           stats = q.registry[m.sourcenick.to_s]
440         else
441           stats = PlayerStats.new( 0, 0, 0 )
442         end
443
444         stats["score"] = stats.score - 1
445         q.registry[m.sourcenick.to_s] = stats
446
447         calculate_ranks( m, q, m.sourcenick.to_s )
448
449         q.question = nil
450         cmd_quiz( m, nil ) if q.registry_conf["autoask"]
451       end
452     end
453   end
454
455
456   def cmd_skip( m, params )
457     return unless @quizzes.has_key?( m.channel.to_s )
458     q = @quizzes[m.channel.to_s]
459
460     q.question = nil
461     cmd_quiz( m, params )
462   end
463
464
465   def cmd_joker( m, params )
466     q = create_quiz( m.channel.to_s )
467
468     if q.question == nil
469       m.reply "#{m.sourcenick.to_s}: There is no open question."
470       return
471     end
472
473     if q.registry[m.sourcenick.to_s].jokers > 0
474       player = q.registry[m.sourcenick.to_s]
475       player.jokers -= 1
476       player.score += 1
477       q.registry[m.sourcenick.to_s] = player
478
479       calculate_ranks( m, q, m.sourcenick.to_s )
480
481       if player.jokers != 1
482         jokers = "jokers"
483       else
484         jokers = "joker"
485       end
486       m.reply "#{Bold}#{Color}12JOKER!#{Color}#{Bold} #{m.sourcenick.to_s} draws a joker and wins this round. You have #{player.jokers} #{jokers} left."
487       m.reply "The answer was: #{q.answer}."
488
489       q.question = nil
490       cmd_quiz( m, nil ) if q.registry_conf["autoask"]
491     else
492       m.reply "#{m.sourcenick.to_s}: You don't have any jokers left ;("
493     end
494   end
495
496
497   def cmd_fetch( m, params )
498     fetch_data( m )
499   end
500
501
502   def cmd_top5( m, params )
503     q = create_quiz( m.channel.to_s )
504     if q.rank_table.empty?
505       m.reply "There are no scores known yet!"
506       return
507     end
508
509     m.reply "* Top 5 Players for #{m.channel.to_s}:"
510
511     [5, q.rank_table.length].min.times do |i|
512       player = q.rank_table[i]
513       nick = player[0]
514       score = player[1].score
515       m.reply "    #{i + 1}. #{unhilight_nick( nick )} (#{score})"
516     end
517   end
518
519
520   def cmd_top_number( m, params )
521     num = params[:number].to_i
522     return unless 1..50 === num
523     q = create_quiz( m.channel.to_s )
524     if q.rank_table.empty?
525       m.reply "There are no scores known yet!"
526       return
527     end
528
529     ar = []
530     m.reply "* Top #{num} Players for #{m.channel.to_s}:"
531     n = [ num, q.rank_table.length ].min
532     n.times do |i|
533       player = q.rank_table[i]
534       nick = player[0]
535       score = player[1].score
536       ar << "#{i + 1}. #{unhilight_nick( nick )} (#{score})"
537     end
538     m.reply ar.join(" | ")
539   end
540
541
542   def cmd_stats( m, params )
543     fetch_data( m ) if @questions.empty?
544
545     m.reply "* Total Number of Questions:"
546     m.reply "    #{@questions.length}"
547   end
548
549
550   def cmd_score( m, params )
551     say_score( m, m.sourcenick.to_s )
552   end
553
554
555   def cmd_score_player( m, params )
556     say_score( m, params[:player] )
557   end
558
559
560   def cmd_autoask( m, params )
561     q = create_quiz( m.channel.to_s )
562
563     if params[:enable].downcase == "on"
564       q.registry_conf["autoask"] = true
565       m.reply "Enabled autoask mode."
566       cmd_quiz( m, nil ) if q.question == nil
567     elsif params[:enable].downcase == "off"
568       q.registry_conf["autoask"] = false
569       m.reply "Disabled autoask mode."
570     else
571       m.reply "Invalid autoask parameter. Use 'on' or 'off'."
572     end
573   end
574
575
576   def cmd_transfer( m, params )
577     q = create_quiz( m.channel.to_s )
578
579     debug q.rank_table.inspect
580
581     source = params[:source]
582     dest = params[:dest]
583     transscore = params[:score].to_i
584     transjokers = params[:jokers].to_i
585     debug "Transferring #{transscore} points and #{transjokers} jokers from #{source} to #{dest}"
586
587     if q.registry.has_key?(source)
588       sourceplayer = q.registry[source]
589       score = sourceplayer.score
590       if transscore == -1
591         transscore = score
592       end
593       if score < transscore
594         m.reply "#{source} only has #{score} points!"
595         return
596       end
597       jokers = sourceplayer.jokers
598       if transjokers == -1
599         transjokers = jokers
600       end
601       if jokers < transjokers
602         m.reply "#{source} only has #{jokers} jokers!!"
603         return
604       end
605       if q.registry.has_key?(dest)
606         destplayer = q.registry[dest]
607       else
608         destplayer = PlayerStats.new(0,0,0)
609       end
610
611       sourceplayer.score -= transscore
612       destplayer.score += transscore
613       sourceplayer.jokers -= transjokers
614       destplayer.jokers += transjokers
615
616       q.registry[source] = sourceplayer
617       calculate_ranks(m, q, source)
618
619       q.registry[dest] = destplayer
620       calculate_ranks(m, q, dest)
621
622       m.reply "Transferred #{transscore} points and #{transjokers} jokers from #{source} to #{dest}"
623     else
624       m.reply "#{source} doesn't have any points!"
625     end
626   end
627
628
629   def cmd_del_player( m, params )
630     q = create_quiz( m.channel.to_s )
631     debug q.rank_table.inspect
632
633     nick = params[:nick]
634     if q.registry.has_key?(nick)
635       player = q.registry[nick]
636       score = player.score
637       if score != 0
638         m.reply "Can't delete player #{nick} with score #{score}."
639         return
640       end
641       jokers = player.jokers
642       if jokers != 0
643         m.reply "Can't delete player #{nick} with #{jokers} jokers."
644         return
645       end
646       q.registry.delete(nick)
647
648       player_rank = nil
649       q.rank_table.each_index { |rank|
650         if nick == q.rank_table[rank][0]
651           player_rank = rank
652           break
653         end
654       }
655       q.rank_table.delete_at(player_rank)
656
657       m.reply "Player #{nick} deleted."
658     else
659       m.reply "Player #{nick} isn't even in the database."
660     end
661   end
662
663
664   def cmd_set_score(m, params)
665     q = create_quiz( m.channel.to_s )
666     debug q.rank_table.inspect
667
668     nick = params[:nick]
669     val = params[:score].to_i
670     if q.registry.has_key?(nick)
671       player = q.registry[nick]
672       player.score = val
673     else
674       player = PlayerStats.new( val, 0, 0)
675     end
676     q.registry[nick] = player
677     calculate_ranks(m, q, nick)
678     m.reply "Score for player #{nick} set to #{val}."
679   end
680
681
682   def cmd_set_jokers(m, params)
683     q = create_quiz( m.channel.to_s )
684
685     nick = params[:nick]
686     val = [params[:jokers].to_i, Max_Jokers].min
687     if q.registry.has_key?(nick)
688       player = q.registry[nick]
689       player.jokers = val
690     else
691       player = PlayerStats.new( 0, val, 0)
692     end
693     q.registry[nick] = player
694     m.reply "Jokers for player #{nick} set to #{val}."
695   end
696 end
697
698
699
700 plugin = QuizPlugin.new
701 plugin.default_auth( 'edit', false )
702
703 # Normal commands
704 plugin.map 'quiz',                  :action => 'cmd_quiz'
705 plugin.map 'quiz solve',            :action => 'cmd_solve'
706 plugin.map 'quiz hint',             :action => 'cmd_hint'
707 plugin.map 'quiz skip',             :action => 'cmd_skip'
708 plugin.map 'quiz joker',            :action => 'cmd_joker'
709 plugin.map 'quiz score',            :action => 'cmd_score'
710 plugin.map 'quiz score :player',    :action => 'cmd_score_player'
711 plugin.map 'quiz fetch',            :action => 'cmd_fetch'
712 plugin.map 'quiz top5',             :action => 'cmd_top5'
713 plugin.map 'quiz top :number',      :action => 'cmd_top_number'
714 plugin.map 'quiz stats',            :action => 'cmd_stats'
715
716 # Admin commands
717 plugin.map 'quiz autoask :enable',  :action => 'cmd_autoask', :auth_path => 'edit'
718 plugin.map 'quiz transfer :source :dest :score :jokers', :action => 'cmd_transfer', :auth_path => 'edit', :defaults => {:score => '-1', :jokers => '-1'}
719 plugin.map 'quiz deleteplayer :nick', :action => 'cmd_del_player', :auth_path => 'edit'
720 plugin.map 'quiz setscore :nick :score', :action => 'cmd_set_score', :auth_path => 'edit'
721 plugin.map 'quiz setjokers :nick :jokers', :action => 'cmd_set_jokers', :auth_path => 'edit'