Ved Pawar
Ved Pawar

Reputation: 148

My space ship keeps on moving even when i don't press the side keys

import pygame
#initialize the screen
pygame.init()

#create the screen
screen = pygame.display.set_mode((800, 700))

#tile and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("spaceship.png")
pygame.display.set_icon(icon)

#Player
playerImg = pygame.image.load("player.png")
playerx = 370
playery = 600
playerx_change = 0.39

def player(x,y):
    screen.blit(playerImg, (x,y))

running = True
while running:

    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        #keystroke
        if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_LEFT:
                playerx_change = -0.39
           if event.key== pygame.K_RIGHT:
                playerx_change = 0.39
           if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.type == pygame.K_RIGHT:
                    playerx_change = 0
            

    playerx += playerx_change
    player(playerx,playery)
    pygame.display.update() 

My spaceship keeps on moving even when i don't press side keys. i am creating space invaders using python and pygame.the ship doesn't stop as it should have according to the code. i use the community version of visual studio 2019.

Upvotes: 2

Views: 88

Answers (1)

Rabbid76
Rabbid76

Reputation: 210998

There is a typo in your code event.key == pygame.K_RIGHT rather than event.type == pygame.K_RIGHT.
Further more, there is an Indentation issue:

running = True
while running:
    # [...]  

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

        #keystroke
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerx_change = -0.39
            if event.key== pygame.K_RIGHT:
                playerx_change = 0.39
        
        #<--| INDENTATION
        if event.type == pygame.KEYUP:
           if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerx_change = 0

Anyway I recommend to use pygame.key.get_pressed() rather than the key events for the movement:

running = True
while running:

    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

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

    player(playerx,playery)
    pygame.display.update() 

The key events KEYDOWN and KEYUP occur once when a key is pressed respectively released, but the states which are returned by pygame.key.get_pressed() are True as long a key is hold down.

Upvotes: 1

Related Questions