I need to be able to move the mouse around while I am handling keydown events.
How do I do this?
Here is the basic code I am using right now:
import pygame, sys
from pygame.locals import *
pygame.init()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == USEREVENT + 1:
rotate = True;
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == K_a:
moveX = -1*moveSpeed
elif event.key == K_RIGHT or event.key == K_d:
moveX = moveSpeed
if event.key == K_DOWN or event.key == K_s:
moveY = moveSpeed
elif event.key == K_UP or event.key == K_w:
moveY = -1*moveSpeed
I can’t move the mouse while the following script is running and I am pressing a key down..
The main problem with your loop is that you have no delay between “frames” – that is that you simply cycle over the event loop at maximum CPU speed – this makes a key press generate lots (lots meaning probably around millions magnitude) of key-down events that are read.
So:
pygame.time.delay(x)inside your whiel loop, with xsomewhere between 15 and 100 – this will give you so many
miliseconds of pause between interations
pygame.event.pump()call inside the loop – this will keep he eventbuffer flowing hapilly and prevent subtle bad behavior across
different systems
there is absotely no need of such a thing as “
-1*moveSpeed” toobtain the negative value of a variable – just use “
-moveSpeed”instead.
Also, this should stop the freezing, but pygame can only capture mouse or key events inside its own display window – which you are not initializing – you will have to call
pygame.display.set_modeto actually see something.