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