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