4 # :title: Quiz plugin for rbot
6 # Author:: Mark Kretschmann <markey@web.de>
7 # Author:: Jocke Andersson <ajocke@gmail.com>
8 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
9 # Author:: Yaohan Chen <yaohan.chen@gmail.com>
11 # Copyright:: (C) 2006 Mark Kretschmann, Jocke Andersson, Giuseppe Bilotta
12 # Copyright:: (C) 2007 Giuseppe Bilotta, Yaohan Chen
16 # A trivia quiz game. Fast paced, featureful and fun.
18 # FIXME:: interesting fact: in the Quiz class, @registry.has_key? seems to be
19 # case insensitive. Although this is all right for us, this leads to
20 # rank vs registry mismatches. So we have to make the @rank_table
21 # comparisons case insensitive as well. For the moment, redefine
22 # everything to downcase before matching the nick.
24 # TODO:: define a class for the rank table. We might also need it for scoring
27 # TODO:: when Ruby 2.0 gets out, fix the FIXME 2.0 UTF-8 workarounds
29 # Class for storing question/answer pairs
30 define_structure :QuizBundle, :question, :answer
32 # Class for storing player stats
33 define_structure :PlayerStats, :score, :jokers, :jokers_time
34 # Why do we still need jokers_time? //Firetech
41 #######################################################################
43 # Abstract an answer to a quiz question, by providing self as a string
44 # and a core that can be answered as an alternative. It also provides
45 # a boolean that tells if the core is numeric or not
46 #######################################################################
53 if @string =~ /#(.+)#/
55 @string.gsub!('#', '')
57 raise ArgumentError, "empty string can't be a valid answer!" if @string.empty?
58 raise ArgumentError, "empty core can't be a valid answer!" if @core and @core.empty?
60 @numeric = (core.to_i.to_s == core) || (core.to_f.to_s == core)
73 str.downcase == core.downcase || str.downcase == @string.downcase
85 #######################################################################
87 # One Quiz instance per channel, contains channel specific data
88 #######################################################################
90 attr_accessor :registry, :registry_conf, :questions,
91 :question, :answers, :canonical_answer, :answer_array,
92 :first_try, :hint, :hintrange, :rank_table, :hinted, :has_errors,
95 def initialize( channel, registry )
97 @registry = registry.sub_registry( 'private' )
99 @registry = registry.sub_registry( channel.downcase )
102 @registry.each_key { |k|
103 unless @registry.has_key?(k)
105 error "Data for #{k} is NOT ACCESSIBLE! Database corrupt?"
109 debug @registry.to_a.map { |a| a.join(", ")}.join("\n")
112 @registry_conf = @registry.sub_registry( "config" )
114 # Per-channel list of sources. If empty, the default one (quiz/quiz.rbot)
116 @registry_conf["sources"] = [] unless @registry_conf.has_key?( "sources" )
118 # Per-channel copy of the global questions table. Acts like a shuffled queue
119 # from which questions are taken, until empty. Then we refill it with questions
120 # from the global table.
121 @registry_conf["questions"] = [] unless @registry_conf.has_key?( "questions" )
123 # Autoask defaults to true
124 @registry_conf["autoask"] = true unless @registry_conf.has_key?( "autoask" )
126 # Autoask delay defaults to 0 (instantly)
127 @registry_conf["autoask_delay"] = 0 unless @registry_conf.has_key?( "autoask_delay" )
129 @questions = @registry_conf["questions"]
132 @canonical_answer = nil
141 # True if the answers is entirely done by separators
144 # We keep this array of player stats for performance reasons. It's sorted by score
145 # and always synced with the registry player stats hash. This way we can do fast
146 # rank lookups, without extra sorting.
147 @rank_table = @registry.to_a.sort { |a,b| b[1].score<=>a[1].score }
152 #######################################################################
154 #######################################################################
155 class QuizPlugin < Plugin
156 Config.register Config::BooleanValue.new('quiz.dotted_nicks',
158 :desc => "When true, nicks in the top X scores will be camouflaged to prevent IRC hilighting")
160 Config.register Config::ArrayValue.new('quiz.sources',
161 :default => ['quiz.rbot'],
162 :desc => "List of files and URLs that will be used to retrieve quiz questions")
165 Config.register Config::IntegerValue.new('quiz.max_jokers',
167 :desc => "Maximum number of jokers a player can gain")
172 @questions = Array.new
175 @ask_mutex = Mutex.new
178 # Function that returns whether a char is a "separator", used for hints
185 # Fetches questions from the data sources, which can be either local files
186 # (in quiz/) or web pages.
189 # Read the winning messages file
190 @win_messages = Array.new
191 winfile = datafile 'win_messages'
192 if File.exists? winfile
193 IO.foreach(winfile) { |line| @win_messages << line.chomp }
195 warning( "win_messages file not found!" )
196 # Fill the array with a least one message or code accessing it would fail
197 @win_messages << "<who> guessed right! The answer was <answer>"
200 m.reply "Fetching questions ..."
202 # TODO Per-channel sources
205 @bot.config['quiz.sources'].each { |p|
206 if p =~ /^https?:\/\//
209 serverdata = @bot.httputil.get(p) # "http://amarok.kde.org/amarokwiki/index.php/Rbot_Quiz"
210 serverdata = serverdata.split( "QUIZ DATA START\n" )[1]
211 serverdata = serverdata.split( "\nQUIZ DATA END" )[0]
212 serverdata = serverdata.gsub( / /, " " ).gsub( /&/, "&" ).gsub( /"/, "\"" )
213 data << "\n\n" << serverdata
215 m.reply "Failed to download questions from #{p}, ignoring sources"
219 debug "Fetching from #{path}"
223 data << "\n\n" << File.read(path)
225 m.reply "Failed to read from local database file #{p}, skipping."
232 # Fuse together and remove comments, then split
233 entries = data.strip.gsub( /^#.*$/, "" ).split( /(?:^|\n+)Question: / )
237 # We'll need at least two lines of data
239 # Check if question isn't empty
241 while p[1].match( /^Answer: (.*)$/ ) == nil and p.size > 2
242 # Delete all lines between the question and the answer
245 p[1] = p[1].gsub( /Answer: /, "" ).strip
246 # If the answer was found
248 # Add the data to the array
249 b = QuizBundle.new( p[0], p[1] )
256 m.reply "done, #{@questions.length} questions loaded."
260 # Returns new Quiz instance for channel, or existing one
261 # Announce errors if a message is passed as second parameter
263 def create_quiz(channel, m=nil)
264 unless @quizzes.has_key?( channel )
265 @quizzes[channel] = Quiz.new( channel, @registry )
268 if @quizzes[channel].has_errors
269 m.reply _("Sorry, the quiz database for %{chan} seems to be corrupt") % {
274 return @quizzes[channel]
279 def say_score( m, nick )
281 q = create_quiz( chan, m )
284 if q.registry.has_key?( nick )
285 score = q.registry[nick].score
286 jokers = q.registry[nick].jokers
289 q.rank_table.each do |place|
291 break if nick.downcase == place[0].downcase
294 m.reply "#{nick}'s score is: #{score} Rank: #{rank} Jokers: #{jokers}"
296 m.reply "#{nick} does not have a score yet. Lamer."
301 def help( plugin, topic="" )
303 _("Quiz game aministration commands (requires authentication): ") + [
304 _("'quiz autoask <on/off>' => enable/disable autoask mode"),
305 _("'quiz autoask delay <secs>' => delay next quiz by <secs> seconds when in autoask mode"),
306 _("'quiz transfer <source> <dest> [score] [jokers]' => transfer [score] points and [jokers] jokers from <source> to <dest> (default is entire score and all jokers)"),
307 _("'quiz setscore <player> <score>' => set <player>'s score to <score>"),
308 _("'quiz setjokers <player> <jokers>' => set <player>'s number of jokers to <jokers>"),
309 _("'quiz deleteplayer <player>' => delete one player from the rank table (only works when score and jokers are set to 0)"),
310 _("'quiz cleanup' => remove players with no points and no jokers")
313 urls = @bot.config['quiz.sources'].select { |p| p =~ /^https?:\/\// }
314 "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. 'quiz refresh' => refresh the question pool for this channel." + (urls.empty? ? "" : "\nYou can add new questions at #{urls.join(', ')}")
319 # Updates the per-channel rank table, which is kept for performance reasons.
320 # This table contains all players sorted by rank.
322 def calculate_ranks( m, q, nick )
323 if q.registry.has_key?( nick )
324 stats = q.registry[nick]
326 # Find player in table
328 q.rank_table.each_with_index do |place, i|
329 if nick.downcase == place[0].downcase
335 # Remove player from old position
337 q.rank_table.delete_at( old_rank )
340 # Insert player at new position
342 q.rank_table.each_with_index do |place, i|
343 if stats.score > place[1].score
344 q.rank_table[i,0] = [[nick, stats]]
350 # If less than all other players' scores, append to table
352 new_rank = q.rank_table.length
353 q.rank_table << [nick, stats]
356 # Print congratulations/condolences if the player's rank has changed
358 if new_rank < old_rank
359 m.reply "#{nick} ascends to rank #{new_rank + 1}. Congratulations :)"
360 elsif new_rank > old_rank
361 m.reply "#{nick} slides down to rank #{new_rank + 1}. So Sorry! NOT. :p"
365 q.rank_table << [[nick, PlayerStats.new( 1 )]]
370 # Reimplemented from Plugin
374 return unless @quizzes.has_key?( chan )
377 return if q.question == nil
379 message = m.message.downcase.strip
381 nick = m.sourcenick.to_s
383 # Support multiple alternate answers and cores
384 answer = q.answers.find { |ans| ans.valid?(message) }
386 # List canonical answer which the hint was based on, to avoid confusion
387 # FIXME display this more friendly
388 answer.info = " (hints were for alternate answer #{q.canonical_answer.core})" if answer != q.canonical_answer and q.hinted
393 reply = "WHOPEEE! #{nick} got it on the first try! That's worth an extra point. Answer was: #{answer}"
394 elsif q.rank_table.length >= 1 and nick.downcase == q.rank_table[0][0].downcase
395 reply = "THE QUIZ CHAMPION defends his throne! Seems like #{nick} is invicible! Answer was: #{answer}"
396 elsif q.rank_table.length >= 2 and nick.downcase == q.rank_table[1][0].downcase
397 reply = "THE SECOND CHAMPION is on the way up! Hurry up #{nick}, you only need #{q.rank_table[0][1].score - q.rank_table[1][1].score - 1} points to beat the king! Answer was: #{answer}"
398 elsif q.rank_table.length >= 3 and nick.downcase == q.rank_table[2][0].downcase
399 reply = "THE THIRD CHAMPION strikes again! Give it all #{nick}, with #{q.rank_table[1][1].score - q.rank_table[2][1].score - 1} more points you'll reach the 2nd place! Answer was: #{answer}"
401 reply = @win_messages[rand( @win_messages.length )].dup
402 reply.gsub!( "<who>", nick )
403 reply.gsub!( "<answer>", answer )
409 if q.registry.has_key?(nick)
410 player = q.registry[nick]
412 player = PlayerStats.new( 0, 0, 0 )
415 player.score = player.score + points
417 # Reward player with a joker every X points
418 if player.score % 15 == 0 and player.jokers < @bot.config['quiz.max_jokers']
420 m.reply "#{nick} gains a new joker. Rejoice :)"
423 q.registry[nick] = player
424 calculate_ranks( m, q, nick)
427 if q.registry_conf["autoask"]
428 delay = q.registry_conf["autoask_delay"]
430 m.reply "#{Bold}#{Color}03Next question in #{Bold}#{delay}#{Bold} seconds"
431 timer = @bot.timer.add_once(delay) {
432 @ask_mutex.synchronize do
433 @waiting.delete(chan)
437 @waiting[chan] = timer
443 # First try is used, and it wasn't the answer.
449 # Stretches an IRC nick with dots, simply to make the client not trigger a hilight,
450 # which is annoying for those not watching. Example: markey -> m.a.r.k.e.y
452 def unhilight_nick( nick )
453 return nick unless @bot.config['quiz.dotted_nicks']
454 return nick.split(//).join(".")
458 #######################################################################
460 #######################################################################
461 def cmd_quiz( m, params )
462 fetch_data( m ) if @questions.empty?
465 @ask_mutex.synchronize do
466 if @waiting.has_key?(chan)
467 m.reply "Next quiz question will be automatically asked soon, have patience"
472 q = create_quiz( chan, m )
476 m.reply "#{Bold}#{Color}03Current question: #{Color}#{Bold}#{q.question}"
477 m.reply "Hint: #{q.hint}" if q.hinted
481 # Fill per-channel questions buffer
482 if q.questions.empty?
483 q.questions = @questions.sort_by { rand }
486 # pick a question and delete it (delete_at returns the deleted item)
487 picked = q.questions.delete_at( rand(q.questions.length) )
489 q.question = picked.question
490 q.answers = picked.answer.split(/\s+\|\|\s+/).map { |ans| QuizAnswer.new(ans) }
492 # Check if any core answer is numerical and tell the players so, if that's the case
493 # The rather obscure statement is needed because to_i and to_f returns 99(.0) for "99 red balloons", and 0 for "balloon"
495 # The "canonical answer" is also determined here, defined to be the first found numerical answer, or
497 numeric = q.answers.find { |ans| ans.numeric? }
499 q.question += "#{Color}07 (Numerical answer)#{Color}"
500 q.canonical_answer = numeric
502 q.canonical_answer = q.answers.first
510 q.canonical_answer.core.scan(/./u) { |ch|
519 # It's possible that an answer is entirely done by separators,
520 # in which case we'll hide everything
521 if q.answer_array == q.hint
529 # Generate array of unique random range
530 q.hintrange = (0..q.hint.length-1).sort_by{ rand }
532 m.reply "#{Bold}#{Color}03Question: #{Color}#{Bold}" + q.question
536 def cmd_solve( m, params )
539 return unless @quizzes.has_key?( chan )
542 m.reply "The correct answer was: #{q.canonical_answer}"
546 cmd_quiz( m, nil ) if q.registry_conf["autoask"]
550 def cmd_hint( m, params )
552 nick = m.sourcenick.to_s
554 return unless @quizzes.has_key?(chan)
558 m.reply "#{nick}: Get a question first!"
560 num_chars = case q.hintrange.length # Number of characters to reveal
573 index = q.hintrange.pop
574 # New hint char until the char isn't a "separator" (space etc.)
575 end while is_sep(q.answer_array[index]) and not q.all_seps
576 q.hint[index] = q.answer_array[index]
578 m.reply "Hint: #{q.hint}"
582 if q.hint == q.answer_array
583 m.reply "#{Bold}#{Color}04BUST!#{Color}#{Bold} This round is over. #{Color}04Minus one point for #{nick}#{Color}."
586 if q.registry.has_key?( nick )
587 stats = q.registry[nick]
589 stats = PlayerStats.new( 0, 0, 0 )
592 stats["score"] = stats.score - 1
593 q.registry[nick] = stats
595 calculate_ranks( m, q, nick)
598 cmd_quiz( m, nil ) if q.registry_conf["autoask"]
604 def cmd_skip( m, params )
606 return unless @quizzes.has_key?(chan)
610 cmd_quiz( m, params )
614 def cmd_joker( m, params )
616 nick = m.sourcenick.to_s
617 q = create_quiz(chan, m)
621 m.reply "#{nick}: There is no open question."
625 if q.registry[nick].jokers > 0
626 player = q.registry[nick]
629 q.registry[nick] = player
631 calculate_ranks( m, q, nick )
633 if player.jokers != 1
638 m.reply "#{Bold}#{Color}12JOKER!#{Color}#{Bold} #{nick} draws a joker and wins this round. You have #{player.jokers} #{jokers} left."
639 m.reply "The answer was: #{q.canonical_answer}."
642 cmd_quiz( m, nil ) if q.registry_conf["autoask"]
644 m.reply "#{nick}: You don't have any jokers left ;("
649 def cmd_fetch( m, params )
654 def cmd_refresh( m, params )
655 q = create_quiz(m.channel)
658 cmd_quiz( m, params )
662 def cmd_top5( m, params )
664 q = create_quiz( chan, m )
667 if q.rank_table.empty?
668 m.reply "There are no scores known yet!"
672 m.reply "* Top 5 Players for #{chan}:"
674 [5, q.rank_table.length].min.times do |i|
675 player = q.rank_table[i]
677 score = player[1].score
678 m.reply " #{i + 1}. #{unhilight_nick( nick )} (#{score})"
683 def cmd_top_number( m, params )
684 num = params[:number].to_i
685 return if num < 1 or num > 50
687 q = create_quiz( chan, m )
690 if q.rank_table.empty?
691 m.reply "There are no scores known yet!"
696 m.reply "* Top #{num} Players for #{chan}:"
697 n = [ num, q.rank_table.length ].min
699 player = q.rank_table[i]
701 score = player[1].score
702 ar << "#{i + 1}. #{unhilight_nick( nick )} (#{score})"
704 m.reply ar.join(" | "), :split_at => /\s+\|\s+/
708 def cmd_stats( m, params )
709 fetch_data( m ) if @questions.empty?
711 m.reply "* Total Number of Questions:"
712 m.reply " #{@questions.length}"
716 def cmd_score( m, params )
717 nick = m.sourcenick.to_s
722 def cmd_score_player( m, params )
723 say_score( m, params[:player] )
727 def cmd_autoask( m, params )
729 q = create_quiz( chan, m )
732 params[:enable] ||= 'status'
734 case params[:enable].downcase
736 q.registry_conf["autoask"] = true
737 m.reply "Enabled autoask mode."
738 cmd_quiz( m, nil ) if q.question == nil
740 q.registry_conf["autoask"] = false
741 m.reply "Disabled autoask mode."
743 m.reply _("Autoask is %{status}, the delay is %{time}") % {
744 :status => q.registry_conf["autoask"],
745 :time => Utils.secs_to_string(q.registry_conf["autoask_delay"]),
748 m.reply "Invalid autoask parameter. Use 'on' or 'off' to set it, 'status' to check the current status."
752 def cmd_autoask_delay( m, params )
754 q = create_quiz( chan, m )
757 delay = params[:time].to_i
758 q.registry_conf["autoask_delay"] = delay
759 m.reply "Autoask delay now #{q.registry_conf['autoask_delay']} seconds"
762 def cmd_transfer( m, params )
764 q = create_quiz( chan, m )
767 debug q.rank_table.inspect
769 source = params[:source]
771 transscore = params[:score].to_i
772 transjokers = params[:jokers].to_i
773 debug "Transferring #{transscore} points and #{transjokers} jokers from #{source} to #{dest}"
775 if q.registry.has_key?(source)
776 sourceplayer = q.registry[source]
777 score = sourceplayer.score
781 if score < transscore
782 m.reply "#{source} only has #{score} points!"
785 jokers = sourceplayer.jokers
789 if jokers < transjokers
790 m.reply "#{source} only has #{jokers} jokers!!"
793 if q.registry.has_key?(dest)
794 destplayer = q.registry[dest]
796 destplayer = PlayerStats.new(0,0,0)
799 if sourceplayer.object_id == destplayer.object_id
800 m.reply "Source and destination are the same, I'm not going to touch them"
804 sourceplayer.score -= transscore
805 destplayer.score += transscore
806 sourceplayer.jokers -= transjokers
807 destplayer.jokers += transjokers
809 q.registry[source] = sourceplayer
810 calculate_ranks(m, q, source)
812 q.registry[dest] = destplayer
813 calculate_ranks(m, q, dest)
815 m.reply "Transferred #{transscore} points and #{transjokers} jokers from #{source} to #{dest}"
817 m.reply "#{source} doesn't have any points!"
822 def cmd_del_player( m, params )
824 q = create_quiz( chan, m )
827 debug q.rank_table.inspect
830 if q.registry.has_key?(nick)
831 player = q.registry[nick]
834 m.reply "Can't delete player #{nick} with score #{score}."
837 jokers = player.jokers
839 m.reply "Can't delete player #{nick} with #{jokers} jokers."
842 q.registry.delete(nick)
845 q.rank_table.each_index { |rank|
846 if nick.downcase == q.rank_table[rank][0].downcase
851 q.rank_table.delete_at(player_rank)
853 m.reply "Player #{nick} deleted."
855 m.reply "Player #{nick} isn't even in the database."
860 def cmd_set_score(m, params)
862 q = create_quiz( chan, m )
865 debug q.rank_table.inspect
868 val = params[:score].to_i
869 if q.registry.has_key?(nick)
870 player = q.registry[nick]
873 player = PlayerStats.new( val, 0, 0)
875 q.registry[nick] = player
876 calculate_ranks(m, q, nick)
877 m.reply "Score for player #{nick} set to #{val}."
881 def cmd_set_jokers(m, params)
883 q = create_quiz( chan, m )
886 debug q.rank_table.inspect
889 val = [params[:jokers].to_i, @bot.config['quiz.max_jokers']].min
890 if q.registry.has_key?(nick)
891 player = q.registry[nick]
894 player = PlayerStats.new( 0, val, 0)
896 q.registry[nick] = player
897 m.reply "Jokers for player #{nick} set to #{val}."
901 def cmd_cleanup(m, params)
903 q = create_quiz( chan, m )
907 q.registry.each { |nick, player|
908 null_players << nick if player.jokers == 0 and player.score == 0
910 debug "Cleaning up by removing #{null_players * ', '}"
911 null_players.each { |nick|
912 cmd_del_player(m, :nick => nick)
919 m.reply 'you must be on some channel to use this command'
922 if @quizzes.delete m.channel
923 @ask_mutex.synchronize do
924 t = @waiting.delete(m.channel)
925 @bot.timer.remove t if t
929 m.reply(_("there is no active quiz on #{m.channel}"))
935 plugin = QuizPlugin.new
936 plugin.default_auth( 'edit', false )
939 plugin.map 'quiz', :action => 'cmd_quiz'
940 plugin.map 'quiz solve', :action => 'cmd_solve'
941 plugin.map 'quiz hint', :action => 'cmd_hint'
942 plugin.map 'quiz skip', :action => 'cmd_skip'
943 plugin.map 'quiz joker', :action => 'cmd_joker'
944 plugin.map 'quiz score', :action => 'cmd_score'
945 plugin.map 'quiz score :player', :action => 'cmd_score_player'
946 plugin.map 'quiz fetch', :action => 'cmd_fetch'
947 plugin.map 'quiz refresh', :action => 'cmd_refresh'
948 plugin.map 'quiz top5', :action => 'cmd_top5'
949 plugin.map 'quiz top :number', :action => 'cmd_top_number'
950 plugin.map 'quiz stats', :action => 'cmd_stats'
951 plugin.map 'quiz stop', :action => :stop
954 plugin.map 'quiz autoask [:enable]', :action => 'cmd_autoask', :auth_path => 'edit'
955 plugin.map 'quiz autoask delay :time', :action => 'cmd_autoask_delay', :auth_path => 'edit', :requirements => {:time => /\d+/}
956 plugin.map 'quiz transfer :source :dest :score :jokers', :action => 'cmd_transfer', :auth_path => 'edit', :defaults => {:score => '-1', :jokers => '-1'}
957 plugin.map 'quiz deleteplayer :nick', :action => 'cmd_del_player', :auth_path => 'edit'
958 plugin.map 'quiz setscore :nick :score', :action => 'cmd_set_score', :auth_path => 'edit'
959 plugin.map 'quiz setjokers :nick :jokers', :action => 'cmd_set_jokers', :auth_path => 'edit'
960 plugin.map 'quiz cleanup', :action => 'cmd_cleanup', :auth_path => 'edit'