]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/games/quiz.rb
quiz: refactor quiz db problem announcement
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / games / quiz.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Quiz plugin for rbot
5 #
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>
10 #
11 # Copyright:: (C) 2006 Mark Kretschmann, Jocke Andersson, Giuseppe Bilotta
12 # Copyright:: (C) 2007 Giuseppe Bilotta, Yaohan Chen
13 #
14 # License:: GPL v2
15 #
16 # A trivia quiz game. Fast paced, featureful and fun.
17
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.
23 #
24 # TODO:: define a class for the rank table. We might also need it for scoring
25 #        in other games.
26 #
27 # TODO:: when Ruby 2.0 gets out, fix the FIXME 2.0 UTF-8 workarounds
28
29 # Class for storing question/answer pairs
30 define_structure :QuizBundle, :question, :answer
31
32 # Class for storing player stats
33 define_structure :PlayerStats, :score, :jokers, :jokers_time
34 # Why do we still need jokers_time? //Firetech
35
36 # Control codes
37 Color = "\003"
38 Bold = "\002"
39
40
41 #######################################################################
42 # CLASS QuizAnswer
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 #######################################################################
47 class QuizAnswer
48   attr_writer :info
49
50   def initialize(str)
51     @string = str.strip
52     @core = nil
53     if @string =~ /#(.+)#/
54       @core = $1
55       @string.gsub!('#', '')
56     end
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?
59
60     @numeric = (core.to_i.to_s == core) || (core.to_f.to_s == core)
61     @info = nil
62   end
63
64   def core
65     @core || @string
66   end
67
68   def numeric?
69     @numeric
70   end
71
72   def valid?(str)
73     str.downcase == core.downcase || str.downcase == @string.downcase
74   end
75
76   def to_str
77     [@string, @info].join
78   end
79   alias :to_s :to_str
80
81
82 end
83
84
85 #######################################################################
86 # CLASS Quiz
87 # One Quiz instance per channel, contains channel specific data
88 #######################################################################
89 class Quiz
90   attr_accessor :registry, :registry_conf, :questions,
91     :question, :answers, :canonical_answer, :answer_array,
92     :first_try, :hint, :hintrange, :rank_table, :hinted, :has_errors,
93     :all_seps
94
95   def initialize( channel, registry )
96     if !channel
97       @registry = registry.sub_registry( 'private' )
98     else
99       @registry = registry.sub_registry( channel.downcase )
100     end
101     @has_errors = false
102     @registry.each_key { |k|
103       unless @registry.has_key?(k)
104         @has_errors = true
105         error "Data for #{k} is NOT ACCESSIBLE! Database corrupt?"
106       end
107     }
108     if @has_errors
109       debug @registry.to_a.map { |a| a.join(", ")}.join("\n")
110     end
111
112     @registry_conf = @registry.sub_registry( "config" )
113
114     # Per-channel list of sources. If empty, the default one (quiz/quiz.rbot)
115     # will be used. TODO
116     @registry_conf["sources"] = [] unless @registry_conf.has_key?( "sources" )
117
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" )
122
123     # Autoask defaults to true
124     @registry_conf["autoask"] = true unless @registry_conf.has_key?( "autoask" )
125
126     # Autoask delay defaults to 0 (instantly)
127     @registry_conf["autoask_delay"] = 0 unless @registry_conf.has_key?( "autoask_delay" )
128
129     @questions = @registry_conf["questions"]
130     @question = nil
131     @answers = []
132     @canonical_answer = nil
133     # FIXME 2.0 UTF-8
134     @answer_array = []
135     @first_try = false
136     # FIXME 2.0 UTF-8
137     @hint = []
138     @hintrange = nil
139     @hinted = false
140
141     # True if the answers is entirely done by separators
142     @all_seps = false
143
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 }
148   end
149 end
150
151
152 #######################################################################
153 # CLASS QuizPlugin
154 #######################################################################
155 class QuizPlugin < Plugin
156   Config.register Config::BooleanValue.new('quiz.dotted_nicks',
157     :default => true,
158     :desc => "When true, nicks in the top X scores will be camouflaged to prevent IRC hilighting")
159
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")
163
164
165   Config.register Config::IntegerValue.new('quiz.max_jokers',
166     :default => 3,
167     :desc => "Maximum number of jokers a player can gain")
168
169   def initialize()
170     super
171
172     @questions = Array.new
173     @quizzes = Hash.new
174     @waiting = Hash.new
175     @ask_mutex = Mutex.new
176   end
177
178   # Function that returns whether a char is a "separator", used for hints
179   #
180   def is_sep( ch )
181     return ch !~ /^\w$/u
182   end
183
184
185   # Fetches questions from the data sources, which can be either local files
186   # (in quiz/) or web pages.
187   #
188   def fetch_data( m )
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 }
194     else
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>"
198     end
199
200     m.reply "Fetching questions ..."
201
202     # TODO Per-channel sources
203
204     data = ""
205     @bot.config['quiz.sources'].each { |p|
206       if p =~ /^https?:\/\//
207         # Wiki data
208         begin
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( /&nbsp;/, " " ).gsub( /&amp;/, "&" ).gsub( /&quot;/, "\"" )
213           data << "\n\n" << serverdata
214         rescue
215           m.reply "Failed to download questions from #{p}, ignoring sources"
216         end
217       else
218         path = datafile p
219         debug "Fetching from #{path}"
220
221         # Local data
222         begin
223           data << "\n\n" << File.read(path)
224         rescue
225           m.reply "Failed to read from local database file #{p}, skipping."
226         end
227       end
228     }
229
230     @questions.clear
231
232     # Fuse together and remove comments, then split
233     entries = data.strip.gsub( /^#.*$/, "" ).split( /(?:^|\n+)Question: / )
234
235     entries.each do |e|
236       p = e.split( "\n" )
237       # We'll need at least two lines of data
238       unless p.size < 2
239         # Check if question isn't empty
240         if p[0].length > 0
241           while p[1].match( /^Answer: (.*)$/ ) == nil and p.size > 2
242             # Delete all lines between the question and the answer
243             p.delete_at(1)
244           end
245           p[1] = p[1].gsub( /Answer: /, "" ).strip
246           # If the answer was found
247           if p[1].length > 0
248             # Add the data to the array
249             b = QuizBundle.new( p[0], p[1] )
250             @questions << b
251           end
252         end
253       end
254     end
255
256     m.reply "done, #{@questions.length} questions loaded."
257   end
258
259
260   # Returns new Quiz instance for channel, or existing one
261   # Announce errors if a message is passed as second parameter
262   #
263   def create_quiz(channel, m=nil)
264     unless @quizzes.has_key?( channel )
265       @quizzes[channel] = Quiz.new( channel, @registry )
266     end
267
268     if @quizzes[channel].has_errors
269       m.reply _("Sorry, the quiz database for %{chan} seems to be corrupt") % {
270         :chan => channel
271       } if m
272       return nil
273     else
274       return @quizzes[channel]
275     end
276   end
277
278
279   def say_score( m, nick )
280     chan = m.channel
281     q = create_quiz( chan, m )
282     return unless q
283
284     if q.registry.has_key?( nick )
285       score = q.registry[nick].score
286       jokers = q.registry[nick].jokers
287
288       rank = 0
289       q.rank_table.each do |place|
290         rank += 1
291         break if nick.downcase == place[0].downcase
292       end
293
294       m.reply "#{nick}'s score is: #{score}    Rank: #{rank}    Jokers: #{jokers}"
295     else
296       m.reply "#{nick} does not have a score yet. Lamer."
297     end
298   end
299
300
301   def help( plugin, topic="" )
302     if topic == "admin"
303       "Quiz game aministration commands (requires authentication): 'quiz autoask <on/off>' => enable/disable autoask mode. 'quiz autoask delay <secs>' => delay next quiz by <secs> seconds when in 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). 'quiz cleanup' => remove players with no points and no jokers."
304     else
305       urls = @bot.config['quiz.sources'].select { |p| p =~ /^https?:\/\// }
306       "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(', ')}")
307     end
308   end
309
310
311   # Updates the per-channel rank table, which is kept for performance reasons.
312   # This table contains all players sorted by rank.
313   #
314   def calculate_ranks( m, q, nick )
315     if q.registry.has_key?( nick )
316       stats = q.registry[nick]
317
318       # Find player in table
319       old_rank = nil
320       q.rank_table.each_with_index do |place, i|
321         if nick.downcase == place[0].downcase
322           old_rank = i
323           break
324         end
325       end
326
327       # Remove player from old position
328       if old_rank
329         q.rank_table.delete_at( old_rank )
330       end
331
332       # Insert player at new position
333       new_rank = nil
334       q.rank_table.each_with_index do |place, i|
335         if stats.score > place[1].score
336           q.rank_table[i,0] = [[nick, stats]]
337           new_rank = i
338           break
339         end
340       end
341
342       # If less than all other players' scores, append to table
343       unless new_rank
344         new_rank = q.rank_table.length
345         q.rank_table << [nick, stats]
346       end
347
348       # Print congratulations/condolences if the player's rank has changed
349       if old_rank
350         if new_rank < old_rank
351           m.reply "#{nick} ascends to rank #{new_rank + 1}. Congratulations :)"
352         elsif new_rank > old_rank
353           m.reply "#{nick} slides down to rank #{new_rank + 1}. So Sorry! NOT. :p"
354         end
355       end
356     else
357       q.rank_table << [[nick, PlayerStats.new( 1 )]]
358     end
359   end
360
361
362   # Reimplemented from Plugin
363   #
364   def message(m)
365     chan = m.channel
366     return unless @quizzes.has_key?( chan )
367     q = @quizzes[chan]
368
369     return if q.question == nil
370
371     message = m.message.downcase.strip
372
373     nick = m.sourcenick.to_s
374
375     # Support multiple alternate answers and cores
376     answer = q.answers.find { |ans| ans.valid?(message) }
377     if answer
378       # List canonical answer which the hint was based on, to avoid confusion
379       # FIXME display this more friendly
380       answer.info = " (hints were for alternate answer #{q.canonical_answer.core})" if answer != q.canonical_answer and q.hinted
381
382       points = 1
383       if q.first_try
384         points += 1
385         reply = "WHOPEEE! #{nick} got it on the first try! That's worth an extra point. Answer was: #{answer}"
386       elsif q.rank_table.length >= 1 and nick.downcase == q.rank_table[0][0].downcase
387         reply = "THE QUIZ CHAMPION defends his throne! Seems like #{nick} is invicible! Answer was: #{answer}"
388       elsif q.rank_table.length >= 2 and nick.downcase == q.rank_table[1][0].downcase
389         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}"
390       elsif    q.rank_table.length >= 3 and nick.downcase == q.rank_table[2][0].downcase
391         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}"
392       else
393         reply = @win_messages[rand( @win_messages.length )].dup
394         reply.gsub!( "<who>", nick )
395         reply.gsub!( "<answer>", answer )
396       end
397
398       m.reply reply
399
400       player = nil
401       if q.registry.has_key?(nick)
402         player = q.registry[nick]
403       else
404         player = PlayerStats.new( 0, 0, 0 )
405       end
406
407       player.score = player.score + points
408
409       # Reward player with a joker every X points
410       if player.score % 15 == 0 and player.jokers < @bot.config['quiz.max_jokers']
411         player.jokers += 1
412         m.reply "#{nick} gains a new joker. Rejoice :)"
413       end
414
415       q.registry[nick] = player
416       calculate_ranks( m, q, nick)
417
418       q.question = nil
419       if q.registry_conf["autoask"]
420         delay = q.registry_conf["autoask_delay"]
421         if delay > 0
422           m.reply "#{Bold}#{Color}03Next question in #{Bold}#{delay}#{Bold} seconds"
423           timer = @bot.timer.add_once(delay) {
424             @ask_mutex.synchronize do
425               @waiting.delete(chan)
426             end
427             cmd_quiz( m, nil)
428           }
429           @waiting[chan] = timer
430         else
431           cmd_quiz( m, nil )
432         end
433       end
434     else
435       # First try is used, and it wasn't the answer.
436       q.first_try = false
437     end
438   end
439
440
441   # Stretches an IRC nick with dots, simply to make the client not trigger a hilight,
442   # which is annoying for those not watching. Example: markey -> m.a.r.k.e.y
443   #
444   def unhilight_nick( nick )
445     return nick unless @bot.config['quiz.dotted_nicks']
446     return nick.split(//).join(".")
447   end
448
449
450   #######################################################################
451   # Command handling
452   #######################################################################
453   def cmd_quiz( m, params )
454     fetch_data( m ) if @questions.empty?
455     chan = m.channel
456
457     @ask_mutex.synchronize do
458       if @waiting.has_key?(chan)
459         m.reply "Next quiz question will be automatically asked soon, have patience"
460         return
461       end
462     end
463
464     q = create_quiz( chan, m )
465     return unless q
466
467     if q.question
468       m.reply "#{Bold}#{Color}03Current question: #{Color}#{Bold}#{q.question}"
469       m.reply "Hint: #{q.hint}" if q.hinted
470       return
471     end
472
473     # Fill per-channel questions buffer
474     if q.questions.empty?
475       q.questions = @questions.sort_by { rand }
476     end
477
478     # pick a question and delete it (delete_at returns the deleted item)
479     picked = q.questions.delete_at( rand(q.questions.length) )
480
481     q.question = picked.question
482     q.answers = picked.answer.split(/\s+\|\|\s+/).map { |ans| QuizAnswer.new(ans) }
483
484     # Check if any core answer is numerical and tell the players so, if that's the case
485     # The rather obscure statement is needed because to_i and to_f returns 99(.0) for "99 red balloons", and 0 for "balloon"
486     #
487     # The "canonical answer" is also determined here, defined to be the first found numerical answer, or
488     # the first core.
489     numeric = q.answers.find { |ans| ans.numeric? }
490     if numeric
491         q.question += "#{Color}07 (Numerical answer)#{Color}"
492         q.canonical_answer = numeric
493     else
494         q.canonical_answer = q.answers.first
495     end
496
497     q.first_try = true
498
499     # FIXME 2.0 UTF-8
500     q.hint = []
501     q.answer_array.clear
502     q.canonical_answer.core.scan(/./u) { |ch|
503       if is_sep(ch)
504         q.hint << ch
505       else
506         q.hint << "^"
507       end
508       q.answer_array << ch
509     }
510     q.all_seps = false
511     # It's possible that an answer is entirely done by separators,
512     # in which case we'll hide everything
513     if q.answer_array == q.hint
514       q.hint.map! { |ch|
515         "^"
516       }
517       q.all_seps = true
518     end
519     q.hinted = false
520
521     # Generate array of unique random range
522     q.hintrange = (0..q.hint.length-1).sort_by{ rand }
523
524     m.reply "#{Bold}#{Color}03Question: #{Color}#{Bold}" + q.question
525   end
526
527
528   def cmd_solve( m, params )
529     chan = m.channel
530
531     return unless @quizzes.has_key?( chan )
532     q = @quizzes[chan]
533
534     m.reply "The correct answer was: #{q.canonical_answer}"
535
536     q.question = nil
537
538     cmd_quiz( m, nil ) if q.registry_conf["autoask"]
539   end
540
541
542   def cmd_hint( m, params )
543     chan = m.channel
544     nick = m.sourcenick.to_s
545
546     return unless @quizzes.has_key?(chan)
547     q = @quizzes[chan]
548
549     if q.question == nil
550       m.reply "#{nick}: Get a question first!"
551     else
552       num_chars = case q.hintrange.length    # Number of characters to reveal
553       when 25..1000 then 7
554       when 20..1000 then 6
555       when 16..1000 then 5
556       when 12..1000 then 4
557       when  8..1000 then 3
558       when  5..1000 then 2
559       when  1..1000 then 1
560       end
561
562       # FIXME 2.0 UTF-8
563       num_chars.times do
564         begin
565           index = q.hintrange.pop
566           # New hint char until the char isn't a "separator" (space etc.)
567         end while is_sep(q.answer_array[index]) and not q.all_seps
568         q.hint[index] = q.answer_array[index]
569       end
570       m.reply "Hint: #{q.hint}"
571       q.hinted = true
572
573       # FIXME 2.0 UTF-8
574       if q.hint == q.answer_array
575         m.reply "#{Bold}#{Color}04BUST!#{Color}#{Bold} This round is over. #{Color}04Minus one point for #{nick}#{Color}."
576
577         stats = nil
578         if q.registry.has_key?( nick )
579           stats = q.registry[nick]
580         else
581           stats = PlayerStats.new( 0, 0, 0 )
582         end
583
584         stats["score"] = stats.score - 1
585         q.registry[nick] = stats
586
587         calculate_ranks( m, q, nick)
588
589         q.question = nil
590         cmd_quiz( m, nil ) if q.registry_conf["autoask"]
591       end
592     end
593   end
594
595
596   def cmd_skip( m, params )
597     chan = m.channel
598     return unless @quizzes.has_key?(chan)
599     q = @quizzes[chan]
600
601     q.question = nil
602     cmd_quiz( m, params )
603   end
604
605
606   def cmd_joker( m, params )
607     chan = m.channel
608     nick = m.sourcenick.to_s
609     q = create_quiz(chan, m)
610     return unless q
611
612     if q.question == nil
613       m.reply "#{nick}: There is no open question."
614       return
615     end
616
617     if q.registry[nick].jokers > 0
618       player = q.registry[nick]
619       player.jokers -= 1
620       player.score += 1
621       q.registry[nick] = player
622
623       calculate_ranks( m, q, nick )
624
625       if player.jokers != 1
626         jokers = "jokers"
627       else
628         jokers = "joker"
629       end
630       m.reply "#{Bold}#{Color}12JOKER!#{Color}#{Bold} #{nick} draws a joker and wins this round. You have #{player.jokers} #{jokers} left."
631       m.reply "The answer was: #{q.canonical_answer}."
632
633       q.question = nil
634       cmd_quiz( m, nil ) if q.registry_conf["autoask"]
635     else
636       m.reply "#{nick}: You don't have any jokers left ;("
637     end
638   end
639
640
641   def cmd_fetch( m, params )
642     fetch_data( m )
643   end
644
645
646   def cmd_refresh( m, params )
647     q = create_quiz(m.channel)
648     q.questions.clear
649     fetch_data(m)
650     cmd_quiz( m, params )
651   end
652
653
654   def cmd_top5( m, params )
655     chan = m.channel
656     q = create_quiz( chan, m )
657     return unless q
658
659     if q.rank_table.empty?
660       m.reply "There are no scores known yet!"
661       return
662     end
663
664     m.reply "* Top 5 Players for #{chan}:"
665
666     [5, q.rank_table.length].min.times do |i|
667       player = q.rank_table[i]
668       nick = player[0]
669       score = player[1].score
670       m.reply "    #{i + 1}. #{unhilight_nick( nick )} (#{score})"
671     end
672   end
673
674
675   def cmd_top_number( m, params )
676     num = params[:number].to_i
677     return if num < 1 or num > 50
678     chan = m.channel
679     q = create_quiz( chan, m )
680     return unless q
681
682     if q.rank_table.empty?
683       m.reply "There are no scores known yet!"
684       return
685     end
686
687     ar = []
688     m.reply "* Top #{num} Players for #{chan}:"
689     n = [ num, q.rank_table.length ].min
690     n.times do |i|
691       player = q.rank_table[i]
692       nick = player[0]
693       score = player[1].score
694       ar << "#{i + 1}. #{unhilight_nick( nick )} (#{score})"
695     end
696     m.reply ar.join(" | "), :split_at => /\s+\|\s+/
697   end
698
699
700   def cmd_stats( m, params )
701     fetch_data( m ) if @questions.empty?
702
703     m.reply "* Total Number of Questions:"
704     m.reply "    #{@questions.length}"
705   end
706
707
708   def cmd_score( m, params )
709     nick = m.sourcenick.to_s
710     say_score( m, nick )
711   end
712
713
714   def cmd_score_player( m, params )
715     say_score( m, params[:player] )
716   end
717
718
719   def cmd_autoask( m, params )
720     chan = m.channel
721     q = create_quiz( chan, m )
722     return unless q
723
724     params[:enable] ||= 'status'
725
726     case params[:enable].downcase
727     when "on", "true"
728       q.registry_conf["autoask"] = true
729       m.reply "Enabled autoask mode."
730       cmd_quiz( m, nil ) if q.question == nil
731     when "off", "false"
732       q.registry_conf["autoask"] = false
733       m.reply "Disabled autoask mode."
734     when "status"
735       m.reply _("Autoask is %{status}, the delay is %{time}") % {
736         :status => q.registry_conf["autoask"],
737         :time => Utils.secs_to_string(q.registry_conf["autoask_delay"]),
738       }
739     else
740       m.reply "Invalid autoask parameter. Use 'on' or 'off' to set it, 'status' to check the current status."
741     end
742   end
743
744   def cmd_autoask_delay( m, params )
745     chan = m.channel
746     q = create_quiz( chan, m )
747     return unless q
748
749     delay = params[:time].to_i
750     q.registry_conf["autoask_delay"] = delay
751     m.reply "Autoask delay now #{q.registry_conf['autoask_delay']} seconds"
752   end
753
754   def cmd_transfer( m, params )
755     chan = m.channel
756     q = create_quiz( chan, m )
757     return unless q
758
759     debug q.rank_table.inspect
760
761     source = params[:source]
762     dest = params[:dest]
763     transscore = params[:score].to_i
764     transjokers = params[:jokers].to_i
765     debug "Transferring #{transscore} points and #{transjokers} jokers from #{source} to #{dest}"
766
767     if q.registry.has_key?(source)
768       sourceplayer = q.registry[source]
769       score = sourceplayer.score
770       if transscore == -1
771         transscore = score
772       end
773       if score < transscore
774         m.reply "#{source} only has #{score} points!"
775         return
776       end
777       jokers = sourceplayer.jokers
778       if transjokers == -1
779         transjokers = jokers
780       end
781       if jokers < transjokers
782         m.reply "#{source} only has #{jokers} jokers!!"
783         return
784       end
785       if q.registry.has_key?(dest)
786         destplayer = q.registry[dest]
787       else
788         destplayer = PlayerStats.new(0,0,0)
789       end
790
791       if sourceplayer.object_id == destplayer.object_id
792         m.reply "Source and destination are the same, I'm not going to touch them"
793         return
794       end
795
796       sourceplayer.score -= transscore
797       destplayer.score += transscore
798       sourceplayer.jokers -= transjokers
799       destplayer.jokers += transjokers
800
801       q.registry[source] = sourceplayer
802       calculate_ranks(m, q, source)
803
804       q.registry[dest] = destplayer
805       calculate_ranks(m, q, dest)
806
807       m.reply "Transferred #{transscore} points and #{transjokers} jokers from #{source} to #{dest}"
808     else
809       m.reply "#{source} doesn't have any points!"
810     end
811   end
812
813
814   def cmd_del_player( m, params )
815     chan = m.channel
816     q = create_quiz( chan, m )
817     return unless q
818
819     debug q.rank_table.inspect
820
821     nick = params[:nick]
822     if q.registry.has_key?(nick)
823       player = q.registry[nick]
824       score = player.score
825       if score != 0
826         m.reply "Can't delete player #{nick} with score #{score}."
827         return
828       end
829       jokers = player.jokers
830       if jokers != 0
831         m.reply "Can't delete player #{nick} with #{jokers} jokers."
832         return
833       end
834       q.registry.delete(nick)
835
836       player_rank = nil
837       q.rank_table.each_index { |rank|
838         if nick.downcase == q.rank_table[rank][0].downcase
839           player_rank = rank
840           break
841         end
842       }
843       q.rank_table.delete_at(player_rank)
844
845       m.reply "Player #{nick} deleted."
846     else
847       m.reply "Player #{nick} isn't even in the database."
848     end
849   end
850
851
852   def cmd_set_score(m, params)
853     chan = m.channel
854     q = create_quiz( chan, m )
855     return unless q
856
857     debug q.rank_table.inspect
858
859     nick = params[:nick]
860     val = params[:score].to_i
861     if q.registry.has_key?(nick)
862       player = q.registry[nick]
863       player.score = val
864     else
865       player = PlayerStats.new( val, 0, 0)
866     end
867     q.registry[nick] = player
868     calculate_ranks(m, q, nick)
869     m.reply "Score for player #{nick} set to #{val}."
870   end
871
872
873   def cmd_set_jokers(m, params)
874     chan = m.channel
875     q = create_quiz( chan, m )
876     return unless q
877
878     debug q.rank_table.inspect
879
880     nick = params[:nick]
881     val = [params[:jokers].to_i, @bot.config['quiz.max_jokers']].min
882     if q.registry.has_key?(nick)
883       player = q.registry[nick]
884       player.jokers = val
885     else
886       player = PlayerStats.new( 0, val, 0)
887     end
888     q.registry[nick] = player
889     m.reply "Jokers for player #{nick} set to #{val}."
890   end
891
892
893   def cmd_cleanup(m, params)
894     chan = m.channel
895     q = create_quiz( chan, m )
896     return unless q
897
898     null_players = []
899     q.registry.each { |nick, player|
900       null_players << nick if player.jokers == 0 and player.score == 0
901     }
902     debug "Cleaning up by removing #{null_players * ', '}"
903     null_players.each { |nick|
904       cmd_del_player(m, :nick => nick)
905     }
906
907   end
908
909   def stop(m, params)
910     unless m.public?
911       m.reply 'you must be on some channel to use this command'
912       return
913     end
914     if @quizzes.delete m.channel
915       @ask_mutex.synchronize do
916         t = @waiting.delete(m.channel)
917         @bot.timer.remove t if t
918       end
919       m.okay
920     else
921       m.reply(_("there is no active quiz on #{m.channel}"))
922     end
923   end
924
925 end
926
927 plugin = QuizPlugin.new
928 plugin.default_auth( 'edit', false )
929
930 # Normal commands
931 plugin.map 'quiz',                  :action => 'cmd_quiz'
932 plugin.map 'quiz solve',            :action => 'cmd_solve'
933 plugin.map 'quiz hint',             :action => 'cmd_hint'
934 plugin.map 'quiz skip',             :action => 'cmd_skip'
935 plugin.map 'quiz joker',            :action => 'cmd_joker'
936 plugin.map 'quiz score',            :action => 'cmd_score'
937 plugin.map 'quiz score :player',    :action => 'cmd_score_player'
938 plugin.map 'quiz fetch',            :action => 'cmd_fetch'
939 plugin.map 'quiz refresh',          :action => 'cmd_refresh'
940 plugin.map 'quiz top5',             :action => 'cmd_top5'
941 plugin.map 'quiz top :number',      :action => 'cmd_top_number'
942 plugin.map 'quiz stats',            :action => 'cmd_stats'
943 plugin.map 'quiz stop', :action => :stop
944
945 # Admin commands
946 plugin.map 'quiz autoask [:enable]',  :action => 'cmd_autoask', :auth_path => 'edit'
947 plugin.map 'quiz autoask delay :time',  :action => 'cmd_autoask_delay', :auth_path => 'edit', :requirements => {:time => /\d+/}
948 plugin.map 'quiz transfer :source :dest :score :jokers', :action => 'cmd_transfer', :auth_path => 'edit', :defaults => {:score => '-1', :jokers => '-1'}
949 plugin.map 'quiz deleteplayer :nick', :action => 'cmd_del_player', :auth_path => 'edit'
950 plugin.map 'quiz setscore :nick :score', :action => 'cmd_set_score', :auth_path => 'edit'
951 plugin.map 'quiz setjokers :nick :jokers', :action => 'cmd_set_jokers', :auth_path => 'edit'
952 plugin.map 'quiz cleanup', :action => 'cmd_cleanup', :auth_path => 'edit'