[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[pygame] Capturing Multiple Keyboard Inputs



Hello everyone,
I am testing my understanding of the pygame.key module by creating a program
that pans the sound of a car engine and raises/lowers its frequency. While
the individual keys do exactly what they're supposed to, I run into a big
problem when I try to do two things at once. For example, if I hold the up
arrow, the frequency of the sound rises with no problem. If I then hold down
the left arrow while still holding up, however, the frequency stops rising
and the pan begins to adjust itself. How can I make both keys carry out
their assigned task at the same time?
As a side note, aside from exporting the redundant code below into its own
methods, are there any other ways to check for multiple keys without giving
each its own if check?
Ugly code is below:

import pygame
from sound_lib.stream import FileStream
from sound_lib.output import Output

def main():
	clock = pygame.time.Clock()
	o = Output()
	sound = FileStream(file="sounds/car.wav")
	screen = pygame.display.set_mode((640, 400))
	sound.looping = True
	sound.play()
	pygame.key.set_repeat(50, 50)
	while(True):
		for event in pygame.event.get():
			if event.type == pygame.KEYDOWN:
				if event.key == pygame.K_UP:
					sound.frequency += 200
				if event.key == pygame.K_DOWN:
					sound.frequency -= 200
				if event.key == pygame.K_LEFT:
					if sound.pan <= -0.9:
						sound.pan = -0.9
					else:
						sound.pan -= 0.1
				if event.key == pygame.K_RIGHT:
					if sound.pan >= 0.9:
						sound.pan = 0.9
					else:
						sound.pan += 0.1
				if event.key == pygame.K_ESCAPE:
					exit()
		clock.tick(10)

if __name__ == '__main__':
	main()

Thanks,
Ryan