Reputation: 53
So I’m making a memory game using pygame and I need to display 16 images on a 4 by 4 grid. I made the 4x4 grid using a couple of for loops. I stored the images in a list variable. So far I can only get one image to display 16 times using the pygame.image.load() function. I’ve tried to google If there is some sort of loop I could run to display those images one by one from the list, but I’ve come up with nothing. The images also need to be in a random position every time the game is Played I’m pretty sure I know how to do that part I’m stuck on displaying the images on the window.
Any help is much appreciated Thanks.
Upvotes: 0
Views: 1032
Reputation: 14906
Create two lists of images, one that simply holds the image bitmaps:
# 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 )
Another list can hold a mapping of image index to location.
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 )
The random_locations
variable holds the index of the image loaded, this is random but will be of a form like: [7, 3, 9, 0, 2, 11, 12, 14, 15, 1, 4, 6, 8, 13, 5, 10]
with no-repeats.
So when drawing your 16 cells, at 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 ) )
Upvotes: 1