【问题标题】:Ruby Blackjack and loops红宝石二十一点和循环
【发布时间】:2013-12-08 20:48:27
【问题描述】:

我正在使用方法构建一个命令行 ruby​​ blackjack 游戏。我已经到了玩家可以击打或坚持的地步(在发了 2 张牌之后)。现在我似乎无法跳到逻辑上思考如何将我的球员限制在只有四次命中。制作

这告诉我我的问题是循环的——也就是说我以错误的方式接近程序的循环部分。

到目前为止,这是我的代码:

def blackjack
  promt
end

def promt
  puts "Welcome! Would you like to play a game of blackjack? Enter Yes or No"
  play = gets.chomp.downcase
  if play == "yes"
    game_plan
  elsif play =="no"
    puts "That's too bad. Come back when you feel like playing"
  else
    puts "Sorry but I don't understand your respones. Please type and enter yes to play Or no to to quit"
    blackjack
  end
end

def game_plan
  wants_to_play = true
  hand = []
  total = first_move(hand)
  wants_to_play = hit_me(hand)
  if wants_to_play == true
    hit_me(hand)
  end
end

def first_move(hand)
  deal(hand)
  deal(hand)
  total(hand) 
end

def deal(hand)
  card = rand(12)
  puts "You have been dealt a card with a value of #{card}"
  hand << card
end

def total(hand)
  total = 0
  hand.each do |count|
    total += count
  end
  puts "The sum of the cards you have been dealt is #{total}"
  total
end

def hit_me(hand)
  puts "Would you like to hit or stick?"
  yay_or_nah = gets.chomp.downcase
  if yay_or_nah == "stick" && total(hand) < 21
    puts "Sorry! The sum of the cards you have been dealt is less than 21. You lost this round!"
  else
    deal(hand)
    total(hand)
    playing = true
  end  
end

blackjack

我想要做的是将我的玩家限制为 2 次击球(在最初的第一次击球之后,这会产生 2 张牌)。我知道这是一个非常烦人的新手问题,但我真的很感激任何可以帮助我以正确方式思考解决方案的反馈。

PS:虽然我了解循环是如何工作的,但我正在努力了解如何以及何时实施它们......所以任何反馈都将非常感激。谢谢!

【问题讨论】:

    标签: ruby loops methods logic blackjack


    【解决方案1】:

    您是否正在寻找类似的东西?

    MAX_HITS = 2
    hits = 0
    loop do
      break if hits > MAX_HITS
      puts "Would you like to hit or stick?"
      …
      else
        hits += 1
        …
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多