簡體   English   中英

如何跟蹤Python中的分數增量?

[英]How do I keep track of score increments in Python?

我正在用Python編寫一個簡單的游戲程序,系統會提示用戶從雜貨店的“健康”和“不健康”項目中進行選擇。 每次用戶選擇健康項目時,其“健康得分(最初為100)都會上升。每次從不健康項目中進行選擇時,其得分都會下降。

我的代碼從初始健康評分100中減去,但在每次選擇后都無法跟蹤最新評分。 我想在每次交易后為用戶提供新的總計(new_hscore),並在結束時給用戶總計(final_score),但是我不確定該怎么做。

用列表完成嗎? 我是否使用.append? 任何幫助將不勝感激! 提前致謝!

這是我的代碼: http : //pastebin.com/TvyURsMb

向下滾動到“ def inner():”函數時,您可以立即看到我正在嘗試執行的操作。

編輯:我得到它的工作! 謝謝所有貢獻者。 我學到了很多。 我最終的“保持評分”工作代碼在這里: http : //pastebin.com/BVVJAnKa

您可以執行以下簡單操作:

hp_history = [10]

def initial_health():
    return hp_history[0]

def cur_health():
    return hp_history[-1]

def affect_health(delta):
    hp_history.append(cur_health() + delta)
    return cur_health()

示范:

>>> cur_health()
10
>>> affect_health(20)
30
>>> affect_health(-5)
25
>>> affect_health(17)
42
>>> cur_health()
42
>>> print hp_history
[10, 30, 25, 42]

您不能像這樣存儲模塊級變量。 任何寫入該變量的嘗試都會創建一個局部變量。 檢查此腳本的行為:

s = 0
def f():
    s = 10
    print s

f()
print s

輸出:

10
0

相反,您應該轉向一種面向對象的方法。 開始將代碼放在類中:

class HeathlyGame():

    def __init__(self):
        self.init_hscore = 100
        self.final_score = 0

    # Beginning. Proceed or quit game.
    def start(self):
            print "Your shopping habits will either help you live longer or they will help you die sooner. No kidding! Wanna find out which one of the two in your case?", yn

            find_out = raw_input(select).upper()

...

game = HeathlyGame()
game.start()

這樣您就可以一次在內存中創建游戲的多個版本,每個版本都可以存儲自己的得分副本。

有關課程的更多信息,請嘗試以下鏈接: http : //en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes

問題似乎是您總是從init_hp開始,忘記了cur_hp

init_hp = 10
while True:
    food = choose_food()
    if "cereal" in food:
        cur_hp = init_hp - 5

# ..

但是您需要:

init_hp = 10
cur_hp = init_hp

while True:
    food = choose_food()
    if "cereal" in food:
        cur_hp -= 5

# ..

您可以使用發電機!

生成器基本上是一個函數,即使您離開該函數並再次調用它,它仍會跟蹤其對象的狀態。 而不是使用'return'和結尾,而是使用'yield'。 嘗試這樣的事情:

def HealthScore(add):
    score = 100
    while 1:
        score += add
        yield score

如果您調用HealthScore(-5),它將返回95。如果再調用HealthScore(5),它將返回100。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM