1
def playing():
    global in_game
    x = 250
    y = 250
    width = 10
    height = 10
    white = (255, 255, 255)
    black = (0, 0, 0)
    keys = pygame.key.get_pressed()
    while in_game:
        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                in_game = False

        if keys[pygame.K_UP]:
            y -= 1
        elif keys[pygame.K_DOWN]:
            y += 1
        elif keys[pygame.K_LEFT]:
            x -= 1
        elif keys[pygame.K_RIGHT]:
            x += 1

        win.fill(white)
        pygame.draw.rect(win, black, (x, y, width, height))
        pygame.display.flip()

In This code I put x and y as the horizontal and vertical movement. I called my function at the bottom of the screen.

smci
  • 32,567
  • 20
  • 113
  • 146
  • Your indentation needs to be fixed. – xilpex May 16 '20 at 17:28
  • By the way, a style tip: you don't really need `in_game` variable and `while in_game:` loop can reduce to `while True`, and you can do `break` to exit the loop. Or `return` if you want to return from the function entirely. CodeReview.SE is a good site for tips on working code. – smci May 16 '20 at 17:58

1 Answers1

2

pygame.key.get_pressed() returns a list of boolean values representing the current state of the keys. You have to evaluate the states of the keys continuously in the application loop, rather than once before the loop:

# keys = pygame.key.get_pressed() <----- DELETE
while in_game:
    for event in pygame.event.get():
        print(event)
        if event.type == pygame.QUIT:
            in_game = False

    keys = pygame.key.get_pressed() # <----- INSERT

    if keys[pygame.K_UP]:
        y -= 1
    elif keys[pygame.K_DOWN]:
        y += 1
    elif keys[pygame.K_LEFT]:
        x -= 1
    elif keys[pygame.K_RIGHT]:
        x += 1

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174