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