Hi I wanted to make a sprite for a planet, that either spawns at the top of the screen, like halfway on the screen so you only get half the planet, or on the bottom. but I want it to randomly choose to be on the top of the screen or on the bottom. I can't figure it out. my screen is width 1000 and height 500.
class Planets(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_original = random.choice(planet_images)
self.image = pygame.transform.scale(self.image_original, (400, 400))
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width * .95 / 2)
# Make the hitbox visible --->
pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.x = (1000)
self.rect.y = -200
self.speedy = 0
self.speedx = -2
def update(self):
# killing and spawning new enemies when they go of the screen
self.rect.x = self.speedx
self.rect.y = self.speedy
if self.rect.left < - 1400:
self.kill()
new_planets = Planets()
all_sprites.add(new_planets)
planets.add(new_planets)
CodePudding user response:
You could use random.choice
again like you did for the images before.
This time you build a list of desired positions on the screen (as tuple with x and y coord) and let random choose where to spawn
lst_of_coord = [(1000, -200), (500, 500)] # each tuple for a x,y position on your screen
self.rect.x, self.rect.y = random.choice(lst_of_coord)
CodePudding user response:
Thankyou very very much. the solution worked. It now spawns randomly on one of the 2 locations
class Planets(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_original = random.choice(planet_images)
self.image = pygame.transform.scale(self.image_original, (400, 400))
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width * .95 / 2)
# Make the hitbox visible --->
pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
list_of_cords = [(1000, -200), (1000, 400)]
self.rect.x, self.rect.y = random.choice(list_of_cords)
self.speedy = 0
self.speedx = -2
def update(self):
# killing and spawning new enemies when they go of the screen
self.rect.x = self.speedx
self.rect.y = self.speedy
if self.rect.left < - 1400:
self.kill()
new_planets = Planets()
all_sprites.add(new_planets)
planets.add(new_planets)