2013-11-24 117 views
0

我正在建造一個命令行紅寶石二十一點遊戲使用的方法。我已經到了玩家可以擊中或堅持的地步(在被交易2張牌之後)。現在我似乎無法跳出邏輯思考如何限制我的球員只有四個命中。 make紅寶石二十一點和循環

這告訴我,我的問題在循環 - 那就是我正以錯誤的方式接近程序的循環部分。

這是到目前爲止我的代碼:

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:雖然我理解循環的工作方式,但我知道如何以及何時實施它們......所以任何反饋都將非常感激。謝謝!

回答

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