【问题标题】:Ruby: War card game, dealing cards to playersRuby:战争纸牌游戏,向玩家发牌
【发布时间】:2014-03-09 04:37:09
【问题描述】:

所以我没有要求任何人为我解决这个问题,但我确实需要一些帮助。我对面向对象编程很陌生,但它开始对我有意义。以下是迄今为止我为战争纸牌游戏所拥有的代码。目前我并不关心套装,尽管我知道如果需要的话如何添加它们。基本上,我的下一步是弄清楚如何向每个玩家发 26 张牌。

这段代码现在所做的是使用 Fisher-Yates 算法对牌组进行洗牌,并输出一个包含现在洗牌的牌组的字符串。我认为这会返回一个数组,因为我使用的是“to_a”方法,但我不认为是这样。

然后我如何将这套牌发给每个玩家?我需要牌桌或球员的班级吗?任何朝着正确方向的帮助都会很棒。再次,请不要为我解决它。我想尽可能地为自己解决这个问题。 编辑:使用 1.9.3,如果有用的话。

class Card
    VALUE = %w(2 3 4 5 6 7 8 9 10 J Q K A)

    attr_accessor :rank

    def initialize(id)
        self.rank = VALUE[id % 13]
    end
end

class Deck 
    attr_accessor :cards
    def initialize
        self.cards = (0..51).to_a.shuffle.collect { |id| Card.new(id) }
    end
end

class Array
    def shuffle!
        each_index do |i|
            r = rand(length-i) + i
            self[r], self[i] = self[i], self[r]
        end
    end

    def shuffle
        dup.shuffle!
    end
end


d = Deck.new
d.cards.each do |card|
    print "#{card.rank} "
end

【问题讨论】:

    标签: ruby war


    【解决方案1】:

    有很多方法可以做到这一点。我没有解决它,但开始了一些可以添加到结构游戏中的基本课程。我会在你的 Deck 类中添加一个方法,从牌组中取出一张牌。 'Player' 类也可以用来代表每个玩家。每个玩家对象都有一个持有牌的手属性:

    class Deck
      def remove_card
        self.cards.pop    # removes a card from end of array
      end
    
      def empty?
        self.cards.count == 0
      end
    end
    
    d = Deck.new
    d.cards.count      #=> 52 cards
    p = Player.new
    p.hand << d.remove_card
    d.cards.count      #=> 51 cards now that one has been removed
    

    你的牌组将卡片排列成一个数组。您的输出是一个字符串,因为您让它打印出排名,但 card 属性确实是一个包含卡片对象的数组。您还可以拥有一个处理游戏的 Game 类:

    class Game
      def initialize(player1, player2)
        @player1 = player1
        @player2 = player2
      end
    
      def play_poker
        @deck = Deck.new
        # give each player five cards
        1.upto(5) do |num|
          @player1.hand << @deck.remove_card
          @player2.hand << @deck.remove_card
        end
    
        # each player has a five card hand at this point
        # omitted code, have a method to score the two hands and determine the winner
      end
    
      def play_war
        # omitted code, have players issued cards
        # omitted, instructions, game play code
      end
    end
    

    所以你可以让游戏玩不同的游戏。评分和输出是您需要添加的其他方法。我还省略了 Player 类供您执行。但是你可以这样玩游戏:

    p1 = Player.new
    p2 = Player.new
    game = Game.new(p1, p2)
    game.play_poker         #=> output could be text like: Player 1's hand: A, 4, 4, 2, Q, Player 2's hand:...... etc
                            #=> winner is Player 1!
    

    可以通过游戏类中的方法进行评分。它还会像上面一样输出文本,打印每个玩家拿到的手牌以及谁赢了。如果使用相同的游戏对象进行许多游戏,您必须确保玩家​​的手被清理干净,使用新的牌组(或进行重新洗牌方法)等等。

    如果你真的想要两个人一起玩,你会用按钮来控制每一步。 H 击中或 s 停留等等。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2023-04-04
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多