I am trying to clean up my code, and am moving scripts to different files. I want put my image (in this case, meteors) in random places, with random rotation and size. I can get it to go to random places, but just can't figure out how to scale and rotate it randomly. This is what I used to use which gave me what I wanted, a meteor in a random size and rotation in a random place.
import pygame, random
screen = pygame.display.set_mode((1280, 720))
pic = pygame.image.load('assets/meteor.png').convert_alpha()
rotimage = pygame.transform.rotozoom(pic, random.randint(0, 359), random.randint(1, 2))
random_x = random.randint(0, 1280)
random_y = random.randint(0, 720)
while True:
screen.blit(rotimage, (random_x, random_y))
pygame.display.update()
It worked fine like this, but I have no clue on how to apply this in another file. My second python file looks something like this.
import random
import pygame
display_width = 1280
display_height = 720
rotation = random.randint(0, 359)
size = random.randint(1, 2)
pic = pygame.image.load('assets/meteor.png')
pygame.init()
class Meteor(pygame.sprite.Sprite):
def __init__(self, x=0, y=0):
pygame.sprite.Sprite.__init__(self)
self.image = pic
self.rect = self.image.get_rect()
self.rect.center = (x, y)
all_meteors = pygame.sprite.Group()
for i in range(3):
new_x = random.randrange(0, display_width)
new_y = random.randrange(0, display_height)
pygame.transform.rotozoom(pic, rotation, size) # How do I put this in
all_meteors.add(Meteor(new_x, new_y)) #this only allows x and y
My new main file looks something like this
while True:
meteors.all_meteors.update()
meteors.all_meteors.draw(screen)
pygame.display.update()
How would I get the image to randomly rotate and scale within the meteor file?
I think creating a Meteor object first, then updating it's pic before adding it to all_meteors should do the trick. Perhaps replace the for-loop with something like this:
for i in range(3):
new_x = random.randrange(0, display_width)
new_y = random.randrange(0, display_height)
met = Meteor(new_x, new_y)
rotation = random.randint(0, 359) # Some line here to pick a random rotation
size = random.randint(1, 3) # some line here to pick a random scale
met.pic = pygame.transform.rotozoom(met.pic, rotation, size) # How do I put this in
all_meteors.add(met) #this only allows x and y
Note: I forget if pygame.transform.rotozoom()
is an in-place operation. If so, then replace met.pic = pygame.transform.rotozoom()
with pygame.transform.rotozoom()
-- remove the met.pic =
.
Another way to go about this would be to adjust the class directly:
class Meteor(pygame.sprite.Sprite):
def __init__(self, x=0, y=0):
pygame.sprite.Sprite.__init__(self)
self.rotation = random.randint(0, 359)
self.size = random.randint(1, 2)
self.image = pic
self.image = pygame.transform.rotozoom(self.image, self.rotation, self.size)
self.rect = self.image.get_rect()
self.rect.center = (x, y)