我正在用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”。如果您能帮我解决这个问题,我们将不胜感激。你知道吗
您的变量正在局部更改。使用全局解决问题。您还可以使用参数和返回坐标来解决问题。你知道吗
读一些让我想起这个问题的东西。无需
return
值或使用global
即可更改坐标的一种方法是使用可变容器类型:这里发生的是变量
coor
只被引用,而不是赋值给。您要分配给的是容器中的,而不是变量coor
本身。当全局coor
在left()
中没有赋值给同一个函数时,它使用了它的隐式存在性。你知道吗(我想这就是我在first version of my previous answer中的想法。)
这也适用于字典,可读性更强:
你的坐标是
global
,但是你没有声明它们是全局的,所以它们被一个同名的局部变量所遮蔽。您需要用函数声明它们global
,以便能够修改它们。你知道吗选项一(不带全局变量):
方案二:
您可以阅读有关globalshere和here的更多信息
相关问题 更多 >
编程相关推荐