python - 为什么我的 Python 函数中的坐标变量没有递增和递减?

标签 python function coordinates increment decrement

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

最佳答案

您的坐标是全局,但您尚未将它们声明为全局坐标,因此它们被同名的局部变量所遮蔽。您需要使用函数将它们声明为全局,以便能够修改它们。

选项一(无全局变量):

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

关于python - 为什么我的 Python 函数中的坐标变量没有递增和递减?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35637695/

相关文章:

linux - 在 Linux 中通过编辑二进制文件来更改函数

javascript - 同步调用异步 IIFE

android - 在android dev中定位项目

java - 把一个长方形分成正方形

c - 结构表

python - 使用 pandas to_datetime 时如何定义格式?

python - 如何将多个 Cython pyx 文件合并到一个链接库中?

python - 使用与条件匹配的第一个值创建一个新列

python - Python 中的散列

javascript - 简化/优雅此代码?