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
Cody Mills
1,567 PointsDungeon Game draw_map() Explanation
I have recently finished the Dungeon Game, and I was wondering if anyone would care to elaborate on the draw_map() function below. I am not quite sure I understand what is fully going on with the for loop.
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('_|'))
2 Answers
Chris Freeman
Treehouse Moderator 68,468 PointsThough the "grid" is presented as 2-dimensional, the grid points are contained in a linear list. So the grid points go Left, Center, Right, Left, Center, Right, Left, Center, Right. Only the Right ones (in positions 2,5, and 8) need a trailing "|" character.
Since the tile is a trivial, formatting '|{}' to '|X' could have been a simple print.
Added comments to code.
def draw_map(player):
# draw top of grid
print(' _ _ _')
tile = '|{}'
# process each cell (grid point)
for idx, cell in enumerate(CELLS):
# if cell is not a Right edge....
if idx in [0, 1, 3, 4, 6, 7]:
if cell == player:
# print "|X"
print(tile.format('X'), end='')
else:
# print "|_"
print(tile.format('_'), end='')
else:
# cell IS Right edge
if cell == player:
# print "|X|"
print(tile.format('X|'))
else:
# print "|_|"
print(tile.format('_|'))
Brandon McClelland
4,645 PointsLooping over the cells of a two dimensional array (think graph paper). You've got idx and cell defining the two axes of the XY plain. Only some of the cells will contain a "_". In the others, it will contain "_|". Unless the player is present, then just draw the "X" or "X| " depending on which idx the loop is iterating over.