我目前有一个网格显示在我的屏幕和一个块正在填补。我希望每一块都用随机颜色填充。因此,我想从列表中删除coords_list(random_coord)
,当它被调用时,这样我的pygame.draw.rect
就不会试图在现有颜色的基础上打印新颜色。你知道吗
将从from itertools import product
开始的代码块放到pygame.draw.rect.............
时出错:
coord_location = coords_list[random_coord] index is out of range
我的代码:
from itertools import product
coords_list = list(product(range(30,1170,30), range(30,870, 30)))
#random map co-ordinate
random_coord = random.randint(0,1065)
coord_location = coords_list[random_coord]
coord_loc_x = coord_location[0]
coord_loc_y = coord_location[1]
#Random color
random_choice = random.randint(0,2)
if random_choice == 0:
terrain = blue
if random_choice == 1:
terrain = green
if random_choice == 2:
terrain = tan
##print(coord_location)
##random_terrain_type = terrain_types(random_choice)
pygame.draw.rect(screen, terrain, (coord_loc_x,coord_loc_y,30,30), 0)
line_start = 30
line_end = 30
top_line_start = 30
bottom_line_end = 30
for i in range(29):
pygame.draw.line(screen, black, (30, line_start), (1170, line_end),1)
line_start += 30
line_end += 30
for i in range(39):
pygame.draw.line(screen, black, (top_line_start, 30), (bottom_line_end, 870), 1)
top_line_start += 30
bottom_line_end += 30
问题是
1065
在一个超出范围的索引中这意味着最大索引是
1063
(python列表索引从0
开始)你的随机索引函数应该是
或者,如果您不想硬编码数字,
random
库也有它将从列表中随机选取一项,不管长度如何
我认为有两种方法可以解决这个问题。主要问题在于这段代码:
方法一不依赖于以随机顺序填充的正方形。我们假设每个正方形都需要填充,所以我们只需按顺序用随机颜色填充它们:
方法2将用随机颜色以随机顺序填充正方形:
相关问题 更多 >
编程相关推荐