首页 > 解决方案 > 使用 pygame 显示多个图像

问题描述

所以我正在使用 pygame 制作一个记忆游戏,我需要在 4 x 4 网格上显示 16 个图像。我使用几个 for 循环制作了 4x4 网格。我将图像存储在列表变量中。到目前为止,我只能使用 pygame.image.load() 函数让一张图像显示 16 次。我试过谷歌如果有某种循环,我可以运行以从列表中一张一张地显示这些图像,但我什么也没想到。每次玩游戏时,图像也需要处于随机位置我很确定我知道如何做那部分我坚持在窗口上显示图像。

非常感谢任何帮助谢谢。

标签: pythonpygame

解决方案


创建两个图像列表,一个仅包含图像位图:

# 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 个单元格时,在 cell [i]draw处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 ) )

推荐阅读