简体   繁体   中英

How to change a global variable in a function using parameters

I am making a text adventure game and I am trying to make a function to change rooms. My rooms are made of booleans, so therefore when I change room, the room I exit becomes false, and the new one becomes true. Each room contains if statements so certain things will run depending on what room you are in. The booleans for the rooms are stated at the top of my code like this.

spawn = True
living_room = True
etc...

So I decided to make a function like this

def change_room(room, new_room):
    room = False
    new_room = True

I then call the function in the following way

if spawn:
    if spawn_input == "door":
        change_room(spawn, living_room)
elif living_room:
    do something

The problem is that the function does not change the global variables to the boolean I choose. I understand that this could be fixed by changing the function to this

def change_room():
    global spawn
    global living_room
    spawn = False
    living_room = True

But I do not want to do this as I would like the function to have parameters so the function can be used for any room to any room. Would be great if someone helped me with this. Thank you!

Reluctant Solution

I personally don't agree with the route you are taking, it is BAD because you are modifying the global space instead of modifying an abstracted data structure that represent your game world. You should store this information in some object, like a dictionary for example. Nonetheless, here is the solution you seek...

def change_room(room, new_room):
    g = globals()
    g[room] = False
    g[new_room] = True

...

if spawn:
    if spawn_input == "door":
        change_room('spawn', 'living_room')
elif living_room:
    # do something

Appropriate Solution

Encapsulate your game world in a Game object and perform operation on said game object.

SPAWN_ROOM = 'spawn'
LIVING_ROOM = 'living_room'

class Game:

  def __init__(self):
    self.current_room = SPAWN_ROOM

  def change_room(self, new_room):
    self.current_room = new_room
    print('You entered {}'.format(new_room))


game = Game()

...

if game.current_room == SPAWN_ROOM:
  if user_input == 'door':
    game.change_room(LIVING_ROOM)

elif game.current_room == LIVING_ROOM:
  # do something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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