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