在ruby中使用.slice和.shift

时间:2017-01-21 04:00:23

标签: ruby multidimensional-array slice

我试图让这款纸牌游戏继续进行。它应该允许用户设置玩家的数量并向每个玩家分发两张牌。

我把牌组切成了卡片对,所以

@deck = [["2","hearts"], ["A","spades"]],
        [["J", "clubs"], ["K","hearts"]]

我试图通过在牌组中弹出第一对牌来分发下一对牌,然后像用户一样重复我的时间。我认为它非常接近工作 - 我很感激任何帮助。

    @cards=["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]*4
    @suits = ["hearts", "spades", "clubs", "diamonds"]*13
    @deck = []

    puts "how many players are there?"
    number_of_players = gets.chomp.to_i


    @deck << [@cards,@suits].transpose.shuffle.each_slice(2)

      1.upto(number_of_players) do |n|
        @deck.shift
        puts "player #{n} cards are: #{@deck}"

      end

1 个答案:

答案 0 :(得分:1)

@deck = [@cards,@suits].transpose.shuffle.each_slice(2).to_a
@initial = @deck.shift(number_of_players)

@initial.each.with_index(1) do |cards, n|
  puts "player #{n} cards are: #{cards}"
end

#⇒ player 1 cards are: [["5", "diamonds"], ["7", "spades"]]
#  player 2 cards are: [["7", "clubs"], ["10", "hearts"]]
#  player 3 cards are: [["9", "spades"], ["Queen", "spades"]]

puts "Left pairs in the deck: #{@deck.count}"
#⇒ 23 # for 3 players, it’s 26 - number_of_players