【发布时间】: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