]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/games/uno.rb
6a0562789e463f4d9056e6c2acd4a3134e386e75
[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?|([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       # make sure that if this is the "pick and pass" after a W+4,
548       # then the following player cannot do a challenge:
549       @last_discard = nil
550       @last_color = nil
551     else
552       if @player_has_picked
553         announce _("%{p} passes turn") % { :p => p }
554       else
555         announce _("you need to pick a card first")
556         return
557       end
558     end
559     next_turn
560   end
561
562   def choose_color(user, color)
563     # you can only pick a color if the current color is unset
564     if @color
565       announce _("you can't pick a color now, %{p}") % {
566         :p => get_player(user)
567       }
568       return
569     end
570     case color
571     when 'r'
572       @color = 'Red'
573     when 'b'
574       @color = 'Blue'
575     when 'g'
576       @color = 'Green'
577     when 'y'
578       @color = 'Yellow'
579     else
580       announce _('what color is that?')
581       return
582     end
583     announce _('color is now %{c}') % {
584       :c => UnoGame.irc_color_bg(@color)+" #{@color} "
585     }
586     next_turn
587   end
588
589   def show_time
590     if @start_time
591       announce _("This %{uno} game has been going on for %{time}") % {
592         :uno => UNO,
593         :time => elapsed_time
594       }
595     else
596       announce _("The game hasn't started yet")
597     end
598   end
599
600   def show_order
601     announce _("%{uno} playing turn: %{players}") % {
602       :uno => UNO, :players => players.join(' ')
603     }
604   end
605
606   def show_turn(opts={})
607     cards = true
608     cards = opts[:cards] if opts.key?(:cards)
609     player = @players.first
610     announce _("it's %{player}'s turn") % { :player => player }
611     show_user_cards(player) if cards
612   end
613
614   def has_turn?(source)
615     @start_time && (@players.first.user == source)
616   end
617
618   def show_picker
619     if @picker > 0
620       announce _("next player must respond correctly or pick %{b}%{n}%{b} cards") % {
621         :b => Bold, :n => @picker
622       }
623     end
624   end
625
626   def show_discard
627     announce _("Current discard: %{card} %{c}") % { :card => @discard,
628       :c => (Wild === @discard) ? UnoGame.irc_color_bg(@color) + " #{@color} " : nil
629     }
630     show_picker
631   end
632
633   def show_user_cards(player)
634     p = Player === player ? player : get_player(player)
635     return unless p
636     notify p, _('Your cards: %{cards}') % {
637       :cards => p.cards.join(' ')
638     }
639   end
640
641   def show_all_cards(u=nil)
642     announce(@players.inject([]) { |list, p|
643       list << [p, p.cards.length].join(': ')
644     }.join(', '))
645     if u
646       show_user_cards(u)
647     end
648   end
649
650   def pick_card(user)
651     p = get_player(user)
652     announce _("%{player} picks a card") % { :player => p }
653     deal(p, 1)
654     @player_has_picked = true
655   end
656
657   def deal(player, num=1)
658     picked = []
659     num.times do
660       picked << @stock.delete_one
661       if @stock.length == 0
662         announce _("Shuffling discarded cards")
663         make_stock
664         if @stock.length == 0
665           announce _("No more cards!")
666           end_game # FIXME nope!
667         end
668       end
669     end
670     picked.sort!
671     notify player, _("You picked %{picked}") % { :picked => picked.join(' ') }
672     player.cards += picked
673     player.cards.sort!
674   end
675
676   def add_player(user)
677     if p = get_player(user)
678       announce _("you're already in the game, %{p}") % {
679         :p => p
680       }
681       return
682     end
683     @dropouts.each do |dp|
684       if dp.user == user
685         announce _("you dropped from the game, %{p}, you can't get back in") % {
686           :p => dp
687         }
688         return
689       end
690     end
691     cards = 7
692     if @start_time
693       cards = (@players.inject(0) do |s, pl|
694         s +=pl.cards.length
695       end*1.0/@players.length).ceil
696     end
697     p = Player.new(user)
698     @players << p
699     announce _("%{p} joins this game of %{uno}") % {
700       :p => p, :uno => UNO
701     }
702     deal(p, cards)
703     return if @start_time
704     if @join_timer
705       @bot.timer.reschedule(@join_timer, 10)
706     elsif @players.length > 1
707       announce _("game will start in 20 seconds")
708       @join_timer = @bot.timer.add_once(20) {
709         start_game
710       }
711     end
712   end
713
714   def drop_player(nick)
715     # A nick is passed because the original player might have left
716     # the channel or IRC
717     unless p = get_player(nick)
718       announce _("%{p} isn't playing %{uno}") % {
719         :p => p, :uno => UNO
720       }
721       return
722     end
723     announce _("%{p} gives up this game of %{uno}") % {
724       :p => p, :uno => UNO
725     }
726     case @players.length
727     when 2
728       if @join_timer
729         @bot.timer.remove(@join_timer)
730         announce _("game start countdown stopped")
731         @join_timer = nil
732       end
733       if p == @players.first
734         next_turn :silent => @start_time.nil?
735       end
736       if @start_time
737         end_game
738         return
739       end
740     when 1
741       end_game(true)
742       return
743     end
744     debug @stock.length
745     while p.cards.length > 0
746       @stock.insert(rand(@stock.length), p.cards.shift)
747     end
748     debug @stock.length
749     @dropouts << @players.delete_one(p)
750   end
751
752   def replace_player(old, new)
753     # The new user
754     user = channel.get_user(new)
755     if not user
756       announce _("there is no '%{nick}' here") % {
757         :nick => new
758       }
759       return false
760     end
761     if p = get_player(user)
762       announce _("%{p} is already playing %{uno} here") % {
763         :p => p, :uno => UNO
764       }
765       return false
766     end
767     # We scan the player list of the player with the old nick, instead
768     # of using get_player, in case of IRC drops etc
769     @players.each do |p|
770       if p.user.nick == old
771         p.user = user
772         announce _("%{p} takes %{b}%{old}%{b}'s place at %{uno}") % {
773           :p => p, :b => Bold, :old => old, :uno => UNO
774         }
775         return true
776       end
777     end
778     announce _("%{b}%{old}%{b} isn't playing %{uno} here") % {
779       :uno => UNO, :b => Bold, :old => old
780     }
781     return false
782   end
783
784   def end_game(halted = false)
785     runtime = @start_time ? Time.now -  @start_time : 0
786     if @join_timer
787       @bot.timer.remove(@join_timer)
788       announce _("game start countdown stopped")
789       @join_timer = nil
790     end
791     if halted
792       if @start_time
793         announce _("%{uno} game halted after %{time}") % {
794           :time => elapsed_time,
795           :uno => UNO
796         }
797       else
798         announce _("%{uno} game halted before it could start") % {
799           :uno => UNO
800         }
801       end
802     else
803       announce _("%{uno} game finished after %{time}! The winner is %{p}") % {
804         :time => elapsed_time,
805         :uno => UNO, :p => @players.first
806       }
807     end
808     if @picker > 0 and not halted
809       if @discard.value == 'Reverse'
810         p = @players.last
811       else
812         p = @players[1]
813       end
814       announce _("%{p} has to pick %{b}%{n}%{b} cards!") % {
815         :p => p, :n => @picker, :b => Bold
816       }
817       deal(p, @picker)
818       @picker = 0
819     end
820     score = @players.inject(0) do |sum, p|
821       if p.cards.length > 0
822         announce _("%{p} still had %{cards}") % {
823           :p => p, :cards => p.cards.join(' ')
824         }
825         sum += p.cards.inject(0) do |cs, c|
826           cs += c.score
827         end
828       end
829       sum
830     end
831
832     closure = { :dropouts => @dropouts, :players => @players, :runtime => runtime }
833     if not halted
834       announce _("%{p} wins with %{b}%{score}%{b} points!") % {
835         :p => @players.first, :score => score, :b => Bold
836       }
837       closure.merge!(:winner => @players.first, :score => score,
838         :opponents => @players.length - 1)
839     end
840
841     @plugin.do_end_game(@channel, closure)
842   end
843
844 end
845
846 # A won game: store score and number of opponents, so we can calculate
847 # an average score per opponent (requested by Squiddhartha)
848 define_structure :UnoGameWon, :score, :opponents
849 # For each player we store the number of games played, the number of
850 # games forfeited, and an UnoGameWon for each won game
851 define_structure :UnoPlayerStats, :played, :forfeits, :won
852
853 class UnoPlugin < Plugin
854   attr :games
855   def initialize
856     super
857     @games = {}
858   end
859
860   def help(plugin, topic="")
861     case topic
862     when 'commands'
863       [
864       _("'jo' to join in"),
865       _("'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"),
866       _("'pe' to pick a card"),
867       _("'pa' to pass your turn"),
868       _("'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)"),
869       _("'ca' to show current cards"),
870       _("'cd' to show the current discard"),
871       _("'ch' to challenge a Wild +4"),
872       _("'od' to show the playing order"),
873       _("'ti' to show play time"),
874       _("'tu' to show whose turn it is")
875     ].join("; ")
876     when 'challenge'
877       _("A Wild +4 can only be played legally if you don't have normal (not special) cards of the current color. ") +
878       _("The next player can challenge a W+4 by using the 'ch' command. ") +
879       _("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. ") +
880       _("If the W+4 play was legal, the challenger must pick 6 cards instead of 4.")
881     when 'rules'
882       _("play all your cards, one at a time, by matching either the color or the value of the currently discarded card. ") +
883       _("cards with special effects: Skip (next player skips a turn), Reverse (reverses the playing order), +2 (next player has to take 2 cards). ") +
884       _("Wilds can be played on any card, and you must specify the color for the next card. ") +
885       _("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. ") +
886       _("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. ") +
887       _("you can also play a Reverse on a +2 or +4, bouncing the effect back to the previous player (that now comes next). ")
888     when /scor(?:e|ing)/, /points?/
889       [
890       _("The points won with a game of %{uno} are totalled from the cards remaining in the hands of the other players."),
891       _("Each normal (not special) card is worth its face value (from 0 to 9 points)."),
892       _("Each colored special card (+2, Reverse, Skip) is worth 20 points."),
893       _("Each Wild and Wild +4 is worth 50 points."),
894       help(plugin, 'top'),
895       help(plugin, 'topwin'),
896       ].join(" ") % { :uno => UnoGame::UNO }
897     when 'top'
898       _("You can see the scoring table with 'uno top N' where N is the number of top scores to show.")
899     when 'topwin'
900       _("You can see the winners table with 'uno topwin N' where N is the number of top winners to show.")
901     when /cards?/
902       [
903       _("There are 108 cards in a standard %{uno} deck."),
904       _("For each color (Blue, Green, Red, Yellow) there are 19 numbered cards (from 0 to 9), with two of each number except for 0."),
905       _("There are also 6 special cards for each color, two each of +2, Reverse, Skip."),
906       _("Finally, there are 4 Wild and 4 Wild +4 cards.")
907       ].join(" ") % { :uno => UnoGame::UNO }
908     when 'admin'
909       _("The game manager (the user that started the game) can execute the following commands to manage it: ") +
910       [
911       _("'uno drop <user>' to drop a user from the game (any user can drop itself using 'uno drop')"),
912       _("'uno replace <old> [with] <new>' to replace a player with someone else (useful in case of disconnects)"),
913       _("'uno transfer [to] <nick>' to transfer game ownership to someone else"),
914       _("'uno end' to end the game before its natural completion")
915       ].join("; ")
916     else
917       _("%{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}.") % {
918         :uno => UnoGame::UNO,
919         :cmds => help(plugin, 'commands')
920       }
921     end
922   end
923
924   def message(m)
925     return unless @games.key?(m.channel)
926     return unless m.plugin # skip messages such as: <someuser> botname,
927     g = @games[m.channel]
928     replied = true
929     case m.plugin.intern
930     when :jo # join game
931       return if m.params
932       g.add_player(m.source)
933     when :pe # pick card
934       return if m.params
935       if g.has_turn?(m.source)
936         if g.player_has_picked
937           m.reply _("you already picked a card")
938         elsif g.picker > 0
939           g.pass(m.source)
940         else
941           g.pick_card(m.source)
942         end
943       else
944         m.reply _("It's not your turn")
945       end
946     when :pa # pass turn
947       return if m.params or not g.start_time
948       if g.has_turn?(m.source)
949         g.pass(m.source)
950       else
951         m.reply _("It's not your turn")
952       end
953     when :pl # play card
954       if g.has_turn?(m.source)
955         g.play_card(m.source, m.params.downcase)
956       else
957         m.reply _("It's not your turn")
958       end
959     when :co # pick color
960       if g.has_turn?(m.source)
961         g.choose_color(m.source, m.params.downcase)
962       else
963         m.reply _("It's not your turn")
964       end
965     when :ca # show current cards
966       return if m.params
967       g.show_all_cards(m.source)
968     when :cd # show current discard
969       return if m.params or not g.start_time
970       g.show_discard
971     when :ch
972       if g.has_turn?(m.source)
973         if g.last_discard
974           g.challenge
975         else
976           m.reply _("previous move cannot be challenged")
977         end
978       else
979         m.reply _("It's not your turn")
980       end
981     when :od # show playing order
982       return if m.params
983       g.show_order
984     when :ti # show play time
985       return if m.params
986       g.show_time
987     when :tu # show whose turn is it
988       return if m.params
989       if g.has_turn?(m.source)
990         m.reply _("it's your turn, sleepyhead"), :nick => true
991       else
992         g.show_turn(:cards => false)
993       end
994     else
995       replied=false
996     end
997     m.replied=true if replied
998   end
999
1000   def create_game(m, p)
1001     if @games.key?(m.channel)
1002       m.reply _("There is already an %{uno} game running here, managed by %{who}. say 'jo' to join in") % {
1003         :who => @games[m.channel].manager,
1004         :uno => UnoGame::UNO
1005       }
1006       return
1007     end
1008     @games[m.channel] = UnoGame.new(self, m.channel, m.source)
1009     @bot.auth.irc_to_botuser(m.source).set_temp_permission('uno::manage', true, m.channel)
1010     m.reply _("Ok, created %{uno} game on %{channel}, say 'jo' to join in") % {
1011       :uno => UnoGame::UNO,
1012       :channel => m.channel
1013     }
1014   end
1015
1016   def transfer_ownership(m, p)
1017     unless @games.key?(m.channel)
1018       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1019       return
1020     end
1021     g = @games[m.channel]
1022     old = g.manager
1023     new = m.channel.get_user(p[:nick])
1024     if new
1025       g.manager = new
1026       @bot.auth.irc_to_botuser(old).reset_temp_permission('uno::manage', m.channel)
1027       @bot.auth.irc_to_botuser(new).set_temp_permission('uno::manage', true, m.channel)
1028       m.reply _("%{uno} game ownership transferred from %{old} to %{nick}") % {
1029         :uno => UnoGame::UNO, :old => old, :nick => p[:nick]
1030       }
1031     else
1032       m.reply _("who is this %{nick} you want me to transfer game ownership to?") % p
1033     end
1034   end
1035
1036   def end_game(m, p)
1037     unless @games.key?(m.channel)
1038       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1039       return
1040     end
1041     @games[m.channel].end_game(true)
1042   end
1043
1044   def cleanup
1045     @games.each { |k, g| g.end_game(true) }
1046     super
1047   end
1048
1049   def chan_reg(channel)
1050     @registry.sub_registry(channel.downcase)
1051   end
1052
1053   def chan_stats(channel)
1054     stats = chan_reg(channel).sub_registry('stats')
1055     class << stats
1056       def store(val)
1057         val.to_i
1058       end
1059       def restore(val)
1060         val.to_i
1061       end
1062     end
1063     stats.set_default(0)
1064     return stats
1065   end
1066
1067   def chan_pstats(channel)
1068     pstats = chan_reg(channel).sub_registry('players')
1069     pstats.set_default(UnoPlayerStats.new(0,0,[]))
1070     return pstats
1071   end
1072
1073   def do_end_game(channel, closure)
1074     reg = chan_reg(channel)
1075     stats = chan_stats(channel)
1076     stats['played'] += 1
1077     stats['played_runtime'] += closure[:runtime]
1078     if closure[:winner]
1079       stats['finished'] += 1
1080       stats['finished_runtime'] += closure[:runtime]
1081
1082       pstats = chan_pstats(channel)
1083
1084       closure[:players].each do |pl|
1085         k = pl.user.downcase
1086         pls = pstats[k]
1087         pls.played += 1
1088         pstats[k] = pls
1089       end
1090
1091       closure[:dropouts].each do |pl|
1092         k = pl.user.downcase
1093         pls = pstats[k]
1094         pls.played += 1
1095         pls.forfeits += 1
1096         pstats[k] = pls
1097       end
1098
1099       winner = closure[:winner]
1100       won = UnoGameWon.new(closure[:score], closure[:opponents])
1101       k = winner.user.downcase
1102       pls = pstats[k] # already marked played +1 above
1103       pls.won << won
1104       pstats[k] = pls
1105     end
1106
1107     @bot.auth.irc_to_botuser(@games[channel].manager).reset_temp_permission('uno::manage', channel)
1108     @games.delete(channel)
1109   end
1110
1111   def do_chanstats(m, p)
1112     stats = chan_stats(m.channel)
1113     np = stats['played']
1114     nf = stats['finished']
1115     if np > 0
1116       str = _("%{nf} %{uno} games completed over %{np} games played. ") % {
1117         :np => np, :uno => UnoGame::UNO, :nf => nf
1118       }
1119       cgt = stats['finished_runtime']
1120       tgt = stats['played_runtime']
1121       str << _("%{cgt} game time for completed games") % {
1122         :cgt => Utils.secs_to_string(cgt)
1123       }
1124       if np > nf
1125         str << _(" on %{tgt} total game time. ") % {
1126           :tgt => Utils.secs_to_string(tgt)
1127         }
1128       else
1129         str << ". "
1130       end
1131       str << _("%{avg} average game time for completed games") % {
1132         :avg => Utils.secs_to_string(cgt/nf)
1133       }
1134       str << _(", %{tavg} for all games") % {
1135         :tavg => Utils.secs_to_string(tgt/np)
1136       } if np > nf
1137       m.reply str
1138     else
1139       m.reply _("nobody has played %{uno} on %{chan} yet") % {
1140         :uno => UnoGame::UNO, :chan => m.channel
1141       }
1142     end
1143   end
1144
1145   def do_pstats(m, p)
1146     dnick = p[:nick] || m.source # display-nick, don't later case
1147     nick = dnick.downcase
1148     ps = chan_pstats(m.channel)[nick]
1149     if ps.played == 0
1150       m.reply _("%{nick} never played %{uno} here") % {
1151         :uno => UnoGame::UNO, :nick => dnick
1152       }
1153       return
1154     end
1155     np = ps.played
1156     nf = ps.forfeits
1157     nw = ps.won.length
1158     score = ps.won.inject(0) { |sum, w| sum += w.score }
1159     str = _("%{nick} played %{np} %{uno} games here, ") % {
1160       :nick => dnick, :np => np, :uno => UnoGame::UNO
1161     }
1162     str << _("forfeited %{nf} games, ") % { :nf => nf } if nf > 0
1163     str << _("won %{nw} games") % { :nw => nw}
1164     if nw > 0
1165       str << _(" with %{score} total points") % { :score => score }
1166       avg = ps.won.inject(0) { |sum, w| sum += w.score/w.opponents }/nw
1167       str << _(" and an average of %{avg} points per opponent") % { :avg => avg }
1168     end
1169     m.reply str
1170   end
1171
1172   def replace_player(m, p)
1173     unless @games.key?(m.channel)
1174       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1175       return
1176     end
1177     @games[m.channel].replace_player(p[:old], p[:new])
1178   end
1179
1180   def drop_player(m, p)
1181     unless @games.key?(m.channel)
1182       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1183       return
1184     end
1185     @games[m.channel].drop_player(p[:nick] || m.source.nick)
1186   end
1187
1188   def print_stock(m, p)
1189     unless @games.key?(m.channel)
1190       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1191       return
1192     end
1193     stock = @games[m.channel].stock
1194     m.reply(_("%{num} cards in stock: %{stock}") % {
1195       :num => stock.length,
1196       :stock => stock.join(' ')
1197     }, :split_at => /#{NormalText}\s*/)
1198   end
1199
1200   def do_top(m, p)
1201     pstats = chan_pstats(m.channel)
1202     scores = []
1203     wins = []
1204     pstats.each do |k, v|
1205       wins << [v.won.length, k]
1206       scores << [v.won.inject(0) { |s, w| s+=w.score }, k]
1207     end
1208
1209     if wins.empty?
1210       m.reply(_("no %{uno} games were completed here") % {
1211         :uno => UnoGame::UNO
1212       })
1213       return
1214     end
1215
1216
1217     if n = p[:scorenum]
1218       msg = _("%{uno} %{num} highest scores: ") % {
1219         :uno => UnoGame::UNO, :num => p[:scorenum]
1220       }
1221       scores.sort! { |a1, a2| -(a1.first <=> a2.first) }
1222       scores = scores[0, n.to_i].compact
1223       i = 0
1224       if scores.length <= 5
1225         list = "\n" + scores.map { |a|
1226           i+=1
1227           _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} points") % {
1228             :i => i, :b => Bold, :nick => a.last, :score => a.first
1229           }
1230         }.join("\n")
1231       else
1232         list = scores.map { |a|
1233           i+=1
1234           _("%{i}. %{nick} ( %{score} )") % {
1235             :i => i, :nick => a.last, :score => a.first
1236           }
1237         }.join(" | ")
1238       end
1239     elsif n = p[:winnum]
1240       msg = _("%{uno} %{num} most wins: ") % {
1241         :uno => UnoGame::UNO, :num => p[:winnum]
1242       }
1243       wins.sort! { |a1, a2| -(a1.first <=> a2.first) }
1244       wins = wins[0, n.to_i].compact
1245       i = 0
1246       if wins.length <= 5
1247         list = "\n" + wins.map { |a|
1248           i+=1
1249           _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} wins") % {
1250             :i => i, :b => Bold, :nick => a.last, :score => a.first
1251           }
1252         }.join("\n")
1253       else
1254         list = wins.map { |a|
1255           i+=1
1256           _("%{i}. %{nick} ( %{score} )") % {
1257             :i => i, :nick => a.last, :score => a.first
1258           }
1259         }.join(" | ")
1260       end
1261     else
1262       msg = _("uh, what kind of score list did you want, again?")
1263       list = _(" I can only show the top scores (with top) and the most wins (with topwin)")
1264     end
1265     m.reply msg + list, :max_lines => (msg+list).count("\n")+1
1266   end
1267 end
1268
1269 pg = UnoPlugin.new
1270
1271 pg.map 'uno', :private => false, :action => :create_game
1272 pg.map 'uno end', :private => false, :action => :end_game, :auth_path => 'manage'
1273 pg.map 'uno drop', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1274 pg.map 'uno giveup', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1275 pg.map 'uno drop :nick', :private => false, :action => :drop_player, :auth_path => 'manage::drop::other!'
1276 pg.map 'uno replace :old [with] :new', :private => false, :action => :replace_player, :auth_path => 'manage'
1277 pg.map 'uno transfer [game [ownership]] [to] :nick', :private => false, :action => :transfer_ownership, :auth_path => 'manage'
1278 pg.map 'uno stock', :private => false, :action => :print_stock
1279 pg.map 'uno chanstats', :private => false, :action => :do_chanstats
1280 pg.map 'uno stats [:nick]', :private => false, :action => :do_pstats
1281 pg.map 'uno top :scorenum', :private => false, :action => :do_top, :defaults => { :scorenum => 5 }
1282 pg.map 'uno topwin :winnum', :private => false, :action => :do_top, :defaults => { :winnum => 5 }
1283
1284 pg.default_auth('stock', false)
1285 pg.default_auth('manage', false)
1286 pg.default_auth('manage::drop::self', true)