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