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