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