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