]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/games/uno.rb
uno plugin: only allow to pick a color after a wild
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / games / uno.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Uno Game Plugin for rbot
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 #
8 # Copyright:: (C) 2008 Giuseppe Bilotta
9 #
10 # License:: GPL v2
11 #
12 # Uno Game: get rid of the cards you have
13 #
14 # TODO documentation
15 # TODO allow full form card names for play
16 # TODO allow choice of rules re stacking + and playing Reverse with them
17
18 class UnoGame
19   COLORS = %w{Red Green Blue Yellow}
20   SPECIALS = %w{+2 Reverse Skip}
21   NUMERICS = (0..9).to_a
22   VALUES = NUMERICS + SPECIALS
23
24   def UnoGame.color_map(clr)
25     case clr
26     when 'Red'
27       :red
28     when 'Blue'
29       :royal_blue
30     when 'Green'
31       :limegreen
32     when 'Yellow'
33       :yellow
34     end
35   end
36
37   def UnoGame.irc_color_bg(clr)
38     Irc.color([:white,:black][COLORS.index(clr)%2],UnoGame.color_map(clr))
39   end
40
41   def UnoGame.irc_color_fg(clr)
42     Irc.color(UnoGame.color_map(clr))
43   end
44
45   def UnoGame.colorify(str, fg=false)
46     ret = Bold.dup
47     str.length.times do |i|
48       ret << (fg ?
49               UnoGame.irc_color_fg(COLORS[i%4]) :
50               UnoGame.irc_color_bg(COLORS[i%4]) ) +str[i,1]
51     end
52     ret << NormalText
53   end
54
55   UNO = UnoGame.colorify('UNO!', true)
56
57   # Colored play cards
58   class Card
59     attr_reader :color
60     attr_reader :value
61     attr_reader :shortform
62     attr_reader :to_s
63     attr_reader :score
64
65     def initialize(color, value)
66       raise unless COLORS.include? color
67       @color = color.dup
68       raise unless VALUES.include? value
69       if NUMERICS.include? value
70         @value = value
71         @score = value
72       else
73         @value = value.dup
74         @score = 20
75       end
76       if @value == '+2'
77         @shortform = (@color[0,1]+@value).downcase
78       else
79         @shortform = (@color[0,1]+@value.to_s[0,1]).downcase
80       end
81       @to_s = UnoGame.irc_color_bg(@color) +
82         Bold + ['', @color, @value, ''].join(' ') + NormalText
83     end
84
85     def picker
86       return 0 unless @value.to_s[0,1] == '+'
87       return @value[1,1].to_i
88     end
89
90     def special?
91       SPECIALS.include?(@value)
92     end
93
94     def <=>(other)
95       cc = self.color <=> other.color
96       if cc == 0
97         return self.value.to_s <=> other.value.to_s
98       else
99         return cc
100       end
101     end
102     include Comparable
103   end
104
105   # Wild, Wild +4 cards
106   class Wild < Card
107     def initialize(value=nil)
108       @color = 'Wild'
109       raise if value and not value == '+4'
110       if value
111         @value = value.dup 
112         @shortform = 'w'+value
113       else
114         @value = nil
115         @shortform = 'w'
116       end
117       @score = 50
118       @to_s = UnoGame.colorify(['', @color, @value, ''].compact.join(' '))
119     end
120     def special?
121       @value
122     end
123   end
124
125   class Player
126     attr_accessor :cards
127     attr_accessor :user
128     def initialize(user)
129       @user = user
130       @cards = []
131     end
132     def has_card?(short)
133       has = []
134       @cards.each { |c|
135         has << c if c.shortform == short
136       }
137       if has.empty?
138         return false
139       else
140         return has
141       end
142     end
143     def to_s
144       Bold + @user.to_s + Bold
145     end
146   end
147
148   # cards in stock
149   attr_reader :stock
150   # current discard
151   attr_reader :discard
152   # previous discard, in case of challenge
153   attr_reader :last_discard
154   # channel the game is played in
155   attr_reader :channel
156   # list of players
157   attr :players
158   # true if the player picked a card (and can thus pass turn)
159   attr_reader :player_has_picked
160   # number of cards to be picked if the player can't play an appropriate card
161   attr_reader :picker
162
163   # the IRC user that created the game
164   attr_accessor :manager
165
166   def initialize(plugin, channel, manager)
167     @channel = channel
168     @plugin = plugin
169     @bot = plugin.bot
170     @players = []
171     @dropouts = []
172     @discard = nil
173     @last_discard = nil
174     @value = nil
175     @color = nil
176     make_base_stock
177     @stock = []
178     make_stock
179     @start_time = nil
180     @join_timer = nil
181     @picker = 0
182     @last_picker = 0
183     @must_play = nil
184     @manager = manager
185   end
186
187   def get_player(user)
188     case user
189     when User
190       @players.each do |p|
191         return p if p.user == user
192       end
193     when String
194       @players.each do |p|
195         return p if p.user.irc_downcase == user.irc_downcase(channel.casemap)
196       end
197     else
198       get_player(user.to_s)
199     end
200     return nil
201   end
202
203   def announce(msg, opts={})
204     @bot.say channel, msg, opts
205   end
206
207   def notify(player, msg, opts={})
208     @bot.notice player.user, msg, opts
209   end
210
211   def make_base_stock
212     @base_stock = COLORS.inject([]) do |list, clr|
213       VALUES.each do |n|
214         list << Card.new(clr, n)
215         list << Card.new(clr, n) unless n == 0
216       end
217       list
218     end
219     4.times do
220       @base_stock << Wild.new
221       @base_stock << Wild.new('+4')
222     end
223   end
224
225   def make_stock
226     @stock.replace @base_stock
227     # remove the cards in the players hand
228     @players.each { |p| p.cards.each { |c| @stock.delete_one c } }
229     # remove current top discarded card if present
230     if @discard
231       @stock.delete_one(discard)
232     end
233     @stock.shuffle!
234   end
235
236   def start_game
237     debug "Starting game"
238     @players.shuffle!
239     show_order
240     announce _("%{p} deals the first card from the stock") % {
241       :p => @players.first
242     }
243     card = @stock.shift
244     @picker = 0
245     @special = false
246     while Wild === card do
247       @stock.insert(rand(@stock.length), card)
248       card = @stock.shift
249     end
250     set_discard(card)
251     show_discard
252     if @special
253       do_special
254     end
255     next_turn
256     @start_time = Time.now
257   end
258
259   def elapsed_time
260     if @start_time
261       Utils.secs_to_string(Time.now-@start_time)
262     else
263       _("no time")
264     end
265   end
266
267   def reverse_turn
268     # if there are two players, the Reverse acts like a Skip, unless
269     # there's a @picker running, in which case the Reverse should bounce the
270     # pick on the other player
271     if @players.length > 2
272       @players.reverse!
273       # put the current player back in its place
274       @players.unshift @players.pop
275       announce _("Playing order was reversed!")
276     elsif @picker > 0
277       announce _("%{cp} bounces the pick to %{np}") % {
278         :cp => @players.first,
279         :np => @players.last
280       }
281     else
282       skip_turn
283     end
284   end
285
286   def skip_turn
287     @players << @players.shift
288     announce _("%{p} skips a turn!") % {
289       # this is first and not last because the actual
290       # turn change will be done by the following next_turn
291       :p => @players.first
292     }
293   end
294
295   def do_special
296     case @discard.value
297     when 'Reverse'
298       reverse_turn
299       @special = false
300     when 'Skip'
301       skip_turn
302       @special = false
303     end
304   end
305
306   def set_discard(card)
307     @discard = card
308     @value = card.value.dup rescue card.value
309     if Wild === card
310       @color = nil
311     else
312       @color = card.color.dup
313     end
314     if card.picker > 0
315       @picker += card.picker
316       @last_picker = @discard.picker
317     end
318     if card.special?
319       @special = true
320     else
321       @special = false
322     end
323     @must_play = nil
324   end
325
326   def next_turn(opts={})
327     @players << @players.shift
328     @player_has_picked = false
329     show_turn
330   end
331
332   def can_play(card)
333     # if play is forced, check against the only allowed cards
334     return false if @must_play and not @must_play.include?(card)
335
336     # When a +something is online, you can only play a +something of same or
337     # higher something, or a Reverse of the correct color, or a Reverse on
338     # a Reverse
339     # TODO make optional
340     if @picker > 0
341       return true if card.picker >= @last_picker
342       return true if card.value == 'Reverse' and (card.color == @color or @discard.value == card.value)
343       return false
344     else
345       # You can always play a Wild
346       return true if Wild === card
347       # On a Wild, you must match the color
348       if Wild === @discard
349         return card.color == @color
350       else
351         # Otherwise, you can match either the value or the color
352         return (card.value == @value) || (card.color == @color)
353       end
354     end
355   end
356
357   def play_card(source, cards)
358     debug "Playing card #{cards}"
359     p = get_player(source)
360     shorts = cards.gsub(/\s+/,'').match(/^(?:([rbgy]\+?\d){1,2}|([rbgy][rs])|(w(?:\+4)?)([rbgy])?)$/).to_a
361     debug shorts.inspect
362     if shorts.empty?
363       announce _("what cards were that again?")
364       return
365     end
366     full = shorts[0]
367     short = shorts[1] || shorts[2] || shorts[3]
368     jolly = shorts[3]
369     jcolor = shorts[4]
370     if jolly
371       toplay = 1
372     else
373       toplay = (full == short) ? 1 : 2
374     end
375     debug [full, short, jolly, jcolor, toplay].inspect
376     # r7r7 -> r7r7, r7, nil, nil
377     # r7 -> r7, r7, nil, nil
378     # w -> w, nil, w, nil
379     # wg -> wg, nil, w, g
380     if cards = p.has_card?(short)
381       debug cards
382       unless can_play(cards.first)
383         announce _("you can't play that card")
384         return
385       end
386       if cards.length >= toplay
387         # if the played card is a W+4 not played during a stacking +x
388         # TODO if A plays an illegal W+4, B plays a W+4, should the next
389         # player be able to challenge A? For the time being we say no,
390         # but I think he should, and in case A's move was illegal
391         # game would have to go back, A would get the penalty and replay,
392         # while if it was legal the challenger would get 50% more cards,
393         # i.e. 12 cards (or more if the stacked +4 were more). This would
394         # only be possible if the first W+4 was illegal, so it wouldn't
395         # apply for a W+4 played on a +2 anyway.
396         #
397         if @picker == 0 and Wild === cards.first and cards.first.value 
398           # save the previous discard in case of challenge
399           @last_discard = @discard.dup
400           # save the color too, in case it was a Wild
401           @last_color = @color.dup
402         else
403           # mark the move as not challengeable
404           @last_discard = nil
405           @last_color = nil
406         end
407         set_discard(p.cards.delete_one(cards.shift))
408         if toplay > 1
409           set_discard(p.cards.delete_one(cards.shift))
410           announce _("%{p} plays %{card} twice!") % {
411             :p => p,
412             :card => @discard
413           }
414         else
415           announce _("%{p} plays %{card}") % { :p => p, :card => @discard }
416         end
417         if p.cards.length == 1
418           announce _("%{p} has %{uno}!") % {
419             :p => p, :uno => UNO
420           }
421         elsif p.cards.length == 0
422           end_game
423           return
424         end
425         show_picker
426         if @color
427           if @special
428             do_special
429           end
430           next_turn
431         elsif jcolor
432           choose_color(p.user, jcolor)
433         else
434           announce _("%{p}, choose a color with: co r|b|g|y") % { :p => p }
435         end
436       else
437         announce _("you don't have two cards of that kind")
438       end
439     else
440       announce _("you don't have that card")
441     end
442   end
443
444   def challenge
445     return unless @last_discard
446     # current player
447     cp = @players.first
448     # previous player
449     lp = @players.last
450     announce _("%{cp} challenges %{lp}'s %{card}!") % {
451       :cp => cp, :lp => lp, :card => @discard
452     }
453     # show the cards of the previous player to the current player
454     notify cp, _("%{p} has %{cards}") % {
455       :p => lp, :cards => lp.cards.join(' ')
456     }
457     # check if the previous player had a non-special card of the correct color
458     legal = true
459     lp.cards.each do |c|
460       if c.color == @last_color and not c.special?
461         legal = false
462       end
463     end
464     if legal
465       @picker += 2
466       announce _("%{lp}'s move was legal, %{cp} must pick %{b}%{n}%{b} cards!") % {
467         :cp => cp, :lp => lp, :b => Bold, :n => @picker
468       }
469       @last_color = nil
470       @last_discard = nil
471       deal(cp, @picker)
472       @picker = 0
473       next_turn
474     else
475       announce _("%{lp}'s move was %{b}not%{b} legal, %{lp} must pick %{b}%{n}%{b} cards and play again!") % {
476         :cp => cp, :lp => lp, :b => Bold, :n => @picker
477       }
478       lp.cards << @discard # put the W+4 back in place
479
480       # reset the discard
481       @color = @last_color.dup
482       @discard = @last_discard.dup
483       @special = false
484       @value = @discard.value.dup rescue @discard.value
485       @last_color = nil
486       @last_discard = nil
487
488       # force the player to play the current cards
489       @must_play = lp.cards.dup
490
491       # give him the penalty cards
492       deal(lp, @picker)
493       @picker = 0
494
495       # and restore the turn
496       @players.unshift @players.pop
497     end
498   end
499
500   def pass(user)
501     p = get_player(user)
502     if @picker > 0
503       announce _("%{p} passes turn, and has to pick %{b}%{n}%{b} cards!") % {
504         :p => p, :b => Bold, :n => @picker
505       }
506       deal(p, @picker)
507       @picker = 0
508     else
509       if @player_has_picked
510         announce _("%{p} passes turn") % { :p => p }
511       else
512         announce _("you need to pick a card first")
513         return
514       end
515     end
516     next_turn
517   end
518
519   def choose_color(user, color)
520     # you can only pick a color if the current color is unset
521     if @color
522       announce _("you can't pick a color now, %{p}") % {
523         :p => get_player(user)
524       }
525       return
526     end
527     case color
528     when 'r'
529       @color = 'Red'
530     when 'b'
531       @color = 'Blue'
532     when 'g'
533       @color = 'Green'
534     when 'y'
535       @color = 'Yellow'
536     else
537       announce _('what color is that?')
538       return
539     end
540     announce _('color is now %{c}') % {
541       :c => UnoGame.irc_color_bg(@color)+" #{@color} "
542     }
543     next_turn
544   end
545
546   def show_time
547     if @start_time
548       announce _("This %{uno} game has been going on for %{time}") % {
549         :uno => UNO,
550         :time => elapsed_time
551       }
552     else
553       announce _("The game hasn't started yet")
554     end
555   end
556
557   def show_order
558     announce _("%{uno} playing turn: %{players}") % {
559       :uno => UNO, :players => players.join(' ')
560     }
561   end
562
563   def show_turn(opts={})
564     cards = true
565     cards = opts[:cards] if opts.key?(:cards)
566     player = @players.first
567     announce _("it's %{player}'s turn") % { :player => player }
568     show_user_cards(player) if cards
569   end
570
571   def has_turn?(source)
572     @players.first.user == source
573   end
574
575   def show_picker
576     if @picker > 0
577       announce _("next player must respond correctly or pick %{b}%{n}%{b} cards") % {
578         :b => Bold, :n => @picker
579       }
580     end
581   end
582
583   def show_discard
584     announce _("Current discard: %{card} %{c}") % { :card => @discard,
585       :c => (Wild === @discard) ? UnoGame.irc_color_bg(@color) + " #{@color} " : nil
586     }
587     show_picker
588   end
589
590   def show_user_cards(player)
591     p = Player === player ? player : get_player(player)
592     notify p, _('Your cards: %{cards}') % {
593       :cards => p.cards.join(' ')
594     }
595   end
596
597   def show_all_cards(u=nil)
598     announce(@players.inject([]) { |list, p|
599       list << [p, p.cards.length].join(': ')
600     }.join(', '))
601     if u
602       show_user_cards(u)
603     end
604   end
605
606   def pick_card(user)
607     p = get_player(user)
608     announce _("%{player} picks a card") % { :player => p }
609     deal(p, 1)
610     @player_has_picked = true
611   end
612
613   def deal(player, num=1)
614     picked = []
615     num.times do
616       picked << @stock.delete_one
617       if @stock.length == 0
618         announce _("Shuffling discarded cards")
619         make_stock
620         if @stock.length == 0
621           announce _("No more cards!")
622           end_game # FIXME nope!
623         end
624       end
625     end
626     picked.sort!
627     notify player, _("You picked %{picked}") % { :picked => picked.join(' ') }
628     player.cards += picked
629     player.cards.sort!
630   end
631
632   def add_player(user)
633     if p = get_player(user)
634       announce _("you're already in the game, %{p}") % {
635         :p => p
636       }
637       return
638     end
639     @dropouts.each do |dp|
640       if dp.user == user
641         announce _("you dropped from the game, %{p}, you can't get back in") % {
642           :p => dp
643         }
644         return
645       end
646     end
647     cards = 7
648     if @start_time
649       cards = @players.inject(0) do |s, pl|
650         s +=pl.cards.length
651       end/@players.length
652     end
653     p = Player.new(user)
654     @players << p
655     announce _("%{p} joins this game of %{uno}") % {
656       :p => p, :uno => UNO
657     }
658     deal(p, cards)
659     return if @start_time
660     if @join_timer
661       @bot.timer.reschedule(@join_timer, 10)
662     elsif @players.length > 1
663       announce _("game will start in 20 seconds")
664       @join_timer = @bot.timer.add_once(20) {
665         start_game
666       }
667     end
668   end
669
670   def drop_player(nick)
671     # A nick is passed because the original player might have left
672     # the channel or IRC
673     unless p = get_player(nick)
674       announce _("%{p} isn't playing %{uno}") % {
675         :p => p, :uno => UNO
676       }
677       return
678     end
679     announce _("%{p} gives up this game of %{uno}") % {
680       :p => p, :uno => UNO
681     }
682     case @players.length
683     when 2
684       if p == @players.first
685         next_turn
686       end
687       end_game
688       return
689     when 1
690       end_game(true)
691       return
692     end
693     debug @stock.length
694     while p.cards.length > 0
695       @stock.insert(rand(@stock.length), p.cards.shift)
696     end
697     debug @stock.length
698     @dropouts << @players.delete_one(p)
699   end
700
701   def replace_player(old, new)
702     # The new user
703     user = channel.get_user(new)
704     if p = get_player(user)
705       announce _("%{p} is already playing %{uno} here") % {
706         :p => p, :uno => UNO
707       }
708       return
709     end
710     # We scan the player list of the player with the old nick, instead
711     # of using get_player, in case of IRC drops etc
712     @players.each do |p|
713       if p.user.nick == old
714         p.user = user
715         announce _("%{p} takes %{b}%{old}%{b}'s place at %{uno}") % {
716           :p => p, :b => Bold, :old => old, :uno => UNO
717         }
718         return
719       end
720     end
721     announce _("%{b}%{old}%{b} isn't playing %{uno} here") % {
722       :uno => UNO, :b => Bold, :old => old
723     }
724   end
725
726   def end_game(halted = false)
727     runtime = @start_time ? Time.now -  @start_time : 0
728     if halted
729       if @start_time
730         announce _("%{uno} game halted after %{time}") % {
731           :time => elapsed_time,
732           :uno => UNO
733         }
734       else
735         announce _("%{uno} game halted before it could start") % {
736           :uno => UNO
737         }
738       end
739     else
740       announce _("%{uno} game finished after %{time}! The winner is %{p}") % {
741         :time => elapsed_time,
742         :uno => UNO, :p => @players.first
743       }
744     end
745     if @picker > 0 and not halted
746       p = @players[1]
747       announce _("%{p} has to pick %{b}%{n}%{b} cards!") % {
748         :p => p, :n => @picker, :b => Bold
749       }
750       deal(p, @picker)
751       @picker = 0
752     end
753     score = @players.inject(0) do |sum, p|
754       if p.cards.length > 0
755         announce _("%{p} still had %{cards}") % {
756           :p => p, :cards => p.cards.join(' ')
757         }
758         sum += p.cards.inject(0) do |cs, c|
759           cs += c.score
760         end
761       end
762       sum
763     end
764
765     closure = { :dropouts => @dropouts, :players => @players, :runtime => runtime }
766     if not halted
767       announce _("%{p} wins with %{b}%{score}%{b} points!") % {
768         :p => @players.first, :score => score, :b => Bold
769       }
770       closure.merge!(:winner => @players.first, :score => score,
771         :opponents => @players.length - 1)
772     end
773
774     @plugin.do_end_game(@channel, closure)
775   end
776
777 end
778
779 # A won game: store score and number of opponents, so we can calculate
780 # an average score per opponent (requested by Squiddhartha)
781 define_structure :UnoGameWon, :score, :opponents
782 # For each player we store the number of games played, the number of
783 # games forfeited, and an UnoGameWon for each won game
784 define_structure :UnoPlayerStats, :played, :forfeits, :won
785
786 class UnoPlugin < Plugin
787   attr :games
788   def initialize
789     super
790     @games = {}
791   end
792
793   def help(plugin, topic="")
794     case topic
795     when 'commands'
796       [
797       _("'jo' to join in"),
798       _("'pl <card>' to play <card>: e.g. 'pl g7' to play Green 7, or 'pl rr' to play Red Reverse, or 'pl y2y2' to play both Yellow 2 cards"),
799       _("'pe' to pick a card"),
800       _("'pa' to pass your turn"),
801       _("'co <color>' to pick a color after playing a Wild: e.g. 'co g' to select Green (or 'pl w+4 g' to select the color when playing the Wild)"),
802       _("'ca' to show current cards"),
803       _("'cd' to show the current discard"),
804       _("'ch' to challenge a Wild +4"),
805       _("'od' to show the playing order"),
806       _("'ti' to show play time"),
807       _("'tu' to show whose turn it is")
808     ].join("; ")
809     when 'challenge'
810       _("A Wild +4 can only be played legally if you don't have normal (not special) cards of the current color. ") +
811       _("The next player can challenge a W+4 by using the 'ch' command. ") +
812       _("If the W+4 play was illegal, the player who played it must pick the W+4, pick 4 cards from the stock, and play a legal card. ") +
813       _("If the W+4 play was legal, the challenger must pick 6 cards instead of 4.")
814     when 'rules'
815       _("play all your cards, one at a time, by matching either the color or the value of the currently discarded card. ") +
816       _("cards with special effects: Skip (next player skips a turn), Reverse (reverses the playing order), +2 (next player has to take 2 cards). ") +
817       _("Wilds can be played on any card, and you must specify the color for the next card. ") +
818       _("Wild +4 also forces the next player to take 4 cards, but it can only be played if you can't play a color card. ") +
819       _("you can play another +2 or +4 card on a +2 card, and a +4 on a +4, forcing the first player who can't play one to pick the cumulative sum of all cards. ") +
820       _("you can also play a Reverse on a +2 or +4, bouncing the effect back to the previous player (that now comes next). ")
821     when /scor(?:e|ing)/, /points?/
822       [
823       _("The points won with a game of %{uno} are totalled from the cards remaining in the hands of the other players."),
824       _("Each normal (not special) card is worth its face value (from 0 to 9 points)."),
825       _("Each colored special card (+2, Reverse, Skip) is worth 20 points."),
826       _("Each Wild and Wild +4 is worth 50 points.")
827       ].join(" ") % { :uno => UnoGame::UNO }
828     when /cards?/
829       [
830       _("There are 108 cards in a standard %{uno} deck."),
831       _("For each color (Blue, Green, Red, Yellow) there are 19 numbered cards (from 0 to 9), with two of each number except for 0."),
832       _("There are also 6 special cards for each color, two each of +2, Reverse, Skip."),
833       _("Finally, there are 4 Wild and 4 Wild +4 cards.")
834       ].join(" ") % { :uno => UnoGame::UNO }
835     when 'admin'
836       _("The game manager (the user that started the game) can execute the following commands to manage it: ") +
837       [
838       _("'uno drop <user>' to drop a user from the game (any user can drop itself using 'uno drop')"),
839       _("'uno replace <old> [with] <new>' to replace a player with someone else (useful in case of disconnects)"),
840       _("'uno transfer [to] <nick>' to transfer game ownership to someone else"),
841       _("'uno end' to end the game before its natural completion")
842       ].join("; ")
843     else
844       _("%{uno} game. !uno to start a game. see 'help uno rules' for the rules, 'help uno admin' for admin commands. In-game commands: %{cmds}.") % {
845         :uno => UnoGame::UNO,
846         :cmds => help(plugin, 'commands')
847       }
848     end
849   end
850
851   def message(m)
852     return unless @games.key?(m.channel)
853     g = @games[m.channel]
854     case m.plugin.intern
855     when :jo # join game
856       return if m.params
857       g.add_player(m.source)
858     when :pe # pick card
859       return if m.params
860       if g.has_turn?(m.source)
861         if g.player_has_picked
862           m.reply _("you already picked a card")
863         elsif g.picker > 0
864           g.pass(m.source)
865         else
866           g.pick_card(m.source)
867         end
868       else
869         m.reply _("It's not your turn")
870       end
871     when :pa # pass turn
872       return if m.params
873       if g.has_turn?(m.source)
874         g.pass(m.source)
875       else
876         m.reply _("It's not your turn")
877       end
878     when :pl # play card
879       if g.has_turn?(m.source)
880         g.play_card(m.source, m.params.downcase)
881       else
882         m.reply _("It's not your turn")
883       end
884     when :co # pick color
885       if g.has_turn?(m.source)
886         g.choose_color(m.source, m.params.downcase)
887       else
888         m.reply _("It's not your turn")
889       end
890     when :ca # show current cards
891       return if m.params
892       g.show_all_cards(m.source)
893     when :cd # show current discard
894       return if m.params
895       g.show_discard
896     when :ch
897       if g.has_turn?(m.source)
898         if g.last_discard
899           g.challenge
900         else
901           m.reply _("previous move cannot be challenged")
902         end
903       else
904         m.reply _("It's not your turn")
905       end
906     when :od # show playing order
907       return if m.params
908       g.show_order
909     when :ti # show play time
910       return if m.params
911       g.show_time
912     when :tu # show whose turn is it
913       return if m.params
914       if g.has_turn?(m.source)
915         m.nickreply _("it's your turn, sleepyhead")
916       else
917         g.show_turn(:cards => false)
918       end
919     end
920   end
921
922   def create_game(m, p)
923     if @games.key?(m.channel)
924       m.reply _("There is already an %{uno} game running here, managed by %{who}. say 'jo' to join in") % {
925         :who => @games[m.channel].manager,
926         :uno => UnoGame::UNO
927       }
928       return
929     end
930     @games[m.channel] = UnoGame.new(self, m.channel, m.source)
931     @bot.auth.irc_to_botuser(m.source).set_temp_permission('uno::manage', true, m.channel)
932     m.reply _("Ok, created %{uno} game on %{channel}, say 'jo' to join in") % {
933       :uno => UnoGame::UNO,
934       :channel => m.channel
935     }
936   end
937
938   def transfer_ownership(m, p)
939     unless @games.key?(m.channel)
940       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
941       return
942     end
943     g = @games[m.channel]
944     old = g.manager
945     new = m.channel.get_user(p[:nick])
946     if new
947       g.manager = new
948       @bot.auth.irc_to_botuser(old).reset_temp_permission('uno::manage', m.channel)
949       @bot.auth.irc_to_botuser(new).set_temp_permission('uno::manage', true, m.channel)
950       m.reply _("%{uno} game ownership transferred from %{old} to %{nick}") % {
951         :uno => UnoGame::UNO, :old => old, :nick => p[:nick]
952       }
953     else
954       m.reply _("who is this %{nick} you want me to transfer game ownership to?") % p
955     end
956   end
957
958   def end_game(m, p)
959     unless @games.key?(m.channel)
960       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
961       return
962     end
963     @games[m.channel].end_game(true)
964   end
965
966   def cleanup
967     @games.each { |k, g| g.end_game(true) }
968     super
969   end
970
971   def chan_reg(channel)
972     @registry.sub_registry(channel.downcase)
973   end
974
975   def chan_stats(channel)
976     stats = chan_reg(channel).sub_registry('stats')
977     class << stats
978       def store(val)
979         val.to_i
980       end
981       def restore(val)
982         val.to_i
983       end
984     end
985     stats.set_default(0)
986     return stats
987   end
988
989   def chan_pstats(channel)
990     pstats = chan_reg(channel).sub_registry('players')
991     pstats.set_default(UnoPlayerStats.new(0,0,[]))
992     return pstats
993   end
994
995   def do_end_game(channel, closure)
996     reg = chan_reg(channel)
997     stats = chan_stats(channel)
998     stats['played'] += 1
999     stats['played_runtime'] += closure[:runtime]
1000     if closure[:winner]
1001       stats['finished'] += 1
1002       stats['finished_runtime'] += closure[:runtime]
1003
1004       pstats = chan_pstats(channel)
1005
1006       closure[:players].each do |pl|
1007         k = pl.user.downcase
1008         pls = pstats[k]
1009         pls.played += 1
1010         pstats[k] = pls
1011       end
1012
1013       closure[:dropouts].each do |pl|
1014         k = pl.user.downcase
1015         pls = pstats[k]
1016         pls.played += 1
1017         pls.forfeits += 1
1018         pstats[k] = pls
1019       end
1020
1021       winner = closure[:winner]
1022       won = UnoGameWon.new(closure[:score], closure[:opponents])
1023       k = winner.user.downcase
1024       pls = pstats[k] # already marked played +1 above
1025       pls.won << won
1026       pstats[k] = pls
1027     end
1028
1029     @bot.auth.irc_to_botuser(@games[channel].manager).reset_temp_permission('uno::manage', channel)
1030     @games.delete(channel)
1031   end
1032
1033   def do_chanstats(m, p)
1034     stats = chan_stats(m.channel)
1035     np = stats['played']
1036     nf = stats['finished']
1037     if np > 0
1038       str = _("%{nf} %{uno} games completed over %{np} games played. ") % {
1039         :np => np, :uno => UnoGame::UNO, :nf => nf
1040       }
1041       cgt = stats['finished_runtime']
1042       tgt = stats['played_runtime']
1043       str << _("%{cgt} game time for completed games") % {
1044         :cgt => Utils.secs_to_string(cgt)
1045       }
1046       if np > nf
1047         str << _(" on %{tgt} total game time. ") % {
1048           :tgt => Utils.secs_to_string(tgt)
1049         }
1050       else
1051         str << ". "
1052       end
1053       str << _("%{avg} average game time for completed games") % {
1054         :avg => Utils.secs_to_string(cgt/nf)
1055       }
1056       str << _(", %{tavg} for all games") % {
1057         :tavg => Utils.secs_to_string(tgt/np)
1058       } if np > nf
1059       m.reply str
1060     else
1061       m.reply _("nobody has played %{uno} on %{chan} yet") % {
1062         :uno => UnoGame::UNO, :chan => m.channel
1063       }
1064     end
1065   end
1066
1067   def do_pstats(m, p)
1068     dnick = p[:nick] || m.source # display-nick, don't later case
1069     nick = dnick.downcase
1070     ps = chan_pstats(m.channel)[nick]
1071     if ps.played == 0
1072       m.reply _("%{nick} never played %{uno} here") % {
1073         :uno => UnoGame::UNO, :nick => dnick
1074       }
1075       return
1076     end
1077     np = ps.played
1078     nf = ps.forfeits
1079     nw = ps.won.length
1080     score = ps.won.inject(0) { |sum, w| sum += w.score }
1081     str = _("%{nick} played %{np} %{uno} games here, ") % {
1082       :nick => dnick, :np => np, :uno => UnoGame::UNO
1083     }
1084     str << _("forfeited %{nf} games, ") % { :nf => nf } if nf > 0
1085     str << _("won %{nw} games") % { :nw => nw}
1086     if nw > 0
1087       str << _(" with %{score} total points") % { :score => score }
1088       avg = ps.won.inject(0) { |sum, w| sum += w.score/w.opponents }/nw
1089       str << _(" and an average of %{avg} points per opponent") % { :avg => avg }
1090     end
1091     m.reply str
1092   end
1093
1094   def replace_player(m, p)
1095     unless @games.key?(m.channel)
1096       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1097       return
1098     end
1099     @games[m.channel].replace_player(p[:old], p[:new])
1100   end
1101
1102   def drop_player(m, p)
1103     unless @games.key?(m.channel)
1104       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1105       return
1106     end
1107     @games[m.channel].drop_player(p[:nick] || m.source.nick)
1108   end
1109
1110   def print_stock(m, p)
1111     unless @games.key?(m.channel)
1112       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1113       return
1114     end
1115     stock = @games[m.channel].stock
1116     m.reply(_("%{num} cards in stock: %{stock}") % {
1117       :num => stock.length,
1118       :stock => stock.join(' ')
1119     }, :split_at => /#{NormalText}\s*/)
1120   end
1121
1122   def do_top(m, p)
1123     pstats = chan_pstats(m.channel)
1124     scores = []
1125     wins = []
1126     pstats.each do |k, v|
1127       wins << [v.won.length, k]
1128       scores << [v.won.inject(0) { |s, w| s+=w.score }, k]
1129     end
1130
1131     if n = p[:scorenum]
1132       msg = _("%{uno} %{num} highest scores: ") % {
1133         :uno => UnoGame::UNO, :num => p[:scorenum]
1134       }
1135       scores.sort! { |a1, a2| -(a1.first <=> a2.first) }
1136       scores = scores[0, n.to_i].compact
1137       i = 0
1138       if scores.length <= 5
1139         list = "\n" + scores.map { |a|
1140           i+=1
1141           _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} points") % {
1142             :i => i, :b => Bold, :nick => a.last, :score => a.first
1143           }
1144         }.join("\n")
1145       else
1146         list = scores.map { |a|
1147           i+=1
1148           _("%{i}. %{nick} ( %{score} )") % {
1149             :i => i, :nick => a.last, :score => a.first
1150           }
1151         }.join(" | ")
1152       end
1153     elsif n = p[:winnum]
1154       msg = _("%{uno} %{num} most wins: ") % {
1155         :uno => UnoGame::UNO, :num => p[:winnum]
1156       }
1157       wins.sort! { |a1, a2| -(a1.first <=> a2.first) }
1158       wins = wins[0, n.to_i].compact
1159       i = 0
1160       if wins.length <= 5
1161         list = "\n" + wins.map { |a|
1162           i+=1
1163           _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} wins") % {
1164             :i => i, :b => Bold, :nick => a.last, :score => a.first
1165           }
1166         }.join("\n")
1167       else
1168         list = wins.map { |a|
1169           i+=1
1170           _("%{i}. %{nick} ( %{score} )") % {
1171             :i => i, :nick => a.last, :score => a.first
1172           }
1173         }.join(" | ")
1174       end
1175     else
1176       msg = _("uh, what kind of score list did you want, again?")
1177       list = _(" I can only show the top scores (with top) and the most wins (with topwin)")
1178     end
1179     m.reply msg + list, :max_lines => (msg+list).count("\n")+1
1180   end
1181 end
1182
1183 pg = UnoPlugin.new
1184
1185 pg.map 'uno', :private => false, :action => :create_game
1186 pg.map 'uno end', :private => false, :action => :end_game, :auth_path => 'manage'
1187 pg.map 'uno drop', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1188 pg.map 'uno giveup', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1189 pg.map 'uno drop :nick', :private => false, :action => :drop_player, :auth_path => 'manage::drop::other!'
1190 pg.map 'uno replace :old [with] :new', :private => false, :action => :replace_player, :auth_path => 'manage'
1191 pg.map 'uno transfer [game [ownership]] [to] :nick', :private => false, :action => :transfer_ownership, :auth_path => 'manage'
1192 pg.map 'uno stock', :private => false, :action => :print_stock
1193 pg.map 'uno chanstats', :private => false, :action => :do_chanstats
1194 pg.map 'uno stats [:nick]', :private => false, :action => :do_pstats
1195 pg.map 'uno top :scorenum', :private => false, :action => :do_top, :defaults => { :scorenum => 5 }
1196 pg.map 'uno topwin :winnum', :private => false, :action => :do_top, :defaults => { :winnum => 5 }
1197
1198 pg.default_auth('stock', false)
1199 pg.default_auth('manage', false)
1200 pg.default_auth('manage::drop::self', true)