Reputation: 71461
I am attempting to draw multiple items on the screen that will move in random directions. The problem is that when I run the program, the objects blink and flash on the screen, not progress across smoothly. I am rather baffled as I only update the screen once, as recommended by other posts on SO. My code is below:
class Game:
def __init__(self):
self.possible_directions = ["up", "down"]
self.speed_down = 800
self.speed_up = 0
self.asteroid = pygame.image.load("Asteroididadactyl.png")
def def draw_asteroid(self, direction):
if direction == "down":
self.gameDisplay.blit(self.asteroid, (self.options[direction], self.speed_down))
self.speed_down -= 1
elif direction == "up":
self.gameDisplay.blit(self.asteroid, (self.options[direction], self.speed_up))
self.speed_up += 1
def player(self):
pygame.init()
self.gameDisplay = pygame.display.set_mode((1000, 900))
pygame.display.set_caption("Asteroid belt")
while True:
for event in pygame.event.get():
#move main object.
self.choice = random.choice(self.possible_directions)
self.draw_asteroid(self.choice)
pygame.display.flip()
Upvotes: 1
Views: 670
Reputation: 20448
The draw_asteroid
method blits the asteroid image depending on the direction
that was passed, and since you pass a random direction each frame, the image is sometimes blitted at the up position (which is called self.speed_up
) and other times at the down position (self.speed_down
), so it appears to flicker.
I'd recommend to change the code completely and rather use objects or pygame sprites with vectors for the velocity and position which you can set to random values during the instantiation. Then first update the objects altogether in the while loop and finally blit them onto the display.
Edit: Here's a minimal example (you could also use pygame.sprite.Sprite
s and sprite groups instead of the list).
import sys
import random
import pygame as pg
class Asteroid:
def __init__(self):
self.image = pg.Surface((50, 50))
self.image.fill((150, 60, 10))
self.pos = pg.math.Vector2(random.randrange(1230),
random.randrange(750))
self.vel = pg.math.Vector2(random.uniform(-5, 5),
random.uniform(-5, 5))
def update(self):
self.pos += self.vel
class Game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((1280, 800))
self.clock = pg.time.Clock()
self.bg_color = pg.Color(20, 20, 20)
self.asteroids = [Asteroid() for _ in range(10)]
self.done = False
def run(self):
while not self.done:
for event in pg.event.get():
if event.type == pg.QUIT:
self.done = True
for asteroid in self.asteroids:
asteroid.update()
self.screen.fill(self.bg_color)
for asteroid in self.asteroids:
self.screen.blit(asteroid.image, asteroid.pos)
pg.display.flip()
self.clock.tick(30)
Game().run()
pg.quit()
sys.exit()
Upvotes: 1