如何在 python 中递增数组中的元组

问题描述 投票:0回答:2

我正在尝试创建这张地图,您可以在其中移动北、南、东和西,以进行 Python 文本冒险项目。问题是我似乎无法弄清楚如何更改坐标,或者我什至无法正确执行任何操作。

map_array = [
    [(1, 5), (2, 5), (3, 5), (4, 5), (5, 5)],
    [(1, 4), (2, 4), (3, 4), (4, 4), (5, 4)],
    [(1, 3), (2, 3), (3, 3), (4, 3), (5, 3)],
    [(1, 2), (2, 2), (3, 2), (4, 2), (5, 2)],
    [(1, 1), (2, 1), (3, 1), (4, 1), (5, 1)]
]
starting_point = map_array[2][2]


def show_map():
    for row in map_array:
        print('\n' + str(row))

show_map()



def explore(player_coordinates):
    print(f"Current player coordinates are {player_coordinates}.")
    update_player_coordinates = input("Where do you go? ")
    if update_player_coordinates.lower == 'east':
        player_coordinates += [1][1]
        return player_coordinates
    explore(player_coordinates)


explore(starting_point)

我正在努力做到这一点,以便当我输入一个主要方向时,它会增加 player_coordinates 的空间。到目前为止,我只得到这个:

当前玩家坐标为(3, 3)。 你去哪里?东方 当前玩家坐标为 (3, 3)。 你去哪里?

应该是(4, 3)

python arrays tuples increment
2个回答
0
投票

元组本质上是不可变的。如果你想要一个可变版本,你必须使用一个列表。

current_position = [3, 3]
if update_player_coordinates.lower() == "east":
    current_position[0] += 1

print(current_position)
> [4, 3]

或者,您必须重建并重新分配元组

current_position = (3, 3)
if update_player_coordinates.lower() == "east":
    current_position = current_position[0] + 1, current_position[1]

print(current_position)
> (4, 3)


0
投票

我不认为你真的想增加

map_array
中的项目 - 你只是想跟踪 which player are currently in.

所以你可能想要这样的东西:

# start the player at location 2,2 in the map
player_x = 2
player_y = 2

...
if update_player_coordinates.lower == 'east':
    # player_y stays the same 
    player_x += 1
© www.soinside.com 2019 - 2024. All rights reserved.