我试图在阵列中一次抓取两个子阵列 - 关于如何做到这一点的任何想法?
示例:
deck = [[2,spades],[3,hearts],[6,diamonds],[10,clubs],[8,hearts],[9,clubs]]
有没有办法一次抓住两张牌,所以索引每次都会增加,然后从[0..1]再到[1..0],依此类推,抓住两张牌时间。
我想说:
玩家1卡:[2,spades],[3,hearts]
玩家2卡:[6,diamonds],[10,clubs]
答案 0 :(得分:3)
我的建议只是将deck数组传递给方法并返回一个带[player1,player2,deck]的数组。如果你只是从牌组的“顶部”绘制,你可以使用shift
从阵列中取出第一个元素。
deck = [[2,"spades"],[3,"hearts"],[6,"diamonds"],[10,"clubs"],[8,"hearts"],[9,"clubs"]]
def drawTwo(arr)
if arr.count >= 4
player_one = [deck.shift, deck.shift]
player_two = [deck.shift, deck.shift]
return [player_one, player_two, deck]
else
return "Not enough cards in deck, please provide a new deck"
end
end
round = drawTwo(deck)
player_one = round[0]
player_two = round[1]
deck = round[2]
puts "Player one: #{player_one}"
puts "Player two: #{player_two}"
puts "Deck: #{deck}"
我试着非常详细,并没有对这段代码进行过多的混淆,所以它应该读起来非常明确。
你可以通过这样重写它来缩短它,我只是想让它变得可以理解发生的事情:
deck = [[2,"spades"],[3,"hearts"],[6,"diamonds"],[10,"clubs"],[8,"hearts"],[9,"clubs"]]
def drawTwo(arr)
arr.count >= 4 ? [[arr.shift, arr.shift], [arr.shift, arr.shift]] : raise "Not enough cards..."
end
player_one, player_two = drawTwo(deck)
puts "Player one: #{player_one}"
puts "Player two: #{player_two}"
puts "Deck: #{deck}"
首次生成套牌时,请务必添加deck.shuffle
。
另外,我不知道你用什么来制作套牌,但是因为我玩得很开心:
def newShuffledDeck
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
suits = ["hearts", "spades", "clubs", "diamonds"]
deck = ranks.product(suits)
deck.shuffle
end
答案 1 :(得分:2)
试试这个
hands = array.each_slice(hand_size).take(player_count)
hands.each_with_index do |hand, n|
puts "player #{n + 1} cards are: #{hand}"
end
这是如何运作的?
each_slice(n)
将数组切割成长度为n
take(n)
获取第一个n
件答案 2 :(得分:0)
deck = [[2,"spades"],[3,"hearts"],[6,"diamonds"],[10,"clubs"],[8,"hearts"],[9,"clubs"]]
deck.each_slice(2) do |el|
puts el
end