Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
event.key == K_r:
#1
I am new to pygame, so I am looking at the docs here and trying each bit out in Idle.

My little function rect11() works OK, but it doesn't refresh when I press the right arrow key.

I presume K_r means the right arrow key, but nothing happens when I press the right arrow key.

Do you know why??

def rect11():
    pygame.init()
    width = 600
    height = 600
    SIZE = (500, 200)

    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)

    YELLOW = (255, 255, 0)
    MAGENTA = (255, 0, 255)
    CYAN = (0, 255, 255)

    BLACK = (0, 0, 0)
    GRAY = (150, 150, 150)
    WHITE = (255, 255, 255)

    def random_point():
        x = randint(0, width)
        y = randint(0, height)
        return (x, y)

    def random_rects(n):
        rects = []
        for i in range(n):
            r = Rect(random_point(), (20, 20))
            rects.append(r)
        return rects

    screen = pygame.display.set_mode((width, height))
    
    running = True
    
    rect = Rect(100, 50, 200, 80)
    
    n = 50
    rects = random_rects(n)

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            
            if event.type == KEYDOWN:
                if event.key == K_r:
                    rects = random_rects(n)
       
        screen.fill(GRAY)
        pygame.draw.rect(screen, GREEN, rect, 1)

        for r in rects:
            if rect.colliderect(r):
                pygame.draw.rect(screen, RED, r, 2)
            else:
                pygame.draw.rect(screen, BLUE, r, 1)
        
        pygame.display.flip()


    pygame.quit()
Reply
#2
(Jul-04-2021, 10:49 AM)Pedroski55 Wrote: I presume K_r means the right arrow key, but nothing happens when I press the right arrow key.
Check out the pygame documentation. It is a go to must when your programming in pygame. Everything starts with K_ as it is keyboard. K_r is "r". K_RIGHT is right arrow.


As a side note: I think it is better and more adaptable to organize things in classes as opposed to nested functions.
Pedroski55 likes this post
Reply
#3
Thanks, in the cold light of morning that was very clear.

All the other examples used mainly the arrow keys, I suppose I just assumed this would too!!

Bad assumption!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020