2013-12-20 275 views
0

我的問題是,chips未保存爲傳遞參數的全局變量。我通過$h1c(這是總籌碼玩家的第一手牌數)。因此,如果他贏或輸,chips應該被設置爲等於chips+-betamount紅寶石不保存/存儲值

問題是它沒有被保存爲全局變量。如果我寫$h1c = 150_000,那麼它會等於這個。如果稍後我寫$h1c = 150_000 + 50_000,那麼200_000將是$ h1c的新值。

由於某些原因,當我聲明chips = chips + betamount時,這與您說的$h1c = $h1c + $h1bet相同,不起作用。

def review(hand, chips, betamount) 
    abc = valueofcards(hand) #player's hand value 
    klm = valueofcards($handD) #dealer's hand value 
    if abc == klm and abc < 19 
     puts "You tied" 
     chips = chips 
    elsif abc > 18 
     puts "You lost" 
     chips = chips - betamount 
    elsif abc < 19 and klm > 18 
     puts "You won" 
     chips = chips + betamount 
    elsif abc < 19 and abc > klm 
     puts "You won" 
     chips = chips + betamount 
    elsif abc < 19 and klm < 19 and klm > abc 
     puts "You lost" 
     chips = chips - betamount 
    end 
end 

這是在我傳遞參數評論:

def pre_review(num) 
    puts "Recap of that round" 
    puts "First Hand:" 
    review($hand1, $h1c, $h1bet) 
    muckcards(num) 
end 

如果需要的話,這裏是鏈接到全碼/遊戲,測試問題出來了http://labs.codecademy.com/Bmvl#:workspace注:我目前只是試圖讓這部分工作爲$ hand1,所以你會選擇1來玩這個問題的手數。

+0

Ruby 1.8.7已經退役。可能是升級的時間... https://www.ruby-lang.org/zh/news/2013/06/30/we-retire-1-8-7/ –

回答

1

這不一樣。以$爲前綴的變量是全局變量,而前綴變量是局部變量。因此,當您更改$h1c的值時,您正在更改您在程序中其他地方引用的相同$h1c變量的值。但是,如果更改chips的值,則只會在review方法的上下文內更改chips的值。只要該方法返回,chips的值就會丟失。

因此,最簡單的解決方案是,即使將參數傳遞給該方法,也不必費心直接讀取全局變量的值。儘管在風格上這可能不是最好的解決方案。事實上,通常全局變量的使用被認爲是不好的做法。

另一個解決辦法是從複習方法返回播放器的芯片的新的價值,就像這樣:

def review(hand, chips, betamount) 
    abc = valueofcards(hand) #player's hand value 
    klm = valueofcards($handD) #dealer's hand value 
    if abc == klm and abc < 19 
     puts "You tied" 
     chips = chips 
    elsif abc > 18 
     puts "You lost" 
     chips = chips - betamount 
    elsif abc < 19 and klm > 18 
     puts "You won" 
     chips = chips + betamount 
    elsif abc < 19 and abc > klm 
     puts "You won" 
     chips = chips + betamount 
    elsif abc < 19 and klm < 19 and klm > abc 
     puts "You lost" 
     chips = chips - betamount 
    end 
    return chips # See here 
end 

然後,從法外設置的玩家籌碼的價值

根據代碼質量和編程風格,修復該程序可能還有很多工作要做,但我現在還不能接受。保持學習! ;-)

1

Ruby是一種傳值語言,不通過引用。因此,您不能重新分配傳遞給該方法內的方法的變量的值。查看關於evaluation strategy的維基百科文章,瞭解變量傳遞的不同方法。

Ruby是傳遞值的事實有點複雜b/c Ruby實際上是通過值傳遞對象的引用。因此,您可以修改方法內的哈希內容,並將這些更改反映到外部變量中。 Java也通過價值傳遞引用,我一直很喜歡this,你可能會發現它很有用。

1

當你這樣做:

review($hand1, $h1c, $h1bet) 

這並不全局變量$h1c本身傳遞給方法,它傳遞(一個參考)其

review方法中,傳遞的值被賦予名稱chips,該名稱在該方法中是本地的。當您分配到chips時,您只需更新名稱chips以引用不同的值。

要獲得您想要的行爲,您需要直接將其分配給$h1c而不是chips。 (或者,更好的編程習慣,您可以從方法中返回值chips而不是使用全局變量。)