简体   繁体   English

如何使用参数更改函数中的全局变量

[英]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. 每个房间都包含if语句,因此某些事情会根据您所在的房间而运行。房间的布尔值会在我的代码顶部显示。

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. 将您的游戏世界封装在Game对象中并对所述游戏对象执行操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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