0

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

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

Is it done with lists? Do I use .append? Any help would be greatly appreciated! Thanks in advance!

Here is my code: http://pastebin.com/TvyURsMb

You can see right away what I'm trying to do when you scroll down to the "def inner():" function.

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

3
  • Your question is unclear. Do you want to give the user their maximum score? Or the history of all the scores they've obtained?
    – bitgarden
    Aug 29, 2013 at 17:05
  • @bitgarden - I think he means he wants to give whatever number is left at the end of the game. So, if I start with 100, lose 20, gain 30, and then end the game, he wants it to return 110.
    – user2555451
    Aug 29, 2013 at 17:08
  • @bitgarden - Yes, I want to give them their new total after each transaction (new_hscore) and their grand total at the end (final_score). Aug 29, 2013 at 17:10

4 Answers 4

1

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]
1
  • Awesome! This code worked perfectly --> +1 The only think I had to modify was the ' "Your new Health Score is: %d" % cur_score ' to ' Your new Health Score is:", cur_score() ' because it was expecting a variable and not a definition. Thanks a lot, Claudiu! Aug 30, 2013 at 5:01
0

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

0

The problem seems to be you are always starting at init_hp, forgetting your cur_hp doing

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

# ..
1
  • Monkey, that would have been a very fine solution (and it probably is) but I must be doing something wrong... When I tried it I got "local variable 'cur_hp' referenced before assignment". Aug 30, 2013 at 4:14
-1

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'. 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.

7
  • @ CMDoolitle - I like the idea of a generator. But, when I try to call the current score like this: print "Your starting Health Score is: %d" % HealthScore(0) it tells me that "..a number is required not a generator". In other words, how do I set HealthScore() to a variable? When I try "% score" it tells me that "score" is not defined. Sorry for the basic question :-) And, thanks a ton for the help!!! Aug 29, 2013 at 17:40
  • Yeah, that is unexpected... can you just go var = HealthScore(8) print "%d" % var ? Aug 29, 2013 at 18:05
  • All things considered tho, if you don't know how to use classes, you need to. Aug 29, 2013 at 18:38
  • It seems like it. I'm learning Python from the Learn Python The Hard Way by Zed Shaw and I'm at a lesson where I have to create my own game. The "Modules, Classes, And Objects" lesson is three lessons ahead. I'll also check out the @DrRobotNinja's link below. Aug 29, 2013 at 21:00
  • hmm this is not really a place for a generator
    – Claudiu
    Aug 29, 2013 at 22:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.