Skip to content
Advertisement

Setting back global variables back to their default value

In game,I have created some global variables whose value changes when a certain action occur.When I restart the game,I want their value to be set again to their initial value.

K= 0

def change():
  #change global variable 
  value
  global K
  K +=5
 def restart():
  #restarts game

I can change global variable value by equilazing it back to its original value.

K = 0

Is there any other way to do so,when there are lot of variables,I can’t make them local.

Thanks for your help

Advertisement

Answer

There is to little sample code there to give you an example – but from what I can get you are trying to do, it is time to move on to use some Object Orientation.

Without resorting to anything more complex, you can have an object that acts as a namespace for the variables you need to acess across several functions.

Upon re-starting the game, simply create a new instance with all the initial values set for your state-keeping object.

Due to the way Python works, you can even set the default values as class attributes, and each time those are updated, the update will affect only the instance corresponding to the state of the ongoing game. By doing this you can use one global variable, holding the game state instance:

class GameState:
   k = 0
   other_var = 0

def restart():
   global state
   state = GameState()

def change():
   ...
   state.k += 5

note that if you do this correctly, you set grounds for getting “for free” a way to save and resume your game, to have more than one player, each player with a separate state, at once, and so on.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement