0

I am trying to make code to move a rectangle by pressing a key. In my code I made a while loop to keep drawing a rectangle that moves to the right in steps of 10 pixels but my progrem only shows the drawing execution of the end of the while loop.

Does anybody knows what I am doing wrong or how to fix it.

See my code below:

x=10
pygame.draw.rect(DISPLAYSURF, GREEN, (0, 10, 10,10))



   while True:
      for event in pygame.event.get():
      if event.type == QUIT:
          pygame.quit()
          sys.exit()
      elif event.type == pygame.KEYDOWN:
          if event.key == pygame.K_RIGHT:
              while x<=380:
                  pygame.time.wait(100)
                  x = x + 20
                  print(x)
                  DISPLAYSURF.fill(BLACK)
                  pygame.draw.rect(DISPLAYSURF, GREEN, (x, 10, 10,10))



pygame.display.update()
ninja
  • 55
  • 1
  • 1
  • 6

2 Answers2

2

See Pygame window not responding after a few seconds. Note, the display is updated when pygame.display.update(), but to make the timing and display update proper work, you've to handle the events between the updates of the display by either pygame.event.get() or pygame.event.pump(). Avoid loops which do some drawing inside the game loop. Use the game loop to perform the animations.

You don't need the inner while loop at all. You've a game loop. Add a state move and initialize it by False.

move = False

When the key is pressed then change the state to True:

if event.key == pygame.K_RIGHT:
    move = True

If move is stated and as long x <= 380 increment x:

while True:

    # [...]

    if move and x <= 380:
        x += 20

The game loop should look like this:

x = 0
move = False
while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                move = True

    if move and x <= 380:
        x += 20

    pygame.time.wait(100)
                  
    DISPLAYSURF.fill(BLACK)
    pygame.draw.rect(DISPLAYSURF, GREEN, (x, 10, 10,10))
    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
1

You need to do do pygame.display.update() every time you draw. Move that line to be called inside your while loop after pygame.draw.rect

Kevin Welch
  • 1,488
  • 1
  • 9
  • 18