创建两个图像列表,一个仅包含图像位图:
# Load in all the 16 images
memory_images = []
for filename in [ 'flower01.png', 'tree01.png', 'flower02.png', 'duck.png' ... ]
new_image = pygame.image.load( filename )
memory_images.append( new_image )
另一个列表可以保存图像索引到位置的映射。
import random
# make a list of random numbers with no repeats:
image_count = len( memory_images ) # should be 16 for a 4x4 grid
random_locations = random.sample( range( image_count ), image_count )
random_locations 变量保存加载图像的索引,这是随机的,但格式如下:[7, 3, 9, 0, 2, 11, 12, 14, 15, 1, 4, 6, 8, 13, 5, 10],无重复。
所以在绘制 16 个单元格时,在单元格 [i] 处绘制 memory_images[ random_locations[ i ] ]。
for i in range( 16 ):
x, y = grid_locations[ i ]
image = memory_images[ random_locations[ i ] ]
screen.blit( image, ( x, y ) )