im trying to draw a shape with pygame.draw.rect() when i press a key but the shape wont stay when another key or event happen and also the shape moves where ever the ship moves but i only want it to move when i shot it and stay in that place and the shape wont stay on the surface after i release that key
import pygame
pygame.init()
display_width = 800
display_hight = 600
colors = {"black": (0, 0, 0), "white": (255, 255, 255), "green": (0, 255, 0), "red": (255, 0, 0), "blue": (0, 0, 255)}
ship_width = 75
ship_hight = 72
gameDisplay = pygame.display.set_mode((display_width, display_hight))
pygame.display.set_caption('test')
clock = pygame.time.Clock()
shipimg = pygame.image.load('D:\\index.png')
def ship(x, y):
gameDisplay.blit(shipimg, (x, y))
def Game_Loop():
x = (display_width * 0.41)
y = (display_hight * 0.8)
x_change = 0
fire_start_y = y - ship_hight
fire_start_x = x + (ship_width / 2)
GameExit = False
while not GameExit:
if fire_start_y < 0:
fire_start_y = y - 30
for event in pygame.event.get():
if event.type == pygame.QUIT:
GameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(colors["white"])
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.draw.rect(gameDisplay, colors["green"], [fire_start_x, fire_start_y, 2, 10])
ship(x, y)
if x <= 0 or x >= display_width - ship_width:
x -= x_change
fire_start_y -= 5
fire_start_x = x + (ship_width / 2)
pygame.display.flip()
clock.tick(60)
Game_Loop()
pygame.quit()
i tried this code to manage the disappearing problem but it made it worse as it ever lopping after i press the key once
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.draw.rect(gameDisplay, colors["green"], [fire_start_x, fire_start_y, 2, 10])
fire_start_x = x + (ship_width / 2)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_x:
pygame.draw.rect(gameDisplay, colors["green"], [fire_start_x, fire_start_y, 2, 10])
fire_start_x = x + (ship_width / 2)