2

i am getting dragging veiw and also not moving continuously till press left or right arrow

 import pygame
 # Set screen size
 screen_size = (800, 600)
 screen = pygame.display.set_mode(screen_size)

 # display caption and icon initilization
 pygame.display.set_caption("Space War")
 icon = pygame.image.load("rocketIcon.png")
 pygame.display.set_icon(icon)

 # loading backgound on display screen
 background = pygame.image.load("Planet_Space_Universe_Fantacy_Wallpaper.jpg")

 # player Initilization
 playerImg = pygame.image.load("rocket.png")
 playerX = 370
 playerY = 480
 playerX_change = 5
 # player


 def player(x, y):
    screen.blit(playerImg, [x, y])
 # enemy
 # bullet

 # continuity loop
 clock = pygame.time.Clock()
 running = True
 while running:
    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        running = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            playerX -= playerX_change

player(playerX, playerY)
clock.tick(120)
pygame.display.update()

Dragging effect during pressing for move

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

1

You have to clear the display or draw the background in every frame. The entire scene is redraw in each frame and everything that is drawn is drawn on the display surface. Therefore the display needs to be cleared at the begin of every frame in the application loop:

while running:
    # [...]

    screen.blit(background, (0, 0))
    player(playerX, playerY)
    pygame.display.update()
    clock.tick(120)

Use pygame.key.get_pressed() instead of the KEYDOWN event.

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.

pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.

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

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerX -= playerX_change
    if keys[pygame.K_RIGHT]:
        playerX += playerX_change

    screen.blit(background, (0, 0))
    player(playerX, playerY)
    pygame.display.update()
    clock.tick(120)

See also How to get if a key is pressed pygame.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174