0

when I spam the arrow keys, nothing works and my square will not budge. this is for a python lesson homework and i am really in need of help, so anyone who know why? if so, please tell me... please

    import pygame
    pygame.init()
    scrlengthX = 640
    scrlengthY = 480
    b = 20

    x = (scrlengthX-b)/2
    y = (scrlengthY-b)/2
    r = pygame.Rect(x,y,b,b)
    #this explains where the square is supposed to be
    while True:
        screen = pygame.display.set_mode([scrlengthX,scrlengthY])
        # size of the screen
        def draw():

            screen.fill([0,0,255])

            r = pygame.Rect(x,y,b,b)


            pygame.draw.rect(screen,(0,0,0), r)
            pygame.display.flip()

        a = 1
        while a == 1:
            draw()
                e = pygame.event.get(pygame.QUIT)
            print(e)
            if len(e) > 0:
                pygame.quit()

        k = pygame.event.get(pygame.KEYDOWN)
        for i in k:
            if i.key == pygame.K_UP:
                y = y-5
            if i.key == pygame.K_DOWN:
                y = y+5
            if i.key == pygame.K_LEFT:
                x = x-5
            if i.key == pygame.K_RIGHT:
                x = x+5
            # button detecting, but it does not work :(
            # this is where everything goes wrong, anybody help?

    pygame.quit()
dejanualex
  • 3,872
  • 6
  • 22
  • 37
  • Welcome to Stack Overflow! Glad to have you join us. I might suggest adding the tag `pygame` to your post to help more relevant people find your question, as well. – Randall Arms Feb 05 '21 at 12:41

2 Answers2

0

Try this subtle change:

k = pygame.event.get()
for i in k:
    if i.type == pygame.KEYDOWN:
        if i.key == pygame.K_UP:
            y -= 5
        if i.key == pygame.K_DOWN:
            y += 5
        if i.key == pygame.K_LEFT:
            x -= 5
        if i.key == pygame.K_RIGHT:
            x += 5
Randall Arms
  • 407
  • 1
  • 5
  • 22
0

Did you possibly mess up indentation?

As far as I read it, your program will only leave the while a==1 loop when quitting, but all the input handling is behind that loop.

I think, you might want to increase indentation of the code starting with the line k=....

With that change, the code works for me.

dasmy
  • 569
  • 4
  • 10