【问题标题】:Displaying multiple images using pygame使用 pygame 显示多个图像
【发布时间】:2019-11-18 00:24:29
【问题描述】:

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

任何帮助都非常感谢谢谢。

【问题讨论】:

  • 如果你发布代码而不是描述代码,这个问题会更容易回答。

标签: python pygame


【解决方案1】:

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

# 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 ) )

【讨论】:

  • 我在我的图像上运行了你的第一个 for 循环并且程序有点工作我没有收到错误但是当窗口打开时它只显示第 8 图像 16 次而不是不同的图像我也必须使用随机.shuffle() 函数每次运行程序时以随机顺序获取图像列表,程序只是从左到右读取它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
相关资源
最近更新 更多