how can I get the mouse and keyboard to work simultaneously in Pygame?

Viewed 222

I've written a simple code using pygame just to test a situation where a player uses key presses and mouse motion simultaneously. However, I'm unable to move the mouse while pressing a key. The code is below:

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

pygame.display.set_mode((640, 480))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    key = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pos()

    pygame.display.update()

Thank you very much. Despite the simplicity of the question, Google couldn't find anything.

2 Answers

The supplied program (at least for me) is quite capable of handling the mouse movement and detecting key-presses simultaneously.

A simple addition of logging information will confirm this:

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

pygame.display.set_mode((640, 480))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    keys  = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pos()

    if ( keys[pygame.K_UP] ):
        print( "up, mouse@ "+str( mouse ), end="     \r" )
    else:
        print( "not up, mouse@ "+str( mouse ), end="     \r" )

    pygame.display.update()

Run this script, move the mouse, periodically pressing ↑.

I can quite easily switch between this outputting up and not up, with the mouse constantly moving.

If this is not the case for you, then likely it is some issue with Pygame and your operating environment. I would re-install PyGame in this case, ensuring a modern version of both Python and PyGame.

In your for loop pooling events, detect mouse and key inputs there

eg.

    for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                      Do Something
    
                if event.type == pygame.KEYDOWN:
                      if event.key == pygame.K_w:
                           Do Something else

Related