简体   繁体   English

如何跟踪Python中的分数增量?

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

I am writing a simple game program in Python where a user is prompted to select from "healthy" and "unhealthy" items in a grocery store. 我正在用Python编写一个简单的游戏程序,系统会提示用户从杂货店的“健康”和“不健康”项目中进行选择。 Each time the user selects a healthy item their "Health Score (initially 100) goes up. Each time they select from the unhealthy items their score goes down. 每次用户选择健康项目时,其“健康得分(最初为100)都会上升。每次从不健康项目中进行选择时,其得分都会下降。

My code adds and subtracts from the initial Health Score of 100, but doesn't keep track of the most updated score after each selection. 我的代码从初始健康评分100中减去,但在每次选择后都无法跟踪最新评分。 I want to give the user their new total after each transaction (new_hscore) and their grand total at the end (final_score), but I'm not sure how to do that. 我想在每次交易后为用户提供新的总计(new_hscore),并在结束时给用户总计(final_score),但是我不确定该怎么做。

Is it done with lists? 用列表完成吗? Do I use .append? 我是否使用.append? Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks in advance! 提前致谢!

Here is my code: http://pastebin.com/TvyURsMb 这是我的代码: http : //pastebin.com/TvyURsMb

You can see right away what I'm trying to do when you scroll down to the "def inner():" function. 向下滚动到“ def inner():”函数时,您可以立即看到我正在尝试执行的操作。

EDIT: I got it working! 编辑:我得到它的工作! Thank you all who contributed. 谢谢所有贡献者。 I learned a lot. 我学到了很多。 My final 'score-keeping' working code is here: http://pastebin.com/BVVJAnKa 我最终的“保持评分”工作代码在这里: http : //pastebin.com/BVVJAnKa

You can do something simple like this: 您可以执行以下简单操作:

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()

Demonstration: 示范:

>>> 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]

You can't store module level variables like that. 您不能像这样存储模块级变量。 Any attempt to write to that variable will create a local variable. 任何写入该变量的尝试都会创建一个局部变量。 Examine the behavior of this script: 检查此脚本的行为:

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

f()
print s

Output: 输出:

10
0

Instead you should be moving towards an object-oriented approach. 相反,您应该转向一种面向对象的方法。 Start placing your code in a class: 开始将代码放在类中:

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()

This will allow you to create multiple versions of the game in memory at once, and each can store their own copy of the score. 这样您就可以一次在内存中创建游戏的多个版本,每个版本都可以存储自己的得分副本。

For more on classes, try this link: http://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes 有关课程的更多信息,请尝试以下链接: http : //en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes

The problem seems to be you are always starting at init_hp , forgetting your cur_hp doing 问题似乎是您总是从init_hp开始,忘记了cur_hp

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

# ..

But you need: 但是您需要:

init_hp = 10
cur_hp = init_hp

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

# ..

You can use a generator! 您可以使用发电机!

A generator is basically a function that keeps track of the state of its objects even after you leave the function and call it again. 生成器基本上是一个函数,即使您离开该函数并再次调用它,它仍会跟踪其对象的状态。 Instead of using 'return' and the end, you use 'yield'. 而不是使用'return'和结尾,而是使用'yield'。 Try something like this: 尝试这样的事情:

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

if you call HealthScore(-5), it will return 95. If you then call HealthScore(5), it will return 100. 如果您调用HealthScore(-5),它将返回95。如果再调用HealthScore(5),它将返回100。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM