【问题标题】:Why aren't the co-ordinate variables incrementing and decrementing in my functions in Python?为什么我的 Python 函数中的坐标变量不递增和递减?
【发布时间】:2016-06-08 20:10:52
【问题描述】:

我正在用 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”开始变化。对我的问题的任何帮助将不胜感激。

【问题讨论】:

  • 它们在函数内。您必须返回新值才能在函数外使用它。

标签: python function coordinates increment decrement


【解决方案1】:

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

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

这里发生的情况是变量coor 只是引用,而不是分配给。您要分配的是 in 该容器,而不是变量 coor 本身。这使用了全局 coorleft() 中的隐式存在,当它未在同一函数中分配时。

(我想这就是我在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}
>>>

【讨论】:

    【解决方案2】:

    您的坐标是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
    

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

    【讨论】:

    • 这是错误的,仍然会失败,因为函数得到了一个参数coorx,所以函数体永远不能使用global coorx
    • 是的,我在回答过程中也漏掉了一些愚蠢的东西:-/
    【解决方案3】:

    您将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
    

    【讨论】:

    • 您不能在没有global 声明的全局变量上使用+=-= 运算符。你会得到一个UnboundLocalError。即使支持就地添加也是如此(它不适用于整数)。
    • @Blckknght 我的错,不知道我在想什么。我在一个函数中混淆了“仅引用”与“引用和分配”。
    【解决方案4】:

    你的“移动”功能有问题:

    • 全局范围内有“coorx”和“coory”(您将两者都设置为 3)
    • 每个“移动”函数都有一个函数本地的参数(coorx 或 coory)

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

    无论如何,使用全局变量并以这种方式更改它们是一种糟糕的编程习惯。这个任务确实“要求”作为一个具有相关类属性 (self.coorx) 和让您“四处走动”的方法的类实现:

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-12
        • 2020-08-18
        • 1970-01-01
        • 2018-06-05
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多