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