Heres my code
import pygame, os os.environ["SDL_VIDEO_CENTERED"] = "1" pygame.init() win = pygame.display d = win.set_mode((1200, 600)) class player: def __init__(self, x, y, height, width): self.x = x self.y = y self.height = height self.width = width self.speed = 2 def draw(self): pygame.draw.rect(d, (0, 0, 0), (self.x, self.y, self.width, self.height)) def move_left(self): self.x -= self.speed def move_right(self): self.x += self.speed class bullet: def __init__(self): self.radius = 10 self.speed = 20 def shoot(self): x = p.x y = p.y self.shooting = True while self.shooting: d.fill((98, 98, 98)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() y -= self.speed pygame.draw.circle(d, (255, 0, 0), (x, y), self.radius) pygame.time.Clock().tick(100) win.update() if y <= 0: self.shooting = False b = bullet() p = player(600, 500, 50, 30) while True: d.fill((98, 98, 98)) p.draw() for event in pygame.event.get(): pass if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: b.shoot() if event.key == pygame.K_LEFT: p.move_left() if event.key == pygame.K_RIGHT: p.move_right() win.update()
This is what i could come up with after a few Trial and errors but it is really uneffective. Firstly the player disappers when i press space bar. I guess this is obvious as i have a different loops for shooting and player but i dont know how to get around it and implement both shooting and player in the same loop.
The second probllem i am having is breaking the
while self.shooting: loop. I tried breaking it when y reaches a certain point by doing this
if y <= 0: self.shooting = False
but this dosent break. Instead, it restarts the loop all over again.
Another weird problem i am having is that everytime i move mouse(slightly fast) or press a bunch of buttons at once, it breaks the
while self.shooting loop.