4 # :title: Uno Game Plugin for rbot
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # Copyright:: (C) 2008 Giuseppe Bilotta
12 # Uno Game: get rid of the cards you have
15 # TODO allow full form card names for play
16 # TODO allow choice of rules re stacking + and playing Reverse with them
19 COLORS = %w{Red Green Blue Yellow}
20 SPECIALS = %w{+2 Reverse Skip}
21 NUMERICS = (0..9).to_a
22 VALUES = NUMERICS + SPECIALS
24 def UnoGame.color_map(clr)
37 def UnoGame.irc_color_bg(clr)
38 Irc.color([:white,:black][COLORS.index(clr)%2],UnoGame.color_map(clr))
41 def UnoGame.irc_color_fg(clr)
42 Irc.color(UnoGame.color_map(clr))
45 def UnoGame.colorify(str, fg=false)
47 str.length.times do |i|
49 UnoGame.irc_color_fg(COLORS[i%4]) :
50 UnoGame.irc_color_bg(COLORS[i%4]) ) +str[i,1]
55 UNO = UnoGame.colorify('UNO!', true)
61 attr_reader :shortform
65 def initialize(color, value)
66 raise unless COLORS.include? color
68 raise unless VALUES.include? value
69 if NUMERICS.include? value
77 @shortform = (@color[0,1]+@value).downcase
79 @shortform = (@color[0,1]+@value.to_s[0,1]).downcase
81 @to_s = UnoGame.irc_color_bg(@color) +
82 Bold + ['', @color, @value, ''].join(' ') + NormalText
86 return 0 unless @value.to_s[0,1] == '+'
87 return @value[1,1].to_i
91 SPECIALS.include?(@value)
95 cc = self.color <=> other.color
97 return self.value.to_s <=> other.value.to_s
105 # Wild, Wild +4 cards
107 def initialize(value=nil)
109 raise if value and not value == '+4'
112 @shortform = 'w'+value
118 @to_s = UnoGame.colorify(['', @color, @value, ''].compact.join(' '))
135 has << c if c.shortform == short
144 Bold + @user.to_s + Bold
152 # previous discard, in case of challenge
153 attr_reader :last_discard
154 # channel the game is played in
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
163 def initialize(plugin, channel)
187 return p if p.user == user
191 return p if p.user.irc_downcase == user.irc_downcase(channel.casemap)
194 get_player(user.to_s)
199 def announce(msg, opts={})
200 @bot.say channel, msg, opts
203 def notify(player, msg, opts={})
204 @bot.notice player.user, msg, opts
208 @base_stock = COLORS.inject([]) do |list, clr|
210 list << Card.new(clr, n)
211 list << Card.new(clr, n) unless n == 0
216 @base_stock << Wild.new
217 @base_stock << Wild.new('+4')
222 @stock.replace @base_stock
223 # remove the cards in the players hand
224 @players.each { |p| p.cards.each { |c| @stock.delete_one c } }
225 # remove current top discarded card if present
227 @stock.delete_one(discard)
233 debug "Starting game"
236 announce _("%{p} deals the first card from the stock") % {
242 while Wild === card do
243 @stock.insert(rand(@stock.length), card)
252 @start_time = Time.now
257 Utils.secs_to_string(Time.now-@start_time)
264 # if there are two players, the Reverse acts like a Skip, unless
265 # there's a @picker running, in which case the Reverse should bounce the
266 # pick on the other player
267 if @players.length > 2
269 # put the current player back in its place
270 @players.unshift @players.pop
271 announce _("Playing order was reversed!")
273 announce _("%{cp} bounces the pick to %{np}") % {
274 :cp => @players.first,
283 @players << @players.shift
284 announce _("%{p} skips a turn!") % {
285 # this is first and not last because the actual
286 # turn change will be done by the following next_turn
302 def set_discard(card)
304 @value = card.value.dup rescue card.value
308 @color = card.color.dup
311 @picker += card.picker
312 @last_picker = @discard.picker
322 def next_turn(opts={})
323 @players << @players.shift
324 @player_has_picked = false
329 # if play is forced, check against the only allowed cards
330 return false if @must_play and not @must_play.include?(card)
332 # When a +something is online, you can only play a +something of same or
333 # higher something, or a Reverse of the correct color, or a Reverse on
337 return true if card.picker >= @last_picker
338 return true if card.value == 'Reverse' and (card.color == @color or @discard.value == card.value)
341 # You can always play a Wild
342 return true if Wild === card
343 # On a Wild, you must match the color
345 return card.color == @color
347 # Otherwise, you can match either the value or the color
348 return (card.value == @value) || (card.color == @color)
353 def play_card(source, cards)
354 debug "Playing card #{cards}"
355 p = get_player(source)
356 shorts = cards.gsub(/\s+/,'').match(/^(?:([rbgy]\+?\d){1,2}|([rbgy][rs])|(w(?:\+4)?)([rbgy])?)$/).to_a
359 announce _("what cards were that again?")
363 short = shorts[1] || shorts[2] || shorts[3]
369 toplay = (full == short) ? 1 : 2
371 debug [full, short, jolly, jcolor, toplay].inspect
372 # r7r7 -> r7r7, r7, nil, nil
373 # r7 -> r7, r7, nil, nil
374 # w -> w, nil, w, nil
375 # wg -> wg, nil, w, g
376 if cards = p.has_card?(short)
378 unless can_play(cards.first)
379 announce _("you can't play that card")
382 if cards.length >= toplay
383 # if the played card is a W+4 not played during a stacking +x
384 # TODO if A plays an illegal W+4, B plays a W+4, should the next
385 # player be able to challenge A? For the time being we say no,
386 # but I think he should, and in case A's move was illegal
387 # game would have to go back, A would get the penalty and replay,
388 # while if it was legal the challenger would get 50% more cards,
389 # i.e. 12 cards (or more if the stacked +4 were more). This would
390 # only be possible if the first W+4 was illegal, so it wouldn't
391 # apply for a W+4 played on a +2 anyway.
393 if @picker == 0 and Wild === cards.first and cards.first.value
394 # save the previous discard in case of challenge
395 @last_discard = @discard.dup
396 # save the color too, in case it was a Wild
397 @last_color = @color.dup
399 # mark the move as not challengeable
403 set_discard(p.cards.delete_one(cards.shift))
405 set_discard(p.cards.delete_one(cards.shift))
406 announce _("%{p} plays %{card} twice!") % {
411 announce _("%{p} plays %{card}") % { :p => p, :card => @discard }
413 if p.cards.length == 1
414 announce _("%{p} has %{uno}!") % {
417 elsif p.cards.length == 0
428 choose_color(p.user, jcolor)
430 announce _("%{p}, choose a color with: co r|b|g|y") % { :p => p }
433 announce _("you don't have two cards of that kind")
436 announce _("you don't have that card")
441 return unless @last_discard
446 announce _("%{cp} challenges %{lp}'s %{card}!") % {
447 :cp => cp, :lp => lp, :card => @discard
449 # show the cards of the previous player to the current player
450 notify cp, _("%{p} has %{cards}") % {
451 :p => lp, :cards => lp.cards.join(' ')
453 # check if the previous player had a non-special card of the correct color
456 if c.color == @last_color and not c.special?
462 announce _("%{lp}'s move was legal, %{cp} must pick %{b}%{n}%{b} cards!") % {
463 :cp => cp, :lp => lp, :b => Bold, :n => @picker
471 announce _("%{lp}'s move was %{b}not%{b} legal, %{lp} must pick %{b}%{n}%{b} cards and play again!") % {
472 :cp => cp, :lp => lp, :b => Bold, :n => @picker
474 lp.cards << @discard # put the W+4 back in place
477 @color = @last_color.dup
478 @discard = @last_discard.dup
480 @value = @discard.value.dup rescue @discard.value
484 # force the player to play the current cards
485 @must_play = lp.cards.dup
487 # give him the penalty cards
491 # and restore the turn
492 @players.unshift @players.pop
499 announce _("%{p} passes turn, and has to pick %{b}%{n}%{b} cards!") % {
500 :p => p, :b => Bold, :n => @picker
505 if @player_has_picked
506 announce _("%{p} passes turn") % { :p => p }
508 announce _("you need to pick a card first")
515 def choose_color(user, color)
526 announce _('what color is that?')
529 announce _('color is now %{c}') % {
530 :c => UnoGame.irc_color_bg(@color)+" #{@color} "
537 announce _("This %{uno} game has been going on for %{time}") % {
539 :time => elapsed_time
542 announce _("The game hasn't started yet")
547 announce _("%{uno} playing turn: %{players}") % {
548 :uno => UNO, :players => players.join(' ')
552 def show_turn(opts={})
554 cards = opts[:cards] if opts.key?(:cards)
555 player = @players.first
556 announce _("it's %{player}'s turn") % { :player => player }
557 show_user_cards(player) if cards
560 def has_turn?(source)
561 @players.first.user == source
566 announce _("next player must respond correctly or pick %{b}%{n}%{b} cards") % {
567 :b => Bold, :n => @picker
573 announce _("Current discard: %{card} %{c}") % { :card => @discard,
574 :c => (Wild === @discard) ? UnoGame.irc_color_bg(@color) + " #{@color} " : nil
579 def show_user_cards(player)
580 p = Player === player ? player : get_player(player)
581 notify p, _('Your cards: %{cards}') % {
582 :cards => p.cards.join(' ')
586 def show_all_cards(u=nil)
587 announce(@players.inject([]) { |list, p|
588 list << [p, p.cards.length].join(': ')
597 announce _("%{player} picks a card") % { :player => p }
599 @player_has_picked = true
602 def deal(player, num=1)
605 picked << @stock.delete_one
606 if @stock.length == 0
607 announce _("Shuffling discarded cards")
609 if @stock.length == 0
610 announce _("No more cards!")
611 end_game # FIXME nope!
616 notify player, _("You picked %{picked}") % { :picked => picked.join(' ') }
617 player.cards += picked
622 if p = get_player(user)
623 announce _("you're already in the game, %{p}") % {
628 @dropouts.each do |dp|
630 announce _("you dropped from the game, %{p}, you can't get back in") % {
638 cards = @players.inject(0) do |s, pl|
644 announce _("%{p} joins this game of %{uno}") % {
648 return if @start_time
650 @bot.timer.reschedule(@join_timer, 10)
651 elsif @players.length > 1
652 announce _("game will start in 20 seconds")
653 @join_timer = @bot.timer.add_once(20) {
659 def drop_player(nick)
660 # A nick is passed because the original player might have left
662 unless p = get_player(nick)
663 announce _("%{p} isn't playing %{uno}") % {
668 announce _("%{p} gives up this game of %{uno}") % {
673 if p == @players.first
683 while p.cards.length > 0
684 @stock.insert(rand(@stock.length), p.cards.shift)
687 @dropouts << @players.delete_one(p)
690 def replace_player(old, new)
692 user = channel.get_user(new)
693 if p = get_player(user)
694 announce _("%{p} is already playing %{uno} here") % {
699 # We scan the player list of the player with the old nick, instead
700 # of using get_player, in case of IRC drops etc
702 if p.user.nick == old
704 announce _("%{p} takes %{b}%{old}%{b}'s place at %{uno}") % {
705 :p => p, :b => Bold, :old => old, :uno => UNO
710 announce _("%{b}%{old}%{b} isn't playing %{uno} here") % {
711 :uno => UNO, :b => Bold, :old => old
715 def end_game(halted = false)
716 runtime = @start_time ? Time.now - @start_time : 0
719 announce _("%{uno} game halted after %{time}") % {
720 :time => elapsed_time,
724 announce _("%{uno} game halted before it could start") % {
729 announce _("%{uno} game finished after %{time}! The winner is %{p}") % {
730 :time => elapsed_time,
731 :uno => UNO, :p => @players.first
734 if @picker > 0 and not halted
736 announce _("%{p} has to pick %{b}%{n}%{b} cards!") % {
737 :p => p, :n => @picker, :b => Bold
742 score = @players.inject(0) do |sum, p|
743 if p.cards.length > 0
744 announce _("%{p} still had %{cards}") % {
745 :p => p, :cards => p.cards.join(' ')
747 sum += p.cards.inject(0) do |cs, c|
754 closure = { :dropouts => @dropouts, :players => @players, :runtime => runtime }
756 announce _("%{p} wins with %{b}%{score}%{b} points!") % {
757 :p => @players.first, :score => score, :b => Bold
759 closure.merge!(:winner => @players.first, :score => score,
760 :opponents => @players.length - 1)
763 @plugin.do_end_game(@channel, closure)
768 # A won game: store score and number of opponents, so we can calculate
769 # an average score per opponent (requested by Squiddhartha)
770 define_structure :UnoGameWon, :score, :opponents
771 # For each player we store the number of games played, the number of
772 # games forfeited, and an UnoGameWon for each won game
773 define_structure :UnoPlayerStats, :played, :forfeits, :won
775 class UnoPlugin < Plugin
782 def help(plugin, topic="")
786 _("'jo' to join in"),
787 _("'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"),
788 _("'pe' to pick a card"),
789 _("'pa' to pass your turn"),
790 _("'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)"),
791 _("'ca' to show current cards"),
792 _("'cd' to show the current discard"),
793 _("'ch' to challenge a Wild +4"),
794 _("'od' to show the playing order"),
795 _("'ti' to show play time"),
796 _("'tu' to show whose turn it is")
799 _("A Wild +4 can only be played legally if you don't have normal (not special) cards of the current color. ") +
800 _("The next player can challenge a W+4 by using the 'ch' command. ") +
801 _("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. ") +
802 _("If the W+4 play was legal, the challenger must pick 6 cards instead of 4.")
804 _("play all your cards, one at a time, by matching either the color or the value of the currently discarded card. ") +
805 _("cards with special effects: Skip (next player skips a turn), Reverse (reverses the playing order), +2 (next player has to take 2 cards). ") +
806 _("Wilds can be played on any card, and you must specify the color for the next card. ") +
807 _("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. ") +
808 _("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. ") +
809 _("you can also play a Reverse on a +2 or +4, bouncing the effect back to the previous player (that now comes next). ")
811 (_("%{uno} game. !uno to start a game. see help uno rules for the rules. commands: %{cmds}") % {
812 :uno => UnoGame::UNO,
813 :cmds => help(plugin, 'commands')
819 return unless @games.key?(m.channel)
820 g = @games[m.channel]
824 g.add_player(m.source)
827 if g.has_turn?(m.source)
828 if g.player_has_picked
829 m.reply _("you already picked a card")
833 g.pick_card(m.source)
836 m.reply _("It's not your turn")
840 if g.has_turn?(m.source)
843 m.reply _("It's not your turn")
846 if g.has_turn?(m.source)
847 g.play_card(m.source, m.params.downcase)
849 m.reply _("It's not your turn")
851 when :co # pick color
852 if g.has_turn?(m.source)
853 g.choose_color(m.source, m.params.downcase)
855 m.reply _("It's not your turn")
857 when :ca # show current cards
859 g.show_all_cards(m.source)
860 when :cd # show current discard
864 if g.has_turn?(m.source)
868 m.reply _("previous move cannot be challenged")
871 m.reply _("It's not your turn")
873 when :od # show playing order
876 when :ti # show play time
879 when :tu # show whose turn is it
881 if g.has_turn?(m.source)
882 m.nickreply _("it's your turn, sleepyhead")
884 g.show_turn(:cards => false)
889 def create_game(m, p)
890 if @games.key?(m.channel)
891 m.reply _("There is already an %{uno} game running here, say 'jo' to join in") % { :uno => UnoGame::UNO }
894 @games[m.channel] = UnoGame.new(self, m.channel)
895 m.reply _("Ok, created %{uno} game on %{channel}, say 'jo' to join in") % {
896 :uno => UnoGame::UNO,
897 :channel => m.channel
902 unless @games.key?(m.channel)
903 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
906 @games[m.channel].end_game(true)
909 def chan_reg(channel)
910 @registry.sub_registry(channel.downcase)
913 def chan_stats(channel)
914 stats = chan_reg(channel).sub_registry('stats')
927 def chan_pstats(channel)
928 pstats = chan_reg(channel).sub_registry('players')
929 pstats.set_default(UnoPlayerStats.new(0,0,[]))
933 def do_end_game(channel, closure)
934 reg = chan_reg(channel)
935 stats = chan_stats(channel)
937 stats['played_runtime'] += closure[:runtime]
939 stats['finished'] += 1
940 stats['finished_runtime'] += closure[:runtime]
942 pstats = chan_pstats(channel)
944 closure[:players].each do |pl|
951 closure[:dropouts].each do |pl|
959 winner = closure[:winner]
960 won = UnoGameWon.new(closure[:score], closure[:opponents])
961 k = winner.user.downcase
962 pls = pstats[k] # already marked played +1 above
967 @games.delete(channel)
970 def do_chanstats(m, p)
971 stats = chan_stats(m.channel)
973 nf = stats['finished']
975 str = _("%{nf} %{uno} games completed over %{np} games played. ") % {
976 :np => np, :uno => UnoGame::UNO, :nf => nf
978 cgt = stats['finished_runtime']
979 tgt = stats['played_runtime']
980 str << _("%{cgt} game time for completed games") % {
981 :cgt => Utils.secs_to_string(cgt)
984 str << _(" on %{tgt} total game time. ") % {
985 :tgt => Utils.secs_to_string(tgt)
990 str << _("%{avg} average game time for completed games") % {
991 :avg => Utils.secs_to_string(cgt/nf)
993 str << _(", %{tavg} for all games") % {
994 :tavg => Utils.secs_to_string(tgt/np)
998 m.reply _("nobody has played %{uno} on %{chan} yet") % {
999 :uno => UnoGame::UNO, :chan => m.channel
1005 dnick = p[:nick] || m.source # display-nick, don't later case
1006 nick = dnick.downcase
1007 ps = chan_pstats(m.channel)[nick]
1009 m.reply _("%{nick} never played %{uno} here") % {
1010 :uno => UnoGame::UNO, :nick => dnick
1017 score = ps.won.inject(0) { |sum, w| sum += w.score }
1018 str = _("%{nick} played %{np} %{uno} games here, ") % {
1019 :nick => dnick, :np => np, :uno => UnoGame::UNO
1021 str << _("forfeited %{nf} games, ") % { :nf => nf } if nf > 0
1022 str << _("won %{nw} games") % { :nw => nw}
1024 str << _(" with %{score} total points") % { :score => score }
1025 avg = ps.won.inject(0) { |sum, w| sum += w.score/w.opponents }/nw
1026 str << _(" and an average of %{avg} points per opponent") % { :avg => avg }
1031 def replace_player(m, p)
1032 unless @games.key?(m.channel)
1033 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1036 @games[m.channel].replace_player(p[:old], p[:new])
1039 def drop_player(m, p)
1040 unless @games.key?(m.channel)
1041 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1044 @games[m.channel].drop_player(p[:nick] || m.source.nick)
1047 def print_stock(m, p)
1048 unless @games.key?(m.channel)
1049 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1052 stock = @games[m.channel].stock
1053 m.reply(_("%{num} cards in stock: %{stock}") % {
1054 :num => stock.length,
1055 :stock => stock.join(' ')
1056 }, :split_at => /#{NormalText}\s*/)
1060 pstats = chan_pstats(m.channel)
1063 pstats.each do |k, v|
1064 wins << [v.won.length, k]
1065 scores << [v.won.inject(0) { |s, w| s+=w.score }, k]
1069 msg = _("%{uno} %{num} highest scores: ") % {
1070 :uno => UnoGame::UNO, :num => p[:scorenum]
1072 scores.sort! { |a1, a2| -(a1.first <=> a2.first) }
1073 scores = scores[0, n.to_i].compact
1074 if scores.length <= 5
1076 list = "\n" + scores.map { |a|
1078 _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} points") % {
1079 :i => i, :b => Bold, :nick => a.last, :score => a.first
1083 list = scores.map { |a|
1085 _("%{i}. %{nick} ( %{score} )") % {
1086 :i => i, :nick => a.last, :score => a.first
1090 elsif n = p[:winnum]
1091 msg = _("%{uno} %{num} most wins: ") % {
1092 :uno => UnoGame::UNO, :num => p[:winnum]
1094 wins.sort! { |a1, a2| -(a1.first <=> a2.first) }
1095 wins = wins[0, n.to_i].compact
1098 list = "\n" + wins.map { |a|
1100 _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} wins") % {
1101 :i => i, :b => Bold, :nick => a.last, :score => a.first
1105 list = wins.map { |a|
1107 _("%{i}. %{nick} ( %{score} )") % {
1108 :i => i, :nick => a.last, :score => a.first
1113 msg = _("uh, what kind of score list did you want, again?")
1114 list = _(" I can only show the top scores (with top) and the most wins (with topwin)")
1116 m.reply msg + list, :max_lines => (msg+list).count("\n")+1
1122 pg.map 'uno', :private => false, :action => :create_game
1123 pg.map 'uno end', :private => false, :action => :end_game, :auth_path => 'manage'
1124 pg.map 'uno drop', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1125 pg.map 'uno giveup', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1126 pg.map 'uno drop :nick', :private => false, :action => :drop_player, :auth_path => 'manage::drop::other!'
1127 pg.map 'uno replace :old [with] :new', :private => false, :action => :replace_player, :auth_path => 'manage'
1128 pg.map 'uno stock', :private => false, :action => :print_stock
1129 pg.map 'uno chanstats', :private => false, :action => :do_chanstats
1130 pg.map 'uno stats [:nick]', :private => false, :action => :do_pstats
1131 pg.map 'uno top :scorenum', :private => false, :action => :do_top, :defaults => { :scorenum => 5 }
1132 pg.map 'uno topwin :winnum', :private => false, :action => :do_top, :defaults => { :winnum => 5 }
1134 pg.default_auth('stock', false)
1135 pg.default_auth('manage', false)
1136 pg.default_auth('manage::drop::self', true)