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 # the IRC user that created the game
164 attr_accessor :manager
166 def initialize(plugin, channel, manager)
191 return p if p.user == user
195 return p if p.user.irc_downcase == user.irc_downcase(channel.casemap)
198 get_player(user.to_s)
203 def announce(msg, opts={})
204 @bot.say channel, msg, opts
207 def notify(player, msg, opts={})
208 @bot.notice player.user, msg, opts
212 @base_stock = COLORS.inject([]) do |list, clr|
214 list << Card.new(clr, n)
215 list << Card.new(clr, n) unless n == 0
220 @base_stock << Wild.new
221 @base_stock << Wild.new('+4')
226 @stock.replace @base_stock
227 # remove the cards in the players hand
228 @players.each { |p| p.cards.each { |c| @stock.delete_one c } }
229 # remove current top discarded card if present
231 @stock.delete_one(discard)
237 debug "Starting game"
240 announce _("%{p} deals the first card from the stock") % {
246 while Wild === card do
247 @stock.insert(rand(@stock.length), card)
256 @start_time = Time.now
261 Utils.secs_to_string(Time.now-@start_time)
268 # if there are two players, the Reverse acts like a Skip, unless
269 # there's a @picker running, in which case the Reverse should bounce the
270 # pick on the other player
271 if @players.length > 2
273 # put the current player back in its place
274 @players.unshift @players.pop
275 announce _("Playing order was reversed!")
277 announce _("%{cp} bounces the pick to %{np}") % {
278 :cp => @players.first,
287 @players << @players.shift
288 announce _("%{p} skips a turn!") % {
289 # this is first and not last because the actual
290 # turn change will be done by the following next_turn
306 def set_discard(card)
308 @value = card.value.dup rescue card.value
312 @color = card.color.dup
315 @picker += card.picker
316 @last_picker = @discard.picker
326 def next_turn(opts={})
327 @players << @players.shift
328 @player_has_picked = false
333 # if play is forced, check against the only allowed cards
334 return false if @must_play and not @must_play.include?(card)
336 # When a +something is online, you can only play a +something of same or
337 # higher something, or a Reverse of the correct color, or a Reverse on
341 return true if card.picker >= @last_picker
342 return true if card.value == 'Reverse' and (card.color == @color or @discard.value == card.value)
345 # You can always play a Wild
346 return true if Wild === card
347 # On a Wild, you must match the color
349 return card.color == @color
351 # Otherwise, you can match either the value or the color
352 return (card.value == @value) || (card.color == @color)
357 def play_card(source, cards)
358 debug "Playing card #{cards}"
359 p = get_player(source)
360 shorts = cards.gsub(/\s+/,'').match(/^(?:([rbgy]\+?\d){1,2}|([rbgy][rs])|(w(?:\+4)?)([rbgy])?)$/).to_a
363 announce _("what cards were that again?")
367 short = shorts[1] || shorts[2] || shorts[3]
373 toplay = (full == short) ? 1 : 2
375 debug [full, short, jolly, jcolor, toplay].inspect
376 # r7r7 -> r7r7, r7, nil, nil
377 # r7 -> r7, r7, nil, nil
378 # w -> w, nil, w, nil
379 # wg -> wg, nil, w, g
380 if cards = p.has_card?(short)
382 unless can_play(cards.first)
383 announce _("you can't play that card")
386 if cards.length >= toplay
387 # if the played card is a W+4 not played during a stacking +x
388 # TODO if A plays an illegal W+4, B plays a W+4, should the next
389 # player be able to challenge A? For the time being we say no,
390 # but I think he should, and in case A's move was illegal
391 # game would have to go back, A would get the penalty and replay,
392 # while if it was legal the challenger would get 50% more cards,
393 # i.e. 12 cards (or more if the stacked +4 were more). This would
394 # only be possible if the first W+4 was illegal, so it wouldn't
395 # apply for a W+4 played on a +2 anyway.
397 if @picker == 0 and Wild === cards.first and cards.first.value
398 # save the previous discard in case of challenge
399 @last_discard = @discard.dup
400 # save the color too, in case it was a Wild
401 @last_color = @color.dup
403 # mark the move as not challengeable
407 set_discard(p.cards.delete_one(cards.shift))
409 set_discard(p.cards.delete_one(cards.shift))
410 announce _("%{p} plays %{card} twice!") % {
415 announce _("%{p} plays %{card}") % { :p => p, :card => @discard }
417 if p.cards.length == 1
418 announce _("%{p} has %{uno}!") % {
421 elsif p.cards.length == 0
432 choose_color(p.user, jcolor)
434 announce _("%{p}, choose a color with: co r|b|g|y") % { :p => p }
437 announce _("you don't have two cards of that kind")
440 announce _("you don't have that card")
445 return unless @last_discard
450 announce _("%{cp} challenges %{lp}'s %{card}!") % {
451 :cp => cp, :lp => lp, :card => @discard
453 # show the cards of the previous player to the current player
454 notify cp, _("%{p} has %{cards}") % {
455 :p => lp, :cards => lp.cards.join(' ')
457 # check if the previous player had a non-special card of the correct color
460 if c.color == @last_color and not c.special?
466 announce _("%{lp}'s move was legal, %{cp} must pick %{b}%{n}%{b} cards!") % {
467 :cp => cp, :lp => lp, :b => Bold, :n => @picker
475 announce _("%{lp}'s move was %{b}not%{b} legal, %{lp} must pick %{b}%{n}%{b} cards and play again!") % {
476 :cp => cp, :lp => lp, :b => Bold, :n => @picker
478 lp.cards << @discard # put the W+4 back in place
481 @color = @last_color.dup
482 @discard = @last_discard.dup
484 @value = @discard.value.dup rescue @discard.value
488 # force the player to play the current cards
489 @must_play = lp.cards.dup
491 # give him the penalty cards
495 # and restore the turn
496 @players.unshift @players.pop
503 announce _("%{p} passes turn, and has to pick %{b}%{n}%{b} cards!") % {
504 :p => p, :b => Bold, :n => @picker
509 if @player_has_picked
510 announce _("%{p} passes turn") % { :p => p }
512 announce _("you need to pick a card first")
519 def choose_color(user, color)
530 announce _('what color is that?')
533 announce _('color is now %{c}') % {
534 :c => UnoGame.irc_color_bg(@color)+" #{@color} "
541 announce _("This %{uno} game has been going on for %{time}") % {
543 :time => elapsed_time
546 announce _("The game hasn't started yet")
551 announce _("%{uno} playing turn: %{players}") % {
552 :uno => UNO, :players => players.join(' ')
556 def show_turn(opts={})
558 cards = opts[:cards] if opts.key?(:cards)
559 player = @players.first
560 announce _("it's %{player}'s turn") % { :player => player }
561 show_user_cards(player) if cards
564 def has_turn?(source)
565 @players.first.user == source
570 announce _("next player must respond correctly or pick %{b}%{n}%{b} cards") % {
571 :b => Bold, :n => @picker
577 announce _("Current discard: %{card} %{c}") % { :card => @discard,
578 :c => (Wild === @discard) ? UnoGame.irc_color_bg(@color) + " #{@color} " : nil
583 def show_user_cards(player)
584 p = Player === player ? player : get_player(player)
585 notify p, _('Your cards: %{cards}') % {
586 :cards => p.cards.join(' ')
590 def show_all_cards(u=nil)
591 announce(@players.inject([]) { |list, p|
592 list << [p, p.cards.length].join(': ')
601 announce _("%{player} picks a card") % { :player => p }
603 @player_has_picked = true
606 def deal(player, num=1)
609 picked << @stock.delete_one
610 if @stock.length == 0
611 announce _("Shuffling discarded cards")
613 if @stock.length == 0
614 announce _("No more cards!")
615 end_game # FIXME nope!
620 notify player, _("You picked %{picked}") % { :picked => picked.join(' ') }
621 player.cards += picked
626 if p = get_player(user)
627 announce _("you're already in the game, %{p}") % {
632 @dropouts.each do |dp|
634 announce _("you dropped from the game, %{p}, you can't get back in") % {
642 cards = @players.inject(0) do |s, pl|
648 announce _("%{p} joins this game of %{uno}") % {
652 return if @start_time
654 @bot.timer.reschedule(@join_timer, 10)
655 elsif @players.length > 1
656 announce _("game will start in 20 seconds")
657 @join_timer = @bot.timer.add_once(20) {
663 def drop_player(nick)
664 # A nick is passed because the original player might have left
666 unless p = get_player(nick)
667 announce _("%{p} isn't playing %{uno}") % {
672 announce _("%{p} gives up this game of %{uno}") % {
677 if p == @players.first
687 while p.cards.length > 0
688 @stock.insert(rand(@stock.length), p.cards.shift)
691 @dropouts << @players.delete_one(p)
694 def replace_player(old, new)
696 user = channel.get_user(new)
697 if p = get_player(user)
698 announce _("%{p} is already playing %{uno} here") % {
703 # We scan the player list of the player with the old nick, instead
704 # of using get_player, in case of IRC drops etc
706 if p.user.nick == old
708 announce _("%{p} takes %{b}%{old}%{b}'s place at %{uno}") % {
709 :p => p, :b => Bold, :old => old, :uno => UNO
714 announce _("%{b}%{old}%{b} isn't playing %{uno} here") % {
715 :uno => UNO, :b => Bold, :old => old
719 def end_game(halted = false)
720 runtime = @start_time ? Time.now - @start_time : 0
723 announce _("%{uno} game halted after %{time}") % {
724 :time => elapsed_time,
728 announce _("%{uno} game halted before it could start") % {
733 announce _("%{uno} game finished after %{time}! The winner is %{p}") % {
734 :time => elapsed_time,
735 :uno => UNO, :p => @players.first
738 if @picker > 0 and not halted
740 announce _("%{p} has to pick %{b}%{n}%{b} cards!") % {
741 :p => p, :n => @picker, :b => Bold
746 score = @players.inject(0) do |sum, p|
747 if p.cards.length > 0
748 announce _("%{p} still had %{cards}") % {
749 :p => p, :cards => p.cards.join(' ')
751 sum += p.cards.inject(0) do |cs, c|
758 closure = { :dropouts => @dropouts, :players => @players, :runtime => runtime }
760 announce _("%{p} wins with %{b}%{score}%{b} points!") % {
761 :p => @players.first, :score => score, :b => Bold
763 closure.merge!(:winner => @players.first, :score => score,
764 :opponents => @players.length - 1)
767 @plugin.do_end_game(@channel, closure)
772 # A won game: store score and number of opponents, so we can calculate
773 # an average score per opponent (requested by Squiddhartha)
774 define_structure :UnoGameWon, :score, :opponents
775 # For each player we store the number of games played, the number of
776 # games forfeited, and an UnoGameWon for each won game
777 define_structure :UnoPlayerStats, :played, :forfeits, :won
779 class UnoPlugin < Plugin
786 def help(plugin, topic="")
790 _("'jo' to join in"),
791 _("'pl <card>' to play <card>: e.g. 'pl g7' to play Green 7, or 'pl rr' to play Red Reverse, or 'pl y2y2' to play both Yellow 2 cards"),
792 _("'pe' to pick a card"),
793 _("'pa' to pass your turn"),
794 _("'co <color>' to pick a color after playing a Wild: e.g. 'co g' to select Green (or 'pl w+4 g' to select the color when playing the Wild)"),
795 _("'ca' to show current cards"),
796 _("'cd' to show the current discard"),
797 _("'ch' to challenge a Wild +4"),
798 _("'od' to show the playing order"),
799 _("'ti' to show play time"),
800 _("'tu' to show whose turn it is")
803 _("A Wild +4 can only be played legally if you don't have normal (not special) cards of the current color. ") +
804 _("The next player can challenge a W+4 by using the 'ch' command. ") +
805 _("If the W+4 play was illegal, the player who played it must pick the W+4, pick 4 cards from the stock, and play a legal card. ") +
806 _("If the W+4 play was legal, the challenger must pick 6 cards instead of 4.")
808 _("play all your cards, one at a time, by matching either the color or the value of the currently discarded card. ") +
809 _("cards with special effects: Skip (next player skips a turn), Reverse (reverses the playing order), +2 (next player has to take 2 cards). ") +
810 _("Wilds can be played on any card, and you must specify the color for the next card. ") +
811 _("Wild +4 also forces the next player to take 4 cards, but it can only be played if you can't play a color card. ") +
812 _("you can play another +2 or +4 card on a +2 card, and a +4 on a +4, forcing the first player who can't play one to pick the cumulative sum of all cards. ") +
813 _("you can also play a Reverse on a +2 or +4, bouncing the effect back to the previous player (that now comes next). ")
815 (_("%{uno} game. !uno to start a game. see help uno rules for the rules. commands: %{cmds}") % {
816 :uno => UnoGame::UNO,
817 :cmds => help(plugin, 'commands')
823 return unless @games.key?(m.channel)
824 g = @games[m.channel]
828 g.add_player(m.source)
831 if g.has_turn?(m.source)
832 if g.player_has_picked
833 m.reply _("you already picked a card")
837 g.pick_card(m.source)
840 m.reply _("It's not your turn")
844 if g.has_turn?(m.source)
847 m.reply _("It's not your turn")
850 if g.has_turn?(m.source)
851 g.play_card(m.source, m.params.downcase)
853 m.reply _("It's not your turn")
855 when :co # pick color
856 if g.has_turn?(m.source)
857 g.choose_color(m.source, m.params.downcase)
859 m.reply _("It's not your turn")
861 when :ca # show current cards
863 g.show_all_cards(m.source)
864 when :cd # show current discard
868 if g.has_turn?(m.source)
872 m.reply _("previous move cannot be challenged")
875 m.reply _("It's not your turn")
877 when :od # show playing order
880 when :ti # show play time
883 when :tu # show whose turn is it
885 if g.has_turn?(m.source)
886 m.nickreply _("it's your turn, sleepyhead")
888 g.show_turn(:cards => false)
893 def create_game(m, p)
894 if @games.key?(m.channel)
895 m.reply _("There is already an %{uno} game running here, managed by %{who}. say 'jo' to join in") % {
896 :who => @games[m.channel].manager,
901 @games[m.channel] = UnoGame.new(self, m.channel, m.source)
902 @bot.auth.irc_to_botuser(m.source).set_temp_permission('uno::manage', true, m.channel)
903 m.reply _("Ok, created %{uno} game on %{channel}, say 'jo' to join in") % {
904 :uno => UnoGame::UNO,
905 :channel => m.channel
909 def transfer_ownership(m, p)
910 unless @games.key?(m.channel)
911 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
914 g = @games[m.channel]
916 new = m.channel.get_user(p[:nick])
919 @bot.auth.irc_to_botuser(old).reset_temp_permission('uno::manage', m.channel)
920 @bot.auth.irc_to_botuser(new).set_temp_permission('uno::manage', true, m.channel)
921 m.reply _("%{uno} game ownership transferred from %{old} to %{nick}") % {
922 :uno => UnoGame::UNO, :old => old, :nick => p[:nick]
925 m.reply _("who is this %{nick} you want me to transfer game ownership to?") % p
930 unless @games.key?(m.channel)
931 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
934 @games[m.channel].end_game(true)
938 @games.each { |k, g| g.end_game(true) }
942 def chan_reg(channel)
943 @registry.sub_registry(channel.downcase)
946 def chan_stats(channel)
947 stats = chan_reg(channel).sub_registry('stats')
960 def chan_pstats(channel)
961 pstats = chan_reg(channel).sub_registry('players')
962 pstats.set_default(UnoPlayerStats.new(0,0,[]))
966 def do_end_game(channel, closure)
967 reg = chan_reg(channel)
968 stats = chan_stats(channel)
970 stats['played_runtime'] += closure[:runtime]
972 stats['finished'] += 1
973 stats['finished_runtime'] += closure[:runtime]
975 pstats = chan_pstats(channel)
977 closure[:players].each do |pl|
984 closure[:dropouts].each do |pl|
992 winner = closure[:winner]
993 won = UnoGameWon.new(closure[:score], closure[:opponents])
994 k = winner.user.downcase
995 pls = pstats[k] # already marked played +1 above
1000 @bot.auth.irc_to_botuser(@games[channel].manager).reset_temp_permission('uno::manage', channel)
1001 @games.delete(channel)
1004 def do_chanstats(m, p)
1005 stats = chan_stats(m.channel)
1006 np = stats['played']
1007 nf = stats['finished']
1009 str = _("%{nf} %{uno} games completed over %{np} games played. ") % {
1010 :np => np, :uno => UnoGame::UNO, :nf => nf
1012 cgt = stats['finished_runtime']
1013 tgt = stats['played_runtime']
1014 str << _("%{cgt} game time for completed games") % {
1015 :cgt => Utils.secs_to_string(cgt)
1018 str << _(" on %{tgt} total game time. ") % {
1019 :tgt => Utils.secs_to_string(tgt)
1024 str << _("%{avg} average game time for completed games") % {
1025 :avg => Utils.secs_to_string(cgt/nf)
1027 str << _(", %{tavg} for all games") % {
1028 :tavg => Utils.secs_to_string(tgt/np)
1032 m.reply _("nobody has played %{uno} on %{chan} yet") % {
1033 :uno => UnoGame::UNO, :chan => m.channel
1039 dnick = p[:nick] || m.source # display-nick, don't later case
1040 nick = dnick.downcase
1041 ps = chan_pstats(m.channel)[nick]
1043 m.reply _("%{nick} never played %{uno} here") % {
1044 :uno => UnoGame::UNO, :nick => dnick
1051 score = ps.won.inject(0) { |sum, w| sum += w.score }
1052 str = _("%{nick} played %{np} %{uno} games here, ") % {
1053 :nick => dnick, :np => np, :uno => UnoGame::UNO
1055 str << _("forfeited %{nf} games, ") % { :nf => nf } if nf > 0
1056 str << _("won %{nw} games") % { :nw => nw}
1058 str << _(" with %{score} total points") % { :score => score }
1059 avg = ps.won.inject(0) { |sum, w| sum += w.score/w.opponents }/nw
1060 str << _(" and an average of %{avg} points per opponent") % { :avg => avg }
1065 def replace_player(m, p)
1066 unless @games.key?(m.channel)
1067 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1070 @games[m.channel].replace_player(p[:old], p[:new])
1073 def drop_player(m, p)
1074 unless @games.key?(m.channel)
1075 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1078 @games[m.channel].drop_player(p[:nick] || m.source.nick)
1081 def print_stock(m, p)
1082 unless @games.key?(m.channel)
1083 m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
1086 stock = @games[m.channel].stock
1087 m.reply(_("%{num} cards in stock: %{stock}") % {
1088 :num => stock.length,
1089 :stock => stock.join(' ')
1090 }, :split_at => /#{NormalText}\s*/)
1094 pstats = chan_pstats(m.channel)
1097 pstats.each do |k, v|
1098 wins << [v.won.length, k]
1099 scores << [v.won.inject(0) { |s, w| s+=w.score }, k]
1103 msg = _("%{uno} %{num} highest scores: ") % {
1104 :uno => UnoGame::UNO, :num => p[:scorenum]
1106 scores.sort! { |a1, a2| -(a1.first <=> a2.first) }
1107 scores = scores[0, n.to_i].compact
1108 if scores.length <= 5
1110 list = "\n" + scores.map { |a|
1112 _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} points") % {
1113 :i => i, :b => Bold, :nick => a.last, :score => a.first
1117 list = scores.map { |a|
1119 _("%{i}. %{nick} ( %{score} )") % {
1120 :i => i, :nick => a.last, :score => a.first
1124 elsif n = p[:winnum]
1125 msg = _("%{uno} %{num} most wins: ") % {
1126 :uno => UnoGame::UNO, :num => p[:winnum]
1128 wins.sort! { |a1, a2| -(a1.first <=> a2.first) }
1129 wins = wins[0, n.to_i].compact
1132 list = "\n" + wins.map { |a|
1134 _("%{i}. %{b}%{nick}%{b} with %{b}%{score}%{b} wins") % {
1135 :i => i, :b => Bold, :nick => a.last, :score => a.first
1139 list = wins.map { |a|
1141 _("%{i}. %{nick} ( %{score} )") % {
1142 :i => i, :nick => a.last, :score => a.first
1147 msg = _("uh, what kind of score list did you want, again?")
1148 list = _(" I can only show the top scores (with top) and the most wins (with topwin)")
1150 m.reply msg + list, :max_lines => (msg+list).count("\n")+1
1156 pg.map 'uno', :private => false, :action => :create_game
1157 pg.map 'uno end', :private => false, :action => :end_game, :auth_path => 'manage'
1158 pg.map 'uno drop', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1159 pg.map 'uno giveup', :private => false, :action => :drop_player, :auth_path => 'manage::drop::self!'
1160 pg.map 'uno drop :nick', :private => false, :action => :drop_player, :auth_path => 'manage::drop::other!'
1161 pg.map 'uno replace :old [with] :new', :private => false, :action => :replace_player, :auth_path => 'manage'
1162 pg.map 'uno transfer [game [ownership]] [to] :nick', :private => false, :action => :transfer_ownership, :auth_path => 'manage'
1163 pg.map 'uno stock', :private => false, :action => :print_stock
1164 pg.map 'uno chanstats', :private => false, :action => :do_chanstats
1165 pg.map 'uno stats [:nick]', :private => false, :action => :do_pstats
1166 pg.map 'uno top :scorenum', :private => false, :action => :do_top, :defaults => { :scorenum => 5 }
1167 pg.map 'uno topwin :winnum', :private => false, :action => :do_top, :defaults => { :winnum => 5 }
1169 pg.default_auth('stock', false)
1170 pg.default_auth('manage', false)
1171 pg.default_auth('manage::drop::self', true)