Pygame Error: Unsupported Image Format - python

Hi I'm trying to follow these instructions from my last question:
Pygame: how to load 150 images and present each one for only .5sec per trial
This is the code I currently have and I'm unsure where I'm going wrong.
import pygame, glob
pygame.init()
pygame.mixer.init()
clock=pygame.time.Clock()
#### Set up window
window=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
centre=window.get_rect().center
pygame.mouse.set_visible(False)
#colours
black = (0, 0, 0)
white = (255, 255, 255)
types= '*.tif'
artfile_names= []
for files in types:
artfile_names.extend(glob.glob(files))
image_list = []
for artwork in artfile_names:
image_list.append(pygame.image.load(artwork).convert())
##Randomizing
index=0
current_image = image_list[index]
if image_list[index]>= 150:
index=0
stimulus= pygame.image.load('image_list')
soundPlay=True
def artwork():
window.blit(stimulus,pygame.FULLSCREEN)
while not soundPlay:
for imageEvent in pygame.event.get():
artwork()
pygame.display.update()
clock.tick()

The first mistake is the same as in your previous question: types= '*.tif'. That means types is a string, but you actually wanted a tuple with the allowed file types: types = '*.tif', (the comma turns it into a tuple). So you iterate over the letters in '*.tif' and pass them to glob.glob which gives you all files in the directory and of course image_list.append(pygame.image.load(artwork).convert()) can't work if you pass it for example a .py file.
The next mistake is the stimulus = pygame.image.load('image_list') line which doesn't work because you need to pass a complete file name or path to the load function. I think your stimulus variable should actually be the current_image.
Here's a complete example that also shows you how to implement a timer.
import glob
import random
import pygame
pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode((640, 480))
file_types = '*.tif', # The comma turns it into a tuple.
# file_types = ['*.tif'] # Or use a list.
artfile_names = []
for file_type in file_types:
artfile_names.extend(glob.glob(file_type))
image_list = []
for artwork in artfile_names:
image_list.append(pygame.image.load(artwork).convert())
random.shuffle(image_list)
index = 0
current_image = image_list[index]
previous_time = pygame.time.get_ticks()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Calcualte the passed time, then increment the index, use
# modulo to keep it in the correct range and finally change
# the image.
current_time = pygame.time.get_ticks()
if current_time - previous_time > 500: # milliseconds
index += 1
index %= len(image_list)
current_image = image_list[index]
previous_time = current_time
# Draw everything.
window.fill((30, 30, 30)) # Clear the screen.
# Blit the current image.
window.blit(current_image, (100, 100))
pygame.display.update()
clock.tick(30)

Near the bottom you have the line:
stimulus= pygame.image.load('image_list')
Here you are trying to load an image titled image_list. There's no file extension there, so your OS doesn't recognize the filetype. But even if you did include a file extension, I think you're trying to load the individual images in the list image_list, and that's a whole other story.

Related

change the color of a variable in an fstring python [duplicate]

I am creating a game with pygame in which the color of a letter changes when you type that letter. Like nitrotype.com. However the problem is that I don't know how to change the colour of individual letters.
I can't clear the screen and then do it because then that would change the color of the entire line.
So either I need a way to change the colour of individual letters or a way to just put single letters on the screen one at a time. However I don't know how to uniformly put the letters(such that the end sentence is centered). Please could someone help me out here. Either by telling me how to change the color of individual letters or how to put individual letters in a perfect manner and then change their color.
import pygame as pg
import pygame
pg.init()
screenHeight, screenWidth = 600, 800
gameDisplay = pg.display.set_mode((screenWidth, screenHeight))
pg.display.set_caption("Nitrotype")
black = (255, 255, 255)
white = (0, 0, 0)
gameDisplay.fill(white)
pg.display.update()
gameOn = True
with open("text.txt", "r") as f:
contents = f.read()
def msgToScreen(msg, color, size):
cur = []
strings = []
words = msg.split(" ")
for i in words:
cur.append(i)
if len(" ".join(cur)) >= 35:
strings.append(" ".join(cur))
cur = []
if cur != []:strings.append(" ".join(cur))
curY = 20
for string in strings:
font = pg.font.SysFont(None, size)
text = font.render(string, True, color)
text_rect = text.get_rect(center=(screenWidth/2, curY))
gameDisplay.blit(text, text_rect)
curY += 40
return text
textOnScreen = msgToScreen(contents, black, 50)
pg.display.update()
curIdx = 0
keyCombination = {"a":pg.K_a, "b":pg.K_b, "c":pg.K_c, "d":pg.K_d, "e":pg.K_e, "f":pg.K_f,
"g":pg.K_g, "h":pg.K_h, "i":pg.K_i, "j":pg.K_j, "k":pg.K_k, "l":pg.K_l,
"m":pg.K_m, "n":pg.K_n, "o":pg.K_o, "p":pg.K_p, "q":pg.K_q, "r":pg.K_r,
"s":pg.K_s, "t":pg.K_t, "u":pg.K_u, "v":pg.K_v, "w":pg.K_w, "x":pg.K_x,
"y":pg.K_y, "z":pg.K_z}
while gameOn:
for event in pygame.event.get():
if event.type == pg.QUIT:
gameOn = False
if event.type == pg.KEYDOWN:
if event.key == keyCombination[contents[curIdx].lower()]:
#Here is where the color of the current letter should change
curIdx += 1
pg.quit()
You can't change the color of a single letter during font rendering; you'll have to render your text letter by letter.
You can either use render() to render each letter to its own surface and blit them to your screen, but you have to calculate where each letter should go manually.
It's a little bit easier if you use the new freetype module, which has a lot of handy functions in the Font class like origin, get_rect and get_metrics which can calculate how big each letter is.
Here's a simple example I hacked together. It's not perfect but you'll get the idea.
import pygame
import pygame.freetype
from itertools import cycle
def main():
pygame.init()
screen = pygame.display.set_mode((800, 600))
# just some demo data for you to type
data = cycle(['This is an example.', 'This is another, longer sentence.'])
current = next(data)
current_idx = 0 # points to the current letter, as you have already guessed
font = pygame.freetype.Font(None, 50)
# the font in the new freetype module have an origin property.
# if you set this to True, the render functions take the dest position
# to be that of the text origin, as opposed to the top-left corner
# of the bounding box
font.origin = True
font_height = font.get_sized_height()
# we want to know how much space each letter takes during rendering.
# the item at index 4 is the 'horizontal_advance_x'
M_ADV_X = 4
# let's calculate how big the entire line of text is
text_surf_rect = font.get_rect(current)
# in this rect, the y property is the baseline
# we use since we use the origin mode
baseline = text_surf_rect.y
# now let's create a surface to render the text on
# and center it on the screen
text_surf = pygame.Surface(text_surf_rect.size)
text_surf_rect.center = screen.get_rect().center
# calculate the width (and other stuff) for each letter of the text
metrics = font.get_metrics(current)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == pygame.KEYDOWN:
if e.unicode == current[current_idx].lower():
# if we press the correct letter, move the index
current_idx += 1
if current_idx >= len(current):
# if the sentence is complete, let's prepare the
# next surface
current_idx = 0
current = next(data)
text_surf_rect = font.get_rect(current)
baseline = text_surf_rect.y
text_surf = pygame.Surface(text_surf_rect.size)
text_surf_rect.center = screen.get_rect().center
metrics = font.get_metrics(current)
# clear everything
screen.fill('white')
text_surf.fill('white')
x = 0
# render each letter of the current sentence one by one
for (idx, (letter, metric)) in enumerate(zip(current, metrics)):
# select the right color
if idx == current_idx:
color = 'lightblue'
elif idx < current_idx:
color = 'lightgrey'
else:
color = 'black'
# render the single letter
font.render_to(text_surf, (x, baseline), letter, color)
# and move the start position
x += metric[M_ADV_X]
screen.blit(text_surf, text_surf_rect)
pygame.display.flip()
if __name__ == '__main__':
main()
Centering the text is easy using a second Surface and using the Rect class' center property.

SGC GUI and Pygame Widget implementation

Hi I am trying to code a simple application with Pygame. I have made various searches and found that best way to get an user input is to use a 3rd Party GUI.
I have found Simple Game Code for this aim. Below, you can find my base code, it looks for the images inside same path of script and replaces them in order at screen.
But I have no experience with this kind of applications. I am trying to understand from the documentation of SGC: https://github.com/codetricity/sgc/blob/master/example/test.py
It is not an easy task for me. I could develop this far, my code is running. But I couldn't understand the button implementation part.
Can you help me implement a "Scale Widget" at beginning to get user input between a range of integers. Also, a "Button Widget" to pass starting screen and begin my main code I will share with you.
Thanks for your time
import glob
import time
import numpy as np
import timeit
import pygame
import sgc
from sgc.locals import *
start = timeit.default_timer()
maxnote = 10
maxduration = 10
pygame.init()
white = (255, 255, 255)
path = r'C:\Path'
mylistname = [f for f in sorted(glob.glob("*.png"))]
mylistpath = [f for f in sorted(glob.glob(path + "/*.png"))]
for i in range(len(mylistname)):
mylistname[i] = mylistname[i].replace(".png", "")
mylistname[i] = mylistname[i].replace("h", ".")
mylistname[i] = float(mylistname[i])
imgname = []
for i in range(len(mylistname)):
imgname.append(str("img" + str(mylistname[i])))
imglist = []
for i in range(len(mylistpath)):
name = str(imgname[i])
name = pygame.image.load(mylistpath[i])
imglist.append(name)
current_image = 0
display_surface = pygame.display.set_mode((400, 400))
while (timeit.default_timer() - start < maxduration) | (current_image < maxnote):
#for imj in range(len(imglist)+1):
print(str(current_image) + "s")
if current_image < len(imglist):
print(str(current_image) + "0")
while True:
print(str(current_image) + "p")
display_surface.fill(white)
display_rect = display_surface.get_rect()
image_rect = imglist[current_image].get_rect()
image_rect.center = display_rect.center
display_surface.blit(imglist[current_image],image_rect)
pygame.display.update()
pygame.display.flip()
time.sleep(5)
current_image = current_image + 1
print(str(current_image) + "n")
break
else:
font = pygame.font.Font('freesansbold.ttf', 32)
text = font.render('GeeksForGeeks', True, (0, 255, 0), (0, 0, 128))
textRect = text.get_rect()
textRect.center = display_rect.center
display_surface.blit(text, textRect)
pygame.display.update()
pygame.display.flip()
time.sleep(5)
pygame.display.quit()
print("the end")
Using your code I added SGC button which is displayed on images and it display text in console when it is clicked.
I had two problems:
SGC is old and works only with Python 2. For Python 3 it would need relative imports. But later it may need other changes.
time.sleep() was blocking loop which checks key/mouse events, updates widgets, runs function when button is clicked, etc. sleep makes this problem with all GUI frameworks (tkinter, PyQt, wxpython, etc.) and in PyGame loop which has to run all time to check and update widgets and other elements. I use clock to check if it is time to change image. This way loop can works all time and it can update Button when mouse move on button and click it.
Tested on Python 2.7, Linux Mint 19.2
import glob
import pygame
import time
import sgc
from sgc.locals import *
# --- constants --- (UPPER_CASE)
WHITE = (255, 255, 255)
MAXNOTE = 10
MAXDURATION = 10
PATH = r'C:\Path'
# --- functions --- (lower_case_names)
def on_click_button():
print('on_click_button')
# --- main ---
filenames = sorted(glob.glob(PATH + "/*.png"))
print('len:', len(filenames))
names = []
images = []
for item in filenames:
names.append("img" + item.replace(".png", "").replace("h", "."))
images.append(pygame.image.load(item))
current_image = 0
# ---
pygame.init()
display_surface = sgc.surface.Screen((400, 400))
#display_surface = pygame.display.set_mode((400, 400))
display_rect = display_surface.get_rect()
font = pygame.font.Font('freesansbold.ttf', 32)
# add button
btn = sgc.Button(label="Clicky", pos=(10, 10))#, label_font=font)
btn.add(0)
# assign function to button
btn.on_click = on_click_button
# ---
clock = pygame.time.Clock()
current_time = pygame.time.get_ticks()
end_time = current_time + MAXDURATION*1000
end_slide = current_time
running = True
while running and ((current_time < end_time) or (current_image < MAXNOTE)):
ticks = clock.tick(30)
for event in pygame.event.get():
# send events to SGC so it can check if button was clicke
sgc.event(event)
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
current_time = pygame.time.get_ticks()
if (end_slide <= current_time) and (current_image < len(images)):
image = images[current_image]
image_rect = image.get_rect()
image_rect.center = display_rect.center
end_slide = current_time + 2000 # 2000ms (2s)
current_image += 1
display_surface.fill(WHITE)
display_surface.blit(image, image_rect)
# draw all widgets
sgc.update(ticks)
pygame.display.flip() # doesn't need pygame.display.update() because both do the same
# ---
display_surface.fill(WHITE)
text = font.render('GeeksForGeeks', True, (0, 255, 0), (0, 0, 128))
text_rect = text.get_rect()
text_rect.center = display_rect.center
display_surface.blit(text, text_rect)
#pygame.display.update() # no need it
pygame.display.flip()
time.sleep(5)
# --- end ---
pygame.display.quit()
print("the end")

Pygame slideshow delay anormally long

I'm setting up a Slideshow system mixing images and videos, from a directory.
I'm using a Raspberry Pi B, pygame and vlc.
I didn't install X so everything happens in framebuffer.
My actual code is working but :
The 4 seconds delay is not respected. The image is displayed +- 11 seconds.
One of the images witch has nothing particular, is displayed much longer, +- 1m30. (my real problem)
I tried a bash script with fbi, fim, vlc without suitable result. The closest was with vlc but it takes too long to render an image in framebuffer.
I'm quite new to pygame. Here is the code:
import pygame
import sys
import time
import vlc
import os
filesdir = '/home/pi/SMBmount/'
pygame.init()
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
black = 0, 0, 0
screen = pygame.display.set_mode(size)
while True:
# For every file in filesdir :
for filename in os.listdir(filesdir):
filenamelower = filename.lower()
# If image:
if filenamelower.endswith('.png') or filenamelower.endswith('.jpg') or filenamelower.endswith('.jpeg'):
fullname = filesdir + filename
img = pygame.image.load(fullname)
img = pygame.transform.scale(img, size)
imgrect = img.get_rect()
screen.fill(black)
screen.blit(img, imgrect)
pygame.mouse.set_visible(False)
pygame.display.flip()
time.sleep(4)
# Elif video:
elif filenamelower.endswith('.mp4') or filenamelower.endswith('.mkv') or filenamelower.endswith('.avi'):
fullname = filesdir + filename
# Create instane of VLC and create reference to movie.
vlcInstance = vlc.Instance("--aout=adummy")
media = vlcInstance.media_new(fullname)
# Create new instance of vlc player
player = vlcInstance.media_player_new()
# Load movie into vlc player instance
player.set_media(media)
# Start movie playback
player.play()
# Do not continue if video not finished
while player.get_state() != vlc.State.Ended:
# Quit if keyboard pressed during video
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pygame.display.quit()
pygame.quit()
sys.exit()
player.stop()
# Quit if keyboard pressed during video
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pygame.display.quit()
pygame.quit()
sys.exit()
I'm open to any alternative able to work with pictures AND videos.
EDIT: It was finally the time it takes to pygame to resize the (next) image with pygame.transform.scale().
Is there any way to optimise that ? Like for example, to print fullscreen without resizing the large images ?
I cannot reproduce the behaviour without the images and the videos, but here a couple of advices which should help in speed up the code when displaying images.
Do not use time.sleep(). It will freeze the game for the given time, so all calculations are done outside this time window, consuming more time. Better to use pygame time Clock. From the docs of its tick() method:
If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. This can be used to help limit the runtime speed of a game. By calling Clock.tick(40) once per frame, the program will never run at more than 40 frames per second.
The tick() method should be called once per iteration in the main loop, so better to not put it inside an if statement.
Here:
screen.fill(black)
screen.blit(img, imgrect)
The first line screen.fill(black) is completely useless: you are redrawing the whole surface in the second line covering all the black background, since the image is rescaled to the screen size. You can safely blit the image without filling the background with black.
This will save time, because each time you use blit or fill, pygame in background does a lot of operation on the Surface to change the color of the pixels (the more the pixels changed, the longer the time needed).
This of course if any of the images you load has an alpha channel. If you have pictures with alpha channel, you need to paint black the background before. To save time, I suggest to remove the alpha channel from the images using another program.
pygame.transform.scale() requires time, especially if you have very large picture. Try to rescale your image with another program and load in pygame images of size the closer possible to your screen.
When loading the images, add .convert(). This will make blitting faster. Should be: img = pygame.image.load(fullname).convert().
In the end, your code should look like:
imgexts = ['png', 'jpg', 'jpeg']
videxts = ['mp4', 'mkv']
#filtering out non video and non image files in the directory using regex
#remember to import re module
showlist = [filename for filename in os.listdir(filesdir) if re.search('[' + '|'.join(imgexts + videxts) + ']$', filename.lower())]
clock = pygame.time.Clock()
while True:
# For every file in filesdir :
for filename in showlist:
filenamelower = filename.lower()
# If image:
if filenamelower.endswith('.png') or filenamelower.endswith('.jpg') or filenamelower.endswith('.jpeg'):
#all your stuff but NOT the time.sleep()
elif filenamelower.endswith('.mp4') or filenamelower.endswith('.mkv') or filenamelower.endswith('.avi'):
#unchanged here
clock.tick(0.25) #framerate = 0.25 means 1 frame each 4 seconds
for event in pygame.event.get():
#unchanged here
I figured out what were the issues, with the help of Valentino.
He helped me to optimize the code to improve the loading times of every image, that fixed the first issue.
See his answer.
Additionnally, I added a block of code :
# If image is not same dimensions
if imgrect.size != size:
img = Image.open(fullname)
img = img.resize(size, Image.ANTIALIAS)
img.save(fullname, optimize=True, quality=95)
img = pygame.image.load(fullname).convert()
imgrect = img.get_rect()
If the picture is not the screen resolution, I use Pillow (PIL) to resize and reduce the color palette to 8-bit (256 colors).
It reduces file sizes significantly (especially for big files) and allow pygame to load the image faster.
It fixed the second issue.
For those interested, the full code is :
import pygame
import sys
import vlc
import os
import re
from PIL import Image
filesdir = '/home/pi/SMBmount/'
imgexts = ['png', 'jpg', 'jpeg']
videxts = ['mp4', 'mkv', 'avi']
time = 5 # Time to display every img
#filtering out non video and non image files in the directory using regex
showlist = [filename for filename in os.listdir(filesdir) if re.search('[' + '|'.join(imgexts + videxts) + ']$', filename.lower())]
pygame.init()
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
while True:
# For every file in filesdir :
for filename in showlist:
filenamelower = filename.lower()
# If image:
if filenamelower.endswith('.png') or filenamelower.endswith('.jpg') or filenamelower.endswith('.jpeg'):
fullname = filesdir + filename
img = pygame.image.load(fullname).convert()
imgrect = img.get_rect()
# If image is not same dimensions
if imgrect.size != size:
img = Image.open(fullname)
img = img.resize(size, Image.ANTIALIAS)
img.save(fullname, optimize=True, quality=95)
img = pygame.image.load(fullname).convert()
imgrect = img.get_rect()
screen.blit(img, imgrect)
pygame.mouse.set_visible(False)
pygame.display.flip()
# Elif video:
elif filenamelower.endswith('.mp4') or filenamelower.endswith('.mkv') or filenamelower.endswith('.avi'):
fullname = filesdir + filename
# Create instane of VLC and create reference to movie.
vlcInstance = vlc.Instance("--aout=adummy")
media = vlcInstance.media_new(fullname)
# Create new instance of vlc player
player = vlcInstance.media_player_new()
# Load movie into vlc player instance
player.set_media(media)
# Start movie playback
player.play()
# Do not continue if video not finished
while player.get_state() != vlc.State.Ended:
# Quit if keyboard pressed during video
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pygame.display.quit()
pygame.quit()
sys.exit()
player.stop()
clock.tick(1 / time) # framerate = 0.25 means 1 frame each 4 seconds
# Quit if keyboard pressed during video
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
pygame.display.quit()
pygame.quit()
sys.exit()

Pygame Cannot Blit An Image To A List Of Rectangles

I am working with pygame, and I thought it'd be a super neat idea to make it so that the bricks were automatically generated at the beginning of the game. So I made a function that asks for how many bricks you want generated, and then creates the "bodies" for those bricks in special locations and assigns them to a list. Then, in the while loop, I try to blit those with the according image. However, I get an error I have never seen before.
Error Image
import pygame, sys
import random
import numpy
pygame.init()
def myPopulater(amountToMake, image, width, h):
myBodies = []
for i in range(amountToMake):
r1 = numpy.random.randint(0, width)
r2 = numpy.random.randint(0, h)
myBodies = myBodies + image.get_rect()
myBodies[i].x = r1
myBodies[i].x = r2
return myBodies
width = 500
h = 500
ball = pygame.image.load("c:\\python\\ball.png")
screen = pygame.display.set_mode((width, h))
myList = myPopulater(25, ball, width, h)
while (1):
#WHENEVER SOMETHING HAPPENS
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(black)
for i in range(0, 25):
screen.blit(ball, myList[i])
pygame.display.flip()
From what I can see, you're trying to add the result of image.get_rect() to your myBodies list.
You should use the list.append method to add an element to a list object.
Change this line:
myBodies = myBodies + image.get_rect()
To this:
myBodies.append(image.get_rect())
That will fix your error.

Pygame Using Class to Randomize Image Placements

I'm creating a card/tile memory association game. It is a 4x4 grid of 100x100 pixel images, so 16 images in total are displayed (8 pairs).
For now all I want is for the images to be displayed in a grid in a random order each time the game is started, which I feel I am close to doing using shuffling them in a list in a class and then calling that class from the main function in the while loop.
Here is my code:
# Memory Tiles Game
# A Memory Game which users can flip tiles in and remember their placement to match
# all of the tiles
import pygame, sys, time
from pygame.locals import *
# User-defined classes
class memorygame(object):
def __init__(self):
imagelist = [image1,image2,image3,image4,image5,image6,image7
image8,image9]
shuffle.imagelist
screen.blit(imagelist[0],(0,0))
screen.blit(imagelist[1],(104,0))
screen.blit(imagelist[2],(208,0))
screen.blit(imagelist[3],(312,0))
screen.blit(imagelist[4],(0,104))
screen.blit(imagelist[5],(104,104))
screen.blit(imagelist[6],(208,104))
screen.blit(imagelist[7],(312,104))
shuffle.imagelist
screen.blit(imagelist[0],(0,208))
screen.blit(imagelist[1],(104,208))
screen.blit(imagelist[2],(208,208))
screen.blit(imagelist[3],(312,208))
screen.blit(imagelist[4],(0,312))
screen.blit(imagelist[5],(104,312))
screen.blit(imagelist[6],(208,312))
screen.blit(imagelist[7],(312,312))
# User-defined functions
def main():
black = ( 0, 0, 0)
white = (255,255,255)
red = (100, 0, 0)
green = ( 0,153, 0)
blue = ( 0, 0,255)
image1 = pygame.image.load('image0.bmp')
image2 = pygame.image.load('image1.bmp')
image3 = pygame.image.load('image2.bmp')
image4 = pygame.image.load('image3.bmp')
image5 = pygame.image.load('image4.bmp')
image6 = pygame.image.load('image5.bmp')
image7 = pygame.image.load('image6.bmp')
image8 = pygame.image.load('image7.bmp')
image9 = pygame.image.load('image8.bmp')
w = 500
h = 400
screen = pygame.display.set_mode((w, h))
screen.fill((white))
running = 1
# Initialize pygame
pygame.init()
# Set window size and title, and frame delay
surfaceSize = (500, 400) # example window size
windowTitle = 'Memory Game' # example title
frameDelay = 0.02 # smaller is faster game
# Create the window
surface = pygame.display.set_mode(surfaceSize, 0, 0)
pygame.display.set_caption(windowTitle)
# create and initialize objects
gameOver = False
#center = [200, 200] # example - replace
# Draw objects
# The next line is an example - replace it
#pygame.draw.circle(surface, pygame.Color('green'), center, 50, 0)
# Refresh the display
pygame.display.update()
# Loop forever
while True:
# Check event
event = pygame.event.poll()
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.fill((black))
class memorygame(object)
# Handle additional events
# Update and draw objects for the next frame
gameOver = update(center, surface)
# Refresh the display
pygame.display.update()
# Set the frame speed by pausing between frames
time.sleep(frameDelay)
main()
It doesn't seem to compile, and I am not sure why. I get a syntax error in the shell.
First of all, you forgot a comma at the end of the first line in the imagelist in your memorygame class. Changing that to
imagelist = [image1,image2,image3,image4,image5,image6,image7,
image8,image9]
should fix the first syntax error.
Secondly, I'm not sure what you are trying to achieve with the line class memorygame(object) in your main loop. You probably want to create an instance of the class outside of the while loop and call a function that blits the images inside the while loop.
The image variables are local by the way, the memorygame class will not see them, unless you explicitly make them global variables, or pass them to the __init__ method of memorygame.
Besides, the way you're shuffling the imagelist isn't quite right. You should import random, and then call random.shuffle(imagelist) instead.

Categories