当前位置:  开发笔记 > 后端 > 正文

使用puts显示值

如何解决《使用puts显示值》经验,为你挑选了1个好方法。

我正在尝试编写一个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

我很感激任何帮助.



1> ndnenkov..:

问题是(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

推荐阅读
贴进你的心聆听你的世界
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有