python - 使用 pygame 显示多个图像
问题描述
所以我正在使用 pygame 制作一个记忆游戏,我需要在 4 x 4 网格上显示 16 个图像。我使用几个 for 循环制作了 4x4 网格。我将图像存储在列表变量中。到目前为止,我只能使用 pygame.image.load() 函数让一张图像显示 16 次。我试过谷歌如果有某种循环,我可以运行以从列表中一张一张地显示这些图像,但我什么也没想到。每次玩游戏时,图像也需要处于随机位置我很确定我知道如何做那部分我坚持在窗口上显示图像。
非常感谢任何帮助谢谢。
解决方案
创建两个图像列表,一个仅包含图像位图:
# 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 ) )
推荐阅读
- list - Python for 循环连接数据帧
- python - 在models.py中使用auth_user_model时Django request.user不工作
- python - 使用熊猫读取带分隔符的文件
- java - 收到错误“HHH000010:在批处理发布时它仍然包含 JDBC 语句”
- go - 我可以使用单行命令输出多维切片值吗?
- jinja2 - Jinja:在for循环中比较列表中的项目
- google-apps-script - “聚合数据系列”平均而不是 Google Apps 脚本中的总和?
- java - Java Elasticsearch 客户端在 ClientConfiguration 中设置HttpClientConfigCallback
- html - 滚动时在右下角的 Master asp 页面中插入徽标不起作用:重叠
- javascript - setInterval“跳闸”本身并启动第二个间隔计时器