2016-06-12 60 views
1
worldArray = [["." for i in range(5)] for i in range(5)] 

这产生一张我可以用于我的游戏的地图。它应该是这个样子:如何更改多个索引的值?

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

比方说,'.'代表草砖。如果我想用'~'来代替特定数量的索引来代表水瓦,那么最简单的方法是什么?我希望地图看起来有点像:

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

我知道我可以手动办理,并更改每个具体指标,以显示'~'瓦,但真正在游戏中的地图我用的是40×40,而不是 - - 这将使得单独替换每个索引的工作有点繁琐和冗余。我希望能够定义我想替换的瓷砖,即第4行,第1-2列;第5行,第1 - 3列。我怎么能这样做呢?

回答

1

你可以写一个辅助函数

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) 

这将导致:

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

我会定义返回函数是否使它~而不是.

""" 
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()函数。

3

切片表示法是为这个完美的:

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) 
+0

哎呀,我误解了这个问题。想到随机的行/列(+1) –

0

基于你的问题我一起扔一个简单的功能,您可以运行。随意复制并粘贴到空闲控制台:

>>> def a(): 
global worldArray 
b = 1 
while b < 2: 
    c = (int(input('Row #: ')),int(input('Column-Leftbound: ')),int(input('Column-Rightbound: '))) 
    worldArray[c[0]][c[1]] = '~' 
    worldArray[c[0]][c[2]] = '~' 
    d = c[2] - c[1] 
    for i in range(d): 
     worldArray[c[0]][c[1]+i] = '~' 
    print(worldArray) 
    b = int(input('b now equals: ')) 
>>> a() #This line is for you to call the function at the console 

请注意以下几点:

合法的行数和列数从0-4。

此外,为了退出while循环,我要求你重置b的值。如果输入的值小于2,则停留在循环中。让我知道这是否有帮助。我试图保持它非常简单。

附注:

worldArray = [[“。”对于我在范围(5)]为我在范围(5)]

不会产生一个很好,整洁的矩阵对我来说。