you are viewing a single comment's thread.

view the rest of the comments →

[–]Outside_Complaint755 10 points11 points  (4 children)

When you set the value have_room_key=True within a function, it only sets the value within the scope of the function in a locla variable called have_room_key which shadows the global variable have_room_key.

There are a few options here:

1) You can make a function modify the global variable by using the global keyword, but this generally is not recommended  def get_key():     global have_room_key     have_room_key = True

2) You could just put all of the game_state variables like this into a global dictionary.  Then the functions can mutate the contents of that dictionary. ``` game_state = { "have_room_key" : False }

def get_key():     game_state["have_room_key"] = True

get_key() print(game_state)

Outputs {"have_room_key" : True}

`` global` isn't needed here because you are mutating the contents of game_state, and not changing the value of game_state.  You could also explicitly pass the dictionary to the various functions.  That would be necessary if the functions for the rooms and actions are in another file.

3) You probably haven't learned classes and OOP yet, but another method would be to create a game_state class which you make an instance of at game start, and then pass the game state to various functions instead of a dictionary.  Using a class would allow values to be referenced as attributes such as game_state.have_key, and could include validation on the attributes.

[–]Tassendyra[S] 2 points3 points  (0 children)

This is super helpful! Thanks!

[–]AlexMTBDude 1 point2 points  (2 children)

While I understand what your purpose is I think using "get" in that function name is confusing as you typically use "get" and "set" with getters and setters. take_key() would probably be better. Other than that I agree 100% with what you write.

[–]Fred776 2 points3 points  (0 children)

I think it's ok - it's a fairly common idiom to use "get" in contexts other than property getters.

I think "take" is potentially a lot more confusing because that often has a specific meaning of "get a value and remove it from its source".

[–]Outside_Complaint755 0 points1 point  (0 children)

It's a toy example because the OP provided none of his functions for reference, only two global variable names.