72
150
http://inventwithpython.com/pygame
Email questions to the author: al@inventwithpython.com
214. pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))
215. for y in range(0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines
216. pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))
Just to make it easier to visualize the grid of cells, we call
pygame.draw.line()
to draw out
each of the vertical and horizontal lines of the grid.
Normally, to draw the 32 vertical lines needed, we would need 32 calls to
pygame.draw.line()
with the following coordinates:
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 0), (0, WINDOWHEIGHT))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (20, 0), (20, WINDOWHEIGHT))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (40, 0), (40, WINDOWHEIGHT))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (60, 0), (60, WINDOWHEIGHT))
...skipped for brevity...
pygame.draw.line(DISPLAYSURF, DARKGRAY, (560, 0), (560, WINDOWHEIGHT))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (580, 0), (580, WINDOWHEIGHT))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (600, 0), (600, WINDOWHEIGHT))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (620, 0), (620, WINDOWHEIGHT))
Instead of typing out all these lines of code, we can just have one line of code inside a
for
loop.
Notice that the pattern for the vertical lines is that the X coordinate of the start and end point
starts at
0
and goes up to
620
, increasing by
20
each time. The Y coordinate is always
0
for the
start point and
WINDOWHEIGHT
for the end point parameter. That means the
for
loop should
iterate over
range(0, 640, 20)
. This is why the
for
loop on line 213 iterates over
range(0, WINDOWWIDTH, CELLSIZE)
.
For the horizontal lines, the coordinates would have to be:
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 0), (WINDOWWIDTH, 0))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 20), (WINDOWWIDTH, 20))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 40), (WINDOWWIDTH, 40))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 60), (WINDOWWIDTH, 60))
...skipped for brevity...
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 400), (WINDOWWIDTH, 400))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 420), (WINDOWWIDTH, 420))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 440), (WINDOWWIDTH, 440))
pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, 460), (WINDOWWIDTH, 460))
The Y coordinate ranges from
0
to
460
, increasing by
20
each time. The X coordinate is always
0
for the start point and
WINDOWWIDTH
for the end point parameter. We can also use a
for
loop
here so we don’t have to type out all those pygame.draw.line()
calls.