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