如何更改多个索引的值?

2024-10-03 11:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

worldArray = [["." for i in range(5)] for i in range(5)]

这产生了一个地图,我可以使用我的游戏。它应该看起来像:

[['.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.']]

假设'.'代表一个草瓷砖。如果我想将特定数量的索引替换为'~',而不是表示一个water tile,那么最简单的方法是什么?我想让地图看起来有点像:

[['.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.'],
 ['~', '~', '.', '.', '.'],
 ['~', '~', '~', '.', '.']]

我知道我可以手动遍历并更改每个特定的索引来显示'~'图块,但是我使用的真正的游戏内地图是40x40,这会使单独替换每个索引的工作变得有点乏味和多余。我想能够定义我要更换的磁贴,即第4行,第1-2列;第5行,第1-3列。我怎么能这样做呢?你知道吗


Tags: 方法in游戏for数量定义地图range
3条回答

你可以写一个助手函数

def replace_at_position(world_array, row_col_dict, repl_char):
    """
    Use row_col_dict in format of {row : (startOfRange, endOfRange)} to replace the characters
    inside the specific range at the specific row with repl_char
    """

    for row in row_col_dict.keys():
        startPos, endPos = row_col_dict[row]

        for i in range(startPos, endPos):
            worldArray[row][i] = repl_char
    return worldArray

你可以这样使用它:

worldArray = [["." for i in range(10)] for j in range(5)]

# replace row 2 (the third row) colums 0-4 (inclusive, exclusive, like range) with character '~'
worldArray = replace_at_position(worldArray, {2 : (0,10)}, '~')

#replace row 1 (the second row) colums 0-5 (inc, exc, like range) with character '~'
worldArray = replace_at_position(worldArray, {1 : (0, 5)}, '~')

pprint.pprint(worldArray)

这将导致:

[['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['~', '~', '~', '~', '~', '.', '.', '.', '.', '.'],
 ['~', '~', '~', '~', '~', '~', '~', '~', '~', '~'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']]

我将定义一个函数,返回是否使其~而不是.。你知道吗

"""
Determines if the game position is regular or not
"""
def isRegular(x,y):
    # Only replace Row 4 column 1 and 2 with ~
    return not (x==4 and y in [1,2])

worldArray = [["." if isRegular(x,y) else "~" for x in range(5) ] for y in range(5)]

您可以根据自己的喜好更改regular()函数。你知道吗

切片表示法非常适合:

from functools import partial

def tile(icon, row, col_start, col_end):
    worldArray[row][col_start:col_end] = icon * (col_end - col_start)

water = partial(tile, '~')
mountain = partial(tile, '^')

water(3, 0, 2)
water(4, 0, 3)

相关问题 更多 >