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