I make a simple program that will click on the arrows to move the image. I need the sprite to move while the arrow is squeezed. The problem is that now if I click on the arrow, the sprite moves once, and does not respond to a key hold. I would be grateful for the help.

import pygame import os def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error as message: print('Cannot load image:', name) raise SystemExit(message) image = image.convert_alpha() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey) return image pygame.init() size = width, height = 501, 501 screen = pygame.display.set_mode(size) all_sprites = pygame.sprite.Group() hero_image = load_image("bomb.png") hero = pygame.sprite.Sprite(all_sprites) hero.image = hero_image hero.rect = hero.image.get_rect() all_sprites.add(hero) running = True while running: for event in pygame.event.get(): # при закрытии окна if event.type == pygame.QUIT: running = False key = pygame.key.get_pressed() if event.type == pygame.KEYUP: f = event.key if event.key == 273: hero.rect.top -= 10 if event.key == 274: hero.rect.top += 10 if event.key == 275: hero.rect.left += 10 if event.key == 276: hero.rect.left -= 10 screen.fill((0, 0, 78)) all_sprites.draw(screen) pygame.display.flip() pygame.quit() 

    1 answer 1

    To move an object all the time while the arrow is pressed, you need to create 4 variables, under the names "left, up, right, down" and set each of them to false. Then in the for event in pygame.event.get() loop for event in pygame.event.get() check:

     if event.type == pygame.KEYDOWN: if event.key == K_UP: up = true if event.key == K_DOWN: down = true if event.key == K_RIGHT: right = true if event.key == K_LEFT: left = true if event.type == pygame.KEYUP: if event.key == pygame.K_UP: up = false if event.key == pygame.K_DOWN: down = false if event.key == pygame.K_RIGHT: right = false if event.key == pygame.K_LEFT: left = false 

    Then, in the while running check the values ​​of the variables "left, up, right, down", if they have a true value, then move the hero object in a certain direction.