Caitlin Lamb
Caitlin Lamb

Reputation: 23

Python only running while loop once

import pygame

r_colour = (200, 100,100)
bg_colour = (0,175,200)
(width, height) = (600, 600)

screen = pygame.display.set_mode((width, height))
screen.fill(bg_colour)
pygame.draw.rect(screen, r_colour, (30, 30, 100, 100), 0)

pygame.display.flip()

running = True
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_s:
                screen.fill(bg_colour)
                pygame.draw.rect(screen, r_colour, (20, 30, 100, 100), 0)
                pygame.display.update()


if running == True:
      for event in pygame.event.get():
          if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_s:
                    screen.fill(bg_colour)
                    pygame.draw.rect(screen, r_colour, (20, 30, 100, 100), 0)
                    pygame.display.update()



while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      break
      running = False



pygame.quit()

I am trying to get the red square to move when pressing the 's' key, not sure as to why it only moves once and then stops. Very new to programming, so I am sorry, if it's long or hard to read.

Upvotes: 2

Views: 205

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

A typical application has 1 single application loop. The application loop does:

  • handle the events and changes states dependent on the events
  • clears the display
  • draw the scene
  • update the display

The KEYDOWY event occurs once when a key is pressed, but it does not occur continuously when a key is hold down.
For a continuously movement you can get the state of the keys by pygame.key.get_pressed():

keys = pygame.key.get_pressed()

e.g. If the state of s is pressed can be evaluated by keys[pygame.K_s].

Add coordinates (x, y) for the position of the rectangle. Continuously manipulate the position in the main application loop, when a key is pressed.

e.g.
Increment x if d is pressed and decrement x if a is pressed.
Increment y if s is pressed and decrement y if w is pressed:

import pygame

r_colour = (200, 100,100)
bg_colour = (0,175,200)
(width, height) = (600, 600)
x, y = 20, 30

screen = pygame.display.set_mode((width, height))

running = True
while running:

    # handle the events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # change coordinates
    keys = pygame.key.get_pressed()
    if keys[pygame.K_d]:
        x += 1
    if keys[pygame.K_a]:
        x -= 1
    if keys[pygame.K_s]:
        y += 1
    if keys[pygame.K_w]:
        y -= 1

    # clear the display
    screen.fill(bg_colour)
    # draw the scene
    pygame.draw.rect(screen, r_colour, (x, y, 100, 100), 0)
    # update the display
    pygame.display.update()

pygame.quit()

Upvotes: 4

Related Questions