我正在使用方法构建命令行ruby二十一点游戏。我已经达到了玩家可以击中或坚持的程度(在获得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:虽然我理解循环是如何工作的但我知道如何以及何时实施它们正在进行争论......所以任何反馈都会非常感激。谢谢!
答案 0 :(得分:2)
你在寻找类似的东西吗?
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