Programming Pygame so that I can press several keys at once to make my character move diagonally

I am trying to program using Python. I am new to Python and computer programming in general. I want to be able to develop brilliant games, etc. I plan to learn C ++ later, but for now I will just stick with python. So the problem is that I'm trying to get my character to move diagonally on the screen when the user presses the K_UP key and the K_RIGHT key or the K_UP key and the K_DOWN key, etc. Here is my code for character movement (event handling):

1. #Event Handling
2. for event in pygame.event.get():
3.     if event.type == pygame.QUIT: 
4.         sys.exit()
5.     elif (event.type == KEYDOWN):
6.         if ((event.key == K_ESCAPE)
7.             or (event.key == K_q)):
8.             sys.exit()
9.         if (event.key == K_UP):
10.            self.char_y = self.char_y - 10
11.        if (event.key == K_DOWN):
12.            self.char_y = self.char_y + 10
13.        if (event.key == K_RIGHT):
14.            self.char_x = self.char_x + 10
15.        if (event.key == K_LEFT):
16.            self.char_x = self.char_x - 10

Thanks in advance.

+5
source share
1 answer

You can do this via pygame.key.get_pressed () :

keys = pygame.key.get_pressed()

if keys[K_LEFT]:
    self.char_x += 10

if keys[K_RIGHT]:
    self.char_x -= 10

if keys[K_UP]:
    self.char_y -= 10

if keys[K_DOWN]:
    self.char_y += 10
+6
source

All Articles