为什么我的 Python 函数中的坐标变量不递增和递减?

Why aren't the co-ordinate variables incrementing and decrementing in my functions in Python?

我正在编写 Python 中基于文本的冒险游戏,玩家在 5x5 网格上移动并拾取物品,但我无法更改玩家的坐标。 coorx 和 coory 在它们各自的函数中不递增和递减。

coorx = 3 #The beginning x coordinate of the player
coory = 3 #The beginning y coordinate of the player

loop = True
#The dimensions of the map are 5x5.
# __ __ __ __ __
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |><|  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#>< = The player's starting position on the map

def left(coorx):
    if coorx != 1: #This checks if the x co-ordinate is not less than 1 so the player does walk off the map.
        coorx -= 1 #This function moves the player left by decrementing the x co-ordinate.

def right(coorx):
    if coorx != 5: #This checks if the x co-ordinate is not more than 5 so the player does walk off the map.
        coorx += 1 #This function moves the player right by incrementing the x co-ordinate.

def back(coory):
    if coory != 1: #This checks if the y co-ordinate is not less than 1 so the player does walk off the map.
        coory -= 1 #This function moves the player left by decrementing the y co-ordinate.

def forward(coory):
    if coory != 5: #This checks if the y co-ordinate is not more than 5 so the player does walk off the map.
        coory += 1 #This function moves the player right by incrementing the y co-ordinate.


while loop: #This loops as long as the variable "loop" is True, and since "loop" never changes, this is an infinite loop.
    move = input().lower()

    if move == "l":
        left(coorx)
        print("You move left.")
        print(coorx, coory)
    elif move == "r":
        right(coorx)
        print("You move right.")
        print(coorx, coory)
    elif move == "f":
        forward(coory)
        print("You move forward.")
        print(coorx, coory)
    elif move == "b":
        back(coory)
        print("You move backwards.")
        print(coorx, coory)

这是输出的内容。

>f
>You move forward.
>3 3
>f
>You move forward.
>3 3
>l
>You move left.
>3 3
>l
>You move left.
>3 3
>b
>You move backwards.
>3 3
>b
>You move backwards.
>3 3
>r
>You move right.
>3 3
>r
>You move right.
>3 3

如您所见,坐标始终没有从“3 3”变化。非常感谢对我的问题的任何帮助。

您的坐标是 global,但您尚未将它们声明为全局坐标,因此它们被同名的局部变量覆盖。您需要使用函数声明它们 global 才能修改它们。

选项一(没有全局变量):

def left(x_coord):
    if x_coord != 1: 
        x_coord -= 1
    return x_coord # Do something with this

选项二:

def left():
    global coorx
    if coorx != 1:
        coorx -= 1

您可以阅读有关全局变量的更多信息here and here

您的变量正在本地更改。使用全局来解决问题。您还可以使用参数和返回坐标来解决问题。

您将 coorxcoory 作为值传递给参数名称为 coorxcoory 的函数。这使得局部引用 coorxcoory 而不是全局引用。

编辑:您需要在每个函数的顶部指定 global coorxglobal coory

此外,在 leftrightbackforward 的函数定义中,您不应使用相同的参数名称。此外,在您的特定情况下,您不需要向这些函数传递任何参数,因为 left() 是向左移动的。根据您的功能,它不需要参数。

def left():
    global coorx
    ...  # rest as per your code

def right():
    global coorx
    ...  # rest as per your code

def back():
    global coory
    ...  # rest as per your code

def forward():
    global coory
    ...  # rest as per your code

你的 "move" 函数有问题:

  • 全局范围内有"coorx"和"coory"(你都设置为3)
  • 每个 "move" 函数都有一个函数局部参数(coorx 或 coory)

您的函数所做的是更改在函数 returns 之后丢弃的局部变量(参数)。全局变量不会改变。

无论如何,使用全局变量并以这种方式更改它们是一种糟糕的编程习惯。这个任务实际上 "asks for" 作为 class 实现,具有相关的 class 属性 (self.coorx) 和让你 "move around":

的方法

http://www.diveintopython3.net/iterators.html#defining-classes

刚读到一些让我想起这个问题的东西。无需 return 值或使用 global 即可更改坐标的一种方法是使用可变容器类型:

>>> coor = [3, 3]  # x, y
>>>
>>> def left():
...     if coor[0] != 1:
...         coor[0] -= 1
...
>>>
>>> left()
>>> coor
[2, 3]
>>>

这里发生的事情是变量 coor 仅被 引用 ,而不是 分配给 。您要分配给 in 那个容器,而不是变量 coor 本身。当未在同一函数中分配给它时,这会在 left() 中使用全局 coor 的隐式存在。

(我想这就是我在 first version of my previous answer 中想到的。)

这也适用于字典,并且更具可读性:

>>> coor = dict(x=3, y=3)
>>>
>>> def left():
...     if coor['x'] != 1:
...         coor['x'] -= 1
...
>>>
>>> left()
>>> coor
{'x': 2, 'y': 3}
>>>