1
\$\begingroup\$

I tried to move my obstacle with the event type KEYDOWN, but it seems it is not working.

This is my code.

import pygame
import time

pygame.init()
res=(500,500)
blue_color=(0,0,255)
black_color=(0,0,0)
red_color=(255,0,0)
title=pygame.display.set_caption("Pygame Game")
screen=pygame.display.set_mode(res,pygame.RESIZABLE)

coord_rec=pygame.Rect(250,2,20,20)
coord_obs=pygame.Rect(150,450,200,20)
rectangle=pygame.draw.rect(screen,blue_color,coord_rec)
obstacle= pygame.draw.rect(screen,red_color,coord_obs)

pygame.display.flip()
launched= True
while launched:
    for event in pygame.event.get():
        if event.type== pygame.QUIT:
            launched=False
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_LEFT:
                    coord_obs.x+=10
            elif  event.key==pygame.K_RIGHT:
                    coord_obs.x +=-10
  

            
    while not coord_rec.colliderect(coord_obs):
              time.sleep(0.0500)
              screen.fill(black_color)
              coord_rec.y+=10
              rectangle=pygame.draw.rect(screen, blue_color, coord_rec)
              obstacle=pygame.draw.rect(screen, red_color, coord_obs)
              pygame.display.flip()
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

I suspect your problem is that you're only reacting to KEYDOWN, rather than tracking which keys are down during any given frame. As written, your players have to beat on the arrow keys as fast as possible. I can usually manage 7 key presses per second, but I'm not as fast as I used to be.

So you need to track which keys are down, which means tracking both down and up events, and maintaining a collection of keys currently down. You would then react to which keys are down, rather than directly acting due to the events. As a means of future proofing, I suggest you track all key presses, not just your current controls, that way when you want to configurable controls (wasd instead of arrows for example), you don't have to mess with your event handling, just the way you query the list of currently pressed keys.

I also strongly suggest ditching your hardcoded velocities and 20fps, in favor of tracking how long its been since the last frame and scaling a "per second" velocity. You should probably track your locations as floating point numbers, and then truncate or round them to integers before drawing them. Adding anything less than 1 to a number as a truncated int will never change the given object's position.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .