Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dungeon Game Building the Game: Part 2

fahad lashari
fahad lashari
6,771 Points

What makes the map print the way that it does?

Hi so here is the code in question:

  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('_|'))

Which section of this code ensures that the map isn't printed like this for example:

|_|_|_|_|_|_|_|X|_|

I have a brief understanding of the 'end' function in that it makes sure that we do not move onto the next line. This is being applied in the code:

 print(tile.format('X'), end='')

and

print(tile.format('_'), end='')

This allows string to be printed in front of last strings however what I do not understand is that how does the code know to move onto the next line after printing:

|_|_|_|

I would greatly appreciate an answer to this while I try to understand this myself.

Thank you in advance

kind regards,

Fahad

1 Answer

Hi Fahad,

At around 1:45 in the video, Kenneth starts talking about the index values of the CELLS list.

If we were to show the index values of those 9 tuples in a 3x3 grid it would look like this:

0 1 2
3 4 5
6 7 8

The outer if condition is checking for indexes 0, 1, 3, 4, 6, 7. These are all the indexes that are NOT in the last column. So you know that if it's one of those, you don't want to go to a new line yet by using end=''. You only want to print a vertical bar and then either an 'X' or an underscore.

The outer else will execute when the index is either 2, 5 or 8. In this case, you're in the last column. You would want to print a vertical bar, either an 'X' or '_' and then the final vertical bar. Because the end keyword argument is omitted, it will print the default \n which allows you to start the next row.