How to intoduce randomness in pygame?

Question:

I’m trying to create a starry night in pygame. It was actually given as exercise in the book I’m following Python Crash Course by Eric. I have so far created a co-ordinated fleet of stars but according to the task, I need to place stars randomly using randint. I can’t conceive how to make it? I’m a beginner. Its python 3

I have so far tried to delete the available space and tried to use to rand int but I have failed.

def get_number_stars(s_settings, star_width):
    """Detertmine the number of stars that fit in a row."""
    available_space_x = s_settings.screen_width - 2 * star_width
    number_stars_x = int(available_space_x / (2 * star_width))
    return number_stars_x


def get_number_rows(s_settings, star_height):
    """Determine the number of stars that fit on the screen."""
    avaialble_space_y = (s_settings.screen_height - (3 * star_height))
    number_rows = int(avaialble_space_y / (2 * star_height))
    return number_rows


def create_star(s_settings, screen, stars, star_number, row_number):
    """Create an star and place it in the row."""
    star = Star(screen, s_settings)
    star_width = star.rect.width
    star.x = star_width + 2 * star_width * star_number
    star.rect.y = star.rect.height + 3 * star.rect.height * row_number
    star.rect.x = star.x
    stars.add(star)


def create_stars_group(s_settings, screen, stars):
    """Create a full group of aliens."""
    # Create an star and find the number of stars in each row
    star = Star(screen, s_settings)
    number_stars_x = get_number_stars(s_settings, star.rect.width)
    number_rows = get_number_rows(s_settings, star.rect.height)

    # Create the first row of stars
    for row_number in range(number_rows):
        for star_number in range(number_stars_x):
            create_star(s_settings, screen, stars, star_number, row_number)

I need a random placed stars but all I’m getting is co ordinated stars as in the code. Thanks for the help!

Asked By: the_paste_rover

||

Answers:

Right now, you are creating a fixed number of stars for each row:

number_stars_x = int(available_space_x / (2 * star_width))

try making this a number between 0 and some max number!

# number_stars_x = randint(0, max_number)
# Note: // will produce an int in python3
number_stars_x = randint(0, available_space_x // (2 * star_width))

This will already make it look random!
Placing the location randomly is also possible, but you will need code to make sure they do not overlap as well.

In that case, you can start with

star.x = randint(star_width, available_space_x - star_width)
Answered By: Mars

Simply use randint(min, max). It generates a number between min and max.

num_stars = randint(0, available_space_x / (2 * star_width))

For more complex usage of random number generation its recommended to use the random module (Shuffle lists, floating point numbers, choices, …).

import random
num_stars = random.randrange(0, available_space_x / (2 * star_width))
Answered By: Banneisen

It depends a lot on what you mean by “random”.

You can either, put a random number of stars as @Mars well suggested.

You can also predefine some “stars spot”, and fill any number of them with the random.choice method

possible_x_stars = [star_width + 2 * star_width * i for i in star_number]
next_star.x = random.choice(possible_x_stars) # You will need to remove the chosen value afterward.

Another method can be to do a while loop (if there is not too many stars), such as:

number_of_stars = 0
tries = 0
placed_stars = []
while number_of_stars < maximum_stars_wanted and tries < max_number_of_try: # To avoid taking too much time
    next_star_x = random.randint(0, screen.width)
    if does_not_overlap(next_star_x, placed_stars): # You will need to create this method
         placed_stars.append(next_star_x)
         number_of_stars += 1
    tries += 1
create_all_stars_from_x(placed_stars) # You will also need to create this method
Answered By: BlueSheepToken

I too have been working through this book and this has worked enough for me. I do not think he wants it to be too complicated. He just wants to make sure you understand what the code is doing.

In your create_star function add the random number to your star_width and star.rect.y variable. These variables are the distance between each star.

def create_star(s_settings, screen, stars, star_number, row_number):
    """Create an star and place it in the row."""
    random_number = randint(-10, 10)
    star = Star(screen, s_settings)
    star_width = star.rect.width + random_number
    star.x = star_width + 2 * star_width * star_number
    star.rect.y = star.rect.height + 3 * star.rect.height * row_number + random_number
    star.rect.x = star.x
    stars.add(star)

And if you want to randomized the first star in each row, you have to edit your init function.

class Star(Sprite):
    """A class to represent a single star in the grid."""

    def __init__(self, ai_settings, screen):
        """Initialize the star and set its starting position."""
        super(Star, self).__init__()
        self.screen = screen
        self.ai_settings = ai_settings
        random_number = randint(-10, 10)

        # Load the star image and set its rect attribute.
        self.image = pygame.image.load('images/star.bmp')
        self.rect = self.image.get_rect()

        # Start each new star near the top left of the screen
        self.rect.x = self.rect.width + random_number
        self.rect.y = self.rect.height + random_number
Answered By: clapHappy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.