Python Forum

Full Version: Randomly selecting sprite from group?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to add items to my random dungeon. I'm thinking to select a sprite at random from my group of floor tiles and use it's location as a spawn location for a key, a treasure, and some enemies.

Is it possible to select a sprite (and it's location) from a group? My searches have revealed nothing about this.

I want to do something like:

key1 = Key(random_floor_tile.x, random_floor_tile.y)


Then to stop the same floor tile from being used twice, adding the selected tile to a group to check before spawning?

Thanks.


PS. Is there are more Pythonese word to use instead of "spawn"? lol
You can make a list of the tiles and randomly pick from them. For example:
import random

CoordinateDict = {'x' : [], 'y' : []}
for num in range(1, 21): #Numbers 1-20
    CoordinateDict['x'].append(num)
    CoordinateDict['y'].append(num)
#The code above puts numbers from 1-20 in the x and y lists of the "CoordinateDict"

while CoordinateDict['x']: #While there are still numbers left to choose from
    x = random.choice(CoordinateDict['x']) #Pick x coord
    y = random.choice(CoordinateDict['y']) #Pick y coord
    CoordinateDict['x'].remove(x) #Remove that x coord from the list
    CoordinateDict['y'].remove(y) #Remove that y coord from the list
    print(f'({x}, {y})') #Print out the coord
I hope this helps.
I need to use coordinates that are in my "Floor_tiles" sprite.Group so items don't appear on the stairs, in the wall, or outside the walls where the character can't go. And all these change every time because it is a map made by random walk. It's not a square grid.

Do sprite groups have an index that I can somehow random choice from?

It occurs to me now that I might be able add the floor sprite's coordinates to a dictionary(or list, or something) as they are put down and then select from that list. Haven't done much of this stuff yet.
Having a problem with data types. The process below gives me a list of tuples, but I need to input the x and y as separate arguments. "Split" doesn't work on tuples, apparently. Maybe how I add them to the list can change? I can use 2 separate lists (one for x and one for y) but then I don't know how to make sure to use x's and y's that are actual pairs.

floor_locations = []

### then  I move my digger sprite with a random walk and add each step to list here:

floor_locations.append(digger.rect.x, digger.rect.y)


### Then... 

key_location = random.choice(floor_locations)
key1 = Key(key_location)
Take a random object from your list of tuples and use tuple unpacking to get the values.
my_tuple = (2,3)
x,y = my_tuple
Thanks! That was a lot easier than I was worried about.