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

Drawing a visual map of the dungeon game

How does python know to print the dungeon map with three rows of three. Why would't things be printed on one line?

Here is the code, how does this result in a grid of 3x3 def draw_map(player): print(' _ _ _ ') tile = '|{}'

for idx, cell in enumerate(CELLS): if idx in [0,1,3,4,6,7]: if cell == player: print(tile.format('X'), end='') else: print(tile.format(''), end='') else: if cell == player: print(tile.format('X|')) else: print(tile.format('|'))

1 Answer

Hi

Good question and trying to think how to explain

The main reason it prints the way it does is the end key that you put in to print. Normally python would print and then move to the next line and print the next thing and then the next line and so forth.. If python reads through the code and comes across end, it will set up to then print next to what was just printed, run the next part of the code and add it in that spot.

The reason this does only three in a line then goes to the next line is due to the idx set up. enumerate will create a count 0 1 2 3 etc.. So if idx in [0,1,3,4,6,7] means the first two times this loop is run 0 and 1 will come up and it will run code which has an end key in it which will continue to add the next printed item on the same line. After this though it will find 2. This starts your else code which doesn't have the end key so will stop printing on this line and move to the next. End result is your first line is 0,1,2 no more end key so breaks to the next line 3,4,5 again 5 is not in the list so moves to else and again no end key so third line is 6,7,8

If i recall the enumerate(cells) for this game would create

(0, (0, 0)) 
(1, (0, 1)) 
(2, (0, 2)) #end of first line because the idx == 2 
(3, (1, 0)) etc

So the first run on your for loop pulls is idx == 0 and cell == (0, 0)

Hope this helps a little bit to understand the breakdown >_<