Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dungeon Game Dungeon Entrance

eestsaid
eestsaid
1,311 Points

dungeon entrance

Team

I started looked at the Dungeon problem specifically the first step for nominating starting locations for monster, door and player. Code I used was:

CELLS = [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0),
         (0, 1), (1, 1), (2, 1), (3, 1), (4, 1),
         (0, 2), (1, 2), (2, 2), (3, 2), (4, 2),
         (0, 3), (1, 3), (2, 3), (3, 3), (4, 3),
         (0, 4), (1, 4), (2, 4), (3, 4), (4, 4)]


def get_locations(location):
    monster = None
    door = None
    player = None
    for i in location:
        monster = random.sample(location, k=1)
    while door == monster:
        door = random.sample(location, k=1)
    else:
        door = random.sample(location, k=1)
    while player == monster or player == door:
        player = random.sample(location, k=1)
    else:
        player = random.sample(location, k=1)
    print(monster, door, player)


get_locations(CELLS)

To locate monster I really just had a stab based on earlier exercises and I don't really know why it has worked. How does the following part actually work? Is I effectively iterating through location and then stopping at some random point?

    for i in location:
        monster = random.sample(location, k=1)

Many thanks

1 Answer

hi, it’s inefficient the way ur doing it: u only need to get a random location for the door.monster and player. u use random.choice to get 1 random location and u use random.sample(<array, the number of random location u want). for this purpose we need 3 random locations, so u need to create the following function : set get_random_loc(): return random.sample(CELLS, 3)

then u unpack this function to 3 variables : monster ,door, player = get_random_loc()

eestsaid
eestsaid
1,311 Points

Thanks bot.net. My question was more about the operation of the for loop not so much the suitability of the code for this specific instance. Do you have any thoughts about the operation of the for loop?