gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:54:36 25 4
gpt4 key购买 nike

我正在用 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

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

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

25 4 0
文章推荐: python - 如何为 Pandas DataFrame 指定输入数据类型
文章推荐: javascript - 内容溢出超出 Div View 高度
文章推荐: javascript - 如何阻止背景样式覆盖 React 内联样式的 backgroundColor 样式?
文章推荐: python - Itertools.permutations 返回 而不是排列列表