Sign in to follow this  
Zaris

python and event.get()

Recommended Posts

When I run this code it seems to wait till an event happens before adding new pixels to the screen. What can I do to get it to run until I click the mouse button.
[source lang = "python"]
import pygame
from pygame.locals import *
from random import randint

pygame.init()
screen = pygame.display.set_mode((640,480), FULLSCREEN|HWSURFACE|DOUBLEBUF, 32)

gameRunning = True

while gameRunning:

    for event in pygame.event.get():
        if event.type == MOUSEBUTTONDOWN:
            gameRunning = False

        rand_col = (randint(0, 255), randint(0,255), randint(0, 255))
        screen.lock()
        for _ in xrange(100):
            rand_pos = (randint(0, 639), randint(0, 479))
            screen.set_at(rand_pos, rand_col)
        screen.unlock()
        pygame.display.flip()

pygame.display.quit()


Share this post


Link to post
Share on other sites
You should google "pygame event handling" and study the articles you find. then, you can write code to perform a task when the user clicks, presses buttons, closes the window etc.

p.s. you should pick a better title for your thread, such as "how do I handle events in pygame".

Share this post


Link to post
Share on other sites
You've made a simple mistake, by putting the rendering code in the same scope as your event handling code. That is, the lines from 'rand_col = (randint(0, 255), randint(0,255), randint(0, 255))' to 'pygame.display.flip()' fall within the for loop that checks for events. If there are no events to process during a frame, the rendering code doesn't get executed either. That's clearly not what you want. Luckily, the problem is easy to correct:

import pygame
from pygame.locals import *
from random import randint

pygame.init()
screen = pygame.display.set_mode((640,480), FULLSCREEN|HWSURFACE|DOUBLEBUF, 32)

gameRunning = True

while gameRunning:

for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
gameRunning = False

rand_col = (randint(0, 255), randint(0,255), randint(0, 255))
screen.lock()
for _ in xrange(100):
rand_pos = (randint(0, 639), randint(0, 479))
screen.set_at(rand_pos, rand_col)
screen.unlock()
pygame.display.flip()

pygame.display.quit()

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this