我正在尝试编写一个Ruby程序来向一个玩家发放两张牌。这是我的代码:
def get_card (card)
suit = (card - 1)/13
if (card == 0)
type = " of clubs"
elsif (card == 1)
type = " of diamonds"
elsif (card == 2)
type = " of hearts"
elsif (card == 3)
type = " of spades"
end
(card) % 13
if (card == 1)
return "ace" + type
elsif (card == 11)
return "jack" + type
elsif (card == 0)
return "king" + type
elsif (card == 2)
return "2" + type
elsif (card == 3)
return "3" + type
elsif (card == 4)
return "4" + type
elsif (card == 5)
return "5" + type
elsif (card == 6)
return "6" + type
elsif (card == 7)
return "7" + type
elsif (card == 8)
return "8" + type
elsif (card == 9)
return "9" + type
elsif (card == 10)
return "10" + type
elsif (card == 12)
return "queen" + type
end
end
def deal_cards
total_cards = (1..52).to_a.shuffle
player_value = [total_cards.pop, total_cards.pop]
puts "Your cards are " + get_card(player_value[0]).to_s + " and " + get_card(player_value[1]).to_s
end
deal_cards();
部分:
puts "Your cards are " + get_card(player_value[0]).to_s + " and " + get_card(player_value[1]).to_s
未显示
的值get_card(player_value[0]).to_s
或
get_card(player_value[1]).to_s
我很感激任何帮助。
答案 0 :(得分:6)
问题是(card) % 13
不会改变card
。你可能想要的是:
card %= 13
<小时/> 但请注意,您的抽象有点令人困惑,并且您有很多重复。为什么不尝试这样的事情:
suits = [:clubs, :diamonds, :hearts, :spades]
values = [*2..10, :jack, :queen, :king, :ace]
deck = suits.product(values).shuffle.map do |suite, value|
{suite: suite, value: value}
end
player_cards = deck.pop(2)
puts "Your cards are #{player_cards.first[:value]} of #{player_cards.first[:suite]} and #{player_cards.last[:value]} of #{player_cards.last[:suite]}"
# => Your cards are jack of spades and 7 of clubs
答案 1 :(得分:0)
尝试:
def get_card (card)
type = case ((card-1)/13)
when 0 then "of clubs"
when 1 then "of diamonds"
when 2 then "of hearts"
when 3 then "of spades"
end
card = case (card%13)
when 0 then "king #{type}"
when 1 then "ace #{type}"
when 11 then "jack #{type}"
when 12 then "queen #{type}"
else card%13
end
"#{card} #{type}"
end
def deal_cards
total_cards = (1..52).to_a.shuffle
player_value = [total_cards.pop, total_cards.pop]
puts "Your cards are #{get_card(player_value[0]).to_s} and #{get_card(player_value[1]).to_s}"
end
deal_cards()