Zeeman
Zeeman

Reputation: 47

Python 3 Functions - List Values for Other Functions

I am working on a very simple text based adventure game. I have been able to do the basics where the player can move from room to room. To enhance the game I wanted a simple combat system but I am having trouble implementing a system which will keep the players health score. I have provided a sample of how the code is at the moment and added comments.

def update_score(x): #after the player has a combat round the variable 'a'is updated with remianing hit points
    a = []
    a.append(x)

def hit_points(): #when the player is in combat and takes a hit, 2 points are deducted and it is passed to the updated score function
    y -= 2
    updated_score(y)

def Continue():
    #how can i then reference the updated score in another function. If the player goes into another battle, the remaining battle points will have to be used and deducted from

I have only just started getting to grips with functions and would like to know if it is possible to pass the updated values from the updated_score function to other functions or when the hit point function is called again.

I am trying to avoid using Global variables.

Any help much appreciatted

Upvotes: 1

Views: 81

Answers (3)

kosnik
kosnik

Reputation: 2434

I assume that your variable y is the one you need to update and access again in the future. But since y is of type int cannot be passed by reference to functions, which means that you cannot access it's updated value unless you define it as a global. Here is a good intro to global variables

https://www.geeksforgeeks.org/global-local-variables-python/

And here is a very detailed post about which variables are passed by value and which by reference in python

https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

In your case you should just make the following change in the definition of hit_points

def hit_points():
    global y
    y -= 2
    updated_score(y)

However, for a big project I wouldn't suggest to use global. This is a typical case where you should define a class and make y a member variable

class Game:
    def __init__(self):
        self._y = 0

    def hit_point(self):
        self._y -= 2

Upvotes: 0

i.terrible
i.terrible

Reputation: 157

Write a class. Consider:

class GameState:
   score = 0
   life = 10

   def update_score(self, x):
      self.score += x  # you can use negative values here too and perform various checks etc.  

   def hit_points(self):
      self.life -= 2

Your data is stored in the class and you can manipulate it with the methods. No issues with polluting global scope.

Upvotes: 0

bphi
bphi

Reputation: 3195

Try using a class

class Player:
    def __init__(self):
        self.hit_points = 100

    def take_hit(self):
        self.hit_points -= 2

p = Player()

print(p.hit_points)
>>> 100

p.take_hit()

print(p.hit_points)
>>> 98

Upvotes: 3

Related Questions