]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/games/uno.rb
f1573dc723f230ab368a426b4f759d3e9a1f8531
[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   attr_reader :stock
151   attr_reader :discard
152   attr_reader :channel
153   attr :players
154   attr_reader :player_has_picked
155   attr_reader :picker
156
157   def initialize(plugin, channel)
158     @channel = channel
159     @plugin = plugin
160     @bot = plugin.bot
161     @players = []
162     @dropouts = []
163     @discard = nil
164     @value = nil
165     @color = nil
166     make_base_stock
167     @stock = []
168     make_stock
169     @start_time = nil
170     @join_timer = nil
171     @picker = 0
172     @last_picker = 0
173   end
174
175   def get_player(user)
176     @players.each { |p| return p if p.user == user }
177     return nil
178   end
179
180   def announce(msg, opts={})
181     @bot.say channel, msg, opts
182   end
183
184   def notify(player, msg, opts={})
185     @bot.notice player.user, msg, opts
186   end
187
188   def make_base_stock
189     @base_stock = COLORS.inject([]) do |list, clr|
190       VALUES.each do |n|
191         list << Card.new(clr, n)
192         list << Card.new(clr, n) unless n == 0
193       end
194       list
195     end
196     4.times do
197       @base_stock << Wild.new
198       @base_stock << Wild.new('+4')
199     end
200   end
201
202   def make_stock
203     @stock.replace @base_stock
204     # remove the cards in the players hand
205     @players.each { |p| p.cards.each { |c| @stock.delete_one c } }
206     # remove current top discarded card if present
207     if @discard
208       @stock.delete_one(discard)
209     end
210     @stock.shuffle!
211   end
212
213   def start_game
214     debug "Starting game"
215     @players.shuffle!
216     show_order
217     announce _("%{p} deals the first card from the stock") % {
218       :p => @players.first
219     }
220     card = @stock.shift
221     @picker = 0
222     @special = false
223     while Wild === card do
224       @stock.insert(rand(@stock.length), card)
225       card = @stock.shift
226     end
227     set_discard(card)
228     show_discard
229     if @special
230       do_special
231     end
232     next_turn
233     @start_time = Time.now
234   end
235
236   def elapsed_time
237     if @start_time
238       Utils.secs_to_string(Time.now-@start_time)
239     else
240       _("no time")
241     end
242   end
243
244   def reverse_turn
245     if @players.length > 2
246       @players.reverse!
247       # put the current player back in its place
248       @players.unshift @players.pop
249       announce _("Playing order was reversed!")
250     else
251       skip_turn
252     end
253   end
254
255   def skip_turn
256     @players << @players.shift
257     announce _("%{p} skips a turn!") % {
258       # this is first and not last because the actual
259       # turn change will be done by the following next_turn
260       :p => @players.first
261     }
262   end
263
264   def do_special
265     case @discard.value
266     when 'Reverse'
267       reverse_turn
268       @special = false
269     when 'Skip'
270       skip_turn
271       @special = false
272     end
273   end
274
275   def set_discard(card)
276     @discard = card
277     @value = card.value.dup rescue card.value
278     if Wild === card
279       @color = nil
280     else
281       @color = card.color.dup
282     end
283     if card.picker > 0
284       @picker += card.picker
285       @last_picker = @discard.picker
286     end
287     if card.special?
288       @special = true
289     else
290       @special = false
291     end
292   end
293
294   def next_turn(opts={})
295     @players << @players.shift
296     @player_has_picked = false
297     show_turn
298   end
299
300   def can_play(card)
301     # When a +something is online, you can only play
302     # a +something of same or higher something, or a Reverse of
303     # the correct color
304     # TODO make optional
305     if @picker > 0
306       if (card.value == 'Reverse' and card.color == @color) or card.picker >= @last_picker
307         return true
308       else
309         return false
310       end
311     else
312       # You can always play a Wild
313       # FIXME W+4 can only be played if you don't have a proper card
314       # TODO make it playable anyway, and allow players to challenge
315       return true if Wild === card
316       # On a Wild, you must match the color
317       if Wild === @discard
318         return card.color == @color
319       else
320         # Otherwise, you can match either the value or the color
321         return (card.value == @value) || (card.color == @color)
322       end
323     end
324   end
325
326   def play_card(source, cards)
327     debug "Playing card #{cards}"
328     p = get_player(source)
329     shorts = cards.gsub(/\s+/,'').match(/^(?:([rbgy]\d){1,2}|([rbgy](?:\+\d|[rs]))|(w(?:\+4)?)([rbgy])?)$/).to_a
330     debug shorts.inspect
331     if shorts.empty?
332       announce _("what cards were that again?")
333       return
334     end
335     full = shorts[0]
336     short = shorts[1] || shorts[2] || shorts[3]
337     jolly = shorts[3]
338     jcolor = shorts[4]
339     if jolly
340       toplay = 1
341     else
342       toplay = (full == short) ? 1 : 2
343     end
344     debug [full, short, jolly, jcolor, toplay].inspect
345     # r7r7 -> r7r7, r7, nil, nil
346     # r7 -> r7, r7, nil, nil
347     # w -> w, nil, w, nil
348     # wg -> wg, nil, w, g
349     if cards = p.has_card?(short)
350       debug cards
351       unless can_play(cards.first)
352         announce _("you can't play that card")
353         return
354       end
355       if cards.length >= toplay
356         set_discard(p.cards.delete_one(cards.shift))
357         if toplay > 1
358           set_discard(p.cards.delete_one(cards.shift))
359           announce _("%{p} plays %{card} twice!") % {
360             :p => p,
361             :card => @discard
362           }
363         else
364           announce _("%{p} plays %{card}") % { :p => p, :card => @discard }
365         end
366         if p.cards.length == 1
367           announce _("%{p} has %{uno}!") % {
368             :p => p, :uno => UNO
369           }
370         elsif p.cards.length == 0
371           end_game
372           return
373         end
374         show_picker
375         if @color
376           if @special
377             do_special
378           end
379           next_turn
380         elsif jcolor
381           choose_color(p.user, jcolor)
382         else
383           announce _("%{p}, choose a color with: co r|b|g|y") % { :p => p }
384         end
385       else
386         announce _("you don't have two cards of that kind")
387       end
388     else
389       announce _("you don't have that card")
390     end
391   end
392
393   def pass(user)
394     p = get_player(user)
395     if @picker > 0
396       announce _("%{p} passes turn, and has to pick %{b}%{n}%{b} cards!") % {
397         :p => p, :b => Bold, :n => @picker
398       }
399       deal(p, @picker)
400       @picker = 0
401     else
402       if @player_has_picked
403         announce _("%{p} passes turn") % { :p => p }
404       else
405         announce _("you need to pick a card first")
406         return
407       end
408     end
409     next_turn
410   end
411
412   def choose_color(user, color)
413     case color
414     when 'r'
415       @color = 'Red'
416     when 'b'
417       @color = 'Blue'
418     when 'g'
419       @color = 'Green'
420     when 'y'
421       @color = 'Yellow'
422     else
423       announce _('what color is that?')
424       return
425     end
426     announce _('color is now %{c}') % {
427       :c => UnoGame.irc_color_bg(@color)+" #{@color} "
428     }
429     next_turn
430   end
431
432   def show_time
433     if @start_time
434       announce _("This %{uno} game has been going on for %{time}") % {
435         :uno => UNO,
436         :time => elapsed_time
437       }
438     else
439       announce _("The game hasn't started yet")
440     end
441   end
442
443   def show_order
444     announce _("%{uno} playing turn: %{players}") % {
445       :uno => UNO, :players => players.join(' ')
446     }
447   end
448
449   def show_turn(opts={})
450     cards = true
451     cards = opts[:cards] if opts.key?(:cards)
452     player = @players.first
453     announce _("it's %{player}'s turn") % { :player => player }
454     show_user_cards(player) if cards
455   end
456
457   def has_turn?(source)
458     @players.first.user == source
459   end
460
461   def show_picker
462     if @picker > 0
463       announce _("next player must respond correctly or pick %{b}%{n}%{b} cards") % {
464         :b => Bold, :n => @picker
465       }
466     end
467   end
468
469   def show_discard
470     announce _("Current discard: %{card} %{c}") % { :card => @discard,
471       :c => (Wild === @discard) ? UnoGame.irc_color_bg(@color) + " #{@color} " : nil
472     }
473     show_picker
474   end
475
476   def show_user_cards(player)
477     p = Player === player ? player : get_player(player)
478     notify p, _('Your cards: %{cards}') % {
479       :cards => p.cards.join(' ')
480     }
481   end
482
483   def show_all_cards(u=nil)
484     announce(@players.inject([]) { |list, p|
485       list << [p, p.cards.length].join(': ')
486     }.join(', '))
487     if u
488       show_user_cards(u)
489     end
490   end
491
492   def pick_card(user)
493     p = get_player(user)
494     announce _("%{player} picks a card") % { :player => p }
495     deal(p, 1)
496     @player_has_picked = true
497   end
498
499   def deal(player, num=1)
500     picked = []
501     num.times do
502       picked << @stock.delete_one
503       if @stock.length == 0
504         announce _("Shuffling discarded cards")
505         make_stock
506         if @stock.length == 0
507           announce _("No more cards!")
508           end_game # FIXME nope!
509         end
510       end
511     end
512     picked.sort!
513     notify player, _("You picked %{picked}") % { :picked => picked.join(' ') }
514     player.cards += picked
515     player.cards.sort!
516   end
517
518   def add_player(user)
519     if p = get_player(user)
520       announce _("you're already in the game, %{p}") % {
521         :p => p
522       }
523       return
524     end
525     @dropouts.each do |dp|
526       if dp.user == user
527         announce _("you dropped from the game, %{p}, you can't get back in") % {
528           :p => dp
529         }
530         return
531       end
532     end
533     cards = 7
534     if @start_time
535       cards = @players.inject(0) do |s, pl|
536         s +=pl.cards.length
537       end/@players.length
538     end
539     p = Player.new(user)
540     @players << p
541     announce _("%{p} joins this game of %{uno}") % {
542       :p => p, :uno => UNO
543     }
544     deal(p, cards)
545     return if @start_time
546     if @join_timer
547       @bot.timer.reschedule(@join_timer, 10)
548     elsif @players.length > 1
549       announce _("game will start in 20 seconds")
550       @join_timer = @bot.timer.add_once(20) {
551         start_game
552       }
553     end
554   end
555
556   def drop_player(user)
557     unless p = get_player(user)
558       announce _("%{p} isn't playing %{uno}") % {
559         :p => p, :uno => UNO
560       }
561       return
562     end
563     announce _("%{p} gives up this game of %{uno}") % {
564       :p => p, :uno => UNO
565     }
566     case @players.length
567     when 2
568       if p == @players.first
569         next_turn
570       end
571       end_game
572       return
573     when 1
574       end_game(true)
575       return
576     end
577     debug @stock.length
578     while p.cards.length > 0
579       @stock.insert(rand(@stock.length), p.cards.shift)
580     end
581     debug @stock.length
582     @dropouts << @players.delete_one(p)
583   end
584
585   def replace_player(old, new)
586     # The new user
587     user = channel.get_user(new)
588     if p = get_player(user)
589       announce _("%{p} is already playing %{uno} here") % {
590         :p => p, :uno => UNO
591       }
592       return
593     end
594     # We scan the player list of the player with the old nick, instead
595     # of using get_player, in case of IRC drops etc
596     @players.each do |p|
597       if p.user.nick == old
598         p.user = user
599         announce _("%{p} takes %{b}%{old}%{b}'s place at %{uno}") % {
600           :p => p, :b => Bold, :old => old, :uno => UNO
601         }
602         return
603       end
604     end
605     announce _("%{b}%{old}%{b} isn't playing %{uno} here") % {
606       :uno => UNO, :b => Bold, :old => old
607     }
608   end
609
610   def end_game(halted = false)
611     if halted
612       if @start_time
613         announce _("%{uno} game halted after %{time}") % {
614           :time => elapsed_time,
615           :uno => UNO
616         }
617       else
618         announce _("%{uno} game halted before it could start") % {
619           :uno => UNO
620         }
621       end
622     else
623       announce _("%{uno} game finished after %{time}! The winner is %{p}") % {
624         :time => elapsed_time,
625         :uno => UNO, :p => @players.first
626       }
627     end
628     if @picker > 0 and not halted
629       p = @players[1]
630       announce _("%{p} has to pick %{b}%{n}%{b} cards!") % {
631         :p => p, :n => @picker, :b => Bold
632       }
633       deal(p, @picker)
634       @picker = 0
635     end
636     score = @players.inject(0) do |sum, p|
637       if p.cards.length > 0
638         announce _("%{p} still had %{cards}") % {
639           :p => p, :cards => p.cards.join(' ')
640         }
641         sum += p.cards.inject(0) do |cs, c|
642           cs += c.score
643         end
644       end
645       sum
646     end
647     if not halted
648       announce _("%{p} wins with %{b}%{score}%{b} points!") % {
649         :p => @players.first, :score => score, :b => Bold
650       }
651     end
652     @plugin.do_end_game(@channel)
653   end
654
655 end
656
657 class UnoPlugin < Plugin
658   attr :games
659   def initialize
660     super
661     @games = {}
662   end
663
664   def help(plugin, topic="")
665     case topic
666     when 'commands'
667       [
668       _("'jo' to join in"),
669       _("'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"),
670       _("'pe' to pick a card"),
671       _("'pa' to pass your turn"),
672       _("'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)"),
673       _("'ca' to show current cards"),
674       _("'cd' to show the current discard"),
675       _("'od' to show the playing order"),
676       _("'ti' to show play time"),
677       _("'tu' to show whose turn it is")
678     ].join(" ; ")
679     when 'rules'
680       _("play all your cards, one at a time, by matching either the color or the value of the currently discarded card. ") +
681       _("cards with special effects: Skip (next player skips a turn), Reverse (reverses the playing order), +2 (next player has to take 2 cards). ") +
682       _("Wilds can be played on any card, and you must specify the color for the next card. ") +
683       _("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. ") +
684       _("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. ") +
685       _("you can also play a Reverse on a +2 or +4, bouncing the effect back to the previous player (that now comes next). ")
686     else
687       (_("%{uno} game. !uno to start a game. see help uno rules for the rules. commands: %{cmds}") % {
688         :uno => UnoGame::UNO,
689         :cmds => help(plugin, 'commands')
690       })
691     end
692   end
693
694   def message(m)
695     return unless @games.key?(m.channel)
696     g = @games[m.channel]
697     case m.plugin.intern
698     when :jo # join game
699       return if m.params
700       g.add_player(m.source)
701     when :pe # pick card
702       return if m.params
703       if g.has_turn?(m.source)
704         if g.player_has_picked
705           m.reply _("you already picked a card")
706         elsif g.picker > 0
707           g.pass(m.source)
708         else
709           g.pick_card(m.source)
710         end
711       else
712         m.reply _("It's not your turn")
713       end
714     when :pa # pass turn
715       return if m.params
716       if g.has_turn?(m.source)
717         g.pass(m.source)
718       else
719         m.reply _("It's not your turn")
720       end
721     when :pl # play card
722       if g.has_turn?(m.source)
723         g.play_card(m.source, m.params.downcase)
724       else
725         m.reply _("It's not your turn")
726       end
727     when :co # pick color
728       if g.has_turn?(m.source)
729         g.choose_color(m.source, m.params.downcase)
730       else
731         m.reply _("It's not your turn")
732       end
733     when :ca # show current cards
734       return if m.params
735       g.show_all_cards(m.source)
736     when :cd # show current discard
737       return if m.params
738       g.show_discard
739     # TODO
740     # when :ch
741     #   g.challenge
742     when :od # show playing order
743       return if m.params
744       g.show_order
745     when :ti # show play time
746       return if m.params
747       g.show_time
748     when :tu # show whose turn is it
749       return if m.params
750       if g.has_turn?(m.source)
751         m.nickreply _("it's your turn, sleepyhead")
752       else
753         g.show_turn(:cards => false)
754       end
755     end
756   end
757
758   def create_game(m, p)
759     if @games.key?(m.channel)
760       m.reply _("There is already an %{uno} game running here, say 'jo' to join in") % { :uno => UnoGame::UNO }
761       return
762     end
763     @games[m.channel] = UnoGame.new(self, m.channel)
764     m.reply _("Ok, created %{uno} game on %{channel}, say 'jo' to join in") % {
765       :uno => UnoGame::UNO,
766       :channel => m.channel
767     }
768   end
769
770   def end_game(m, p)
771     unless @games.key?(m.channel)
772       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
773       return
774     end
775     @games[m.channel].end_game(true)
776   end
777
778   def do_end_game(channel)
779     @games.delete(channel)
780   end
781
782   def replace_player(m, p)
783     unless @games.key?(m.channel)
784       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
785       return
786     end
787     @games[m.channel].replace_player(p[:old], p[:new])
788   end
789
790   def drop_player(m, p)
791     unless @games.key?(m.channel)
792       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
793       return
794     end
795     who = p[:nick] ? m.channel.get_user(p[:nick]) : m.source
796     @games[m.channel].drop_player(who)
797   end
798
799   def print_stock(m, p)
800     unless @games.key?(m.channel)
801       m.reply _("There is no %{uno} game running here") % { :uno => UnoGame::UNO }
802       return
803     end
804     stock = @games[m.channel].stock
805     m.reply(_("%{num} cards in stock: %{stock}") % {
806       :num => stock.length,
807       :stock => stock.join(' ')
808     }, :split_at => /#{NormalText}\s*/)
809   end
810 end
811
812 pg = UnoPlugin.new
813
814 pg.map 'uno', :private => false, :action => :create_game
815 pg.map 'uno end', :private => false, :action => :end_game
816 pg.map 'uno drop', :private => false, :action => :drop_player
817 pg.map 'uno giveup', :private => false, :action => :drop_player
818 pg.map 'uno drop :nick', :private => false, :action => :drop_player, :auth_path => ':other'
819 pg.map 'uno replace :old [with] :new', :private => false, :action => :replace_player
820 pg.map 'uno stock', :private => false, :action => :print_stock
821
822 pg.default_auth('stock', false)
823 pg.default_auth('end', false)
824 pg.default_auth('drop::other', false)
825 pg.default_auth('replace', false)