Graphical displays with Python and Pygame

Pygame Draw Module

Up to this point, I've been using pre-existing images loaded from disk. Now I'll look at Pygame's draw module, which provides capabilities for lines and simple shapes. All of the draw methods have three common arguments. The first two, Surface and color, are the Pygame surface to draw onto and the color to use while drawing. The last argument is always width, or the number of pixels across each line. If width is 0, the shape is filled.

The six examples in Figures 3-8 illustrate the primary drawing functions and their associated code. The pictures were generated with pygame.image.save.

Figure 3: drawFunctions/rect.py.
Figure 4: drawFunctions/polygon.py import pygame
Figure 5: drawFunctions/circle.py import pygame
Figure 6: drawFunctions/ellipse.py import pygame
Figure 7: drawFunctions/arc.py.
Figure 8: drawFunctions/line.py import pygame

More Drawing Functions

The draw module has three other functions, all related to drawing lines. The line function accepts a Python list of coordinates and draws a line between each list entry. Unlike polygon, the figure is not closed automatically. The closed argument can be True or False and responds appropriately.

The remaining two functions, aaline and aalines work like their traditional cousins. The width of either aaline function is always one pixel plus the surrounding anti-aliasing. Instead of the width argument, the last argument is blending and can be True or False. If blending is True, the function will blend underlying pixels rather than overwrite them.

Listing 3 shows how to use Pygame to create a classic optical illusion (Figure 9). Although I'm drawing straight lines, I get a curve! To see the effect develop, uncomment lines 13 and 14 (by removing the pound sign), so the screen will refresh after each set of lines drawn. You can adjust time.sleep on line 13 to change the delay between refreshes.

Figure 9: The result of lineCurve.py. Are the lines curved or straight?

Listing 3

lineCurve.py

01 import pygame
02 import time
03
04 size = 600
05 pygame.display.init()
06 screen = pygame.display.set_mode ( ( size, size ) )
07
08 for i in range ( 0, size, 25 ):
09   pygame.draw.line ( screen, ( 0, 250, 0 ), ( 0, i ), ( i, size ), 1 )
10   pygame.draw.line ( screen, ( 0, 250, 0 ), ( i, 0 ), ( size, i ), 1 )
11   pygame.draw.line ( screen, ( 0, 250, 0 ), ( size - i, 0 ), ( 0, i ), 1 )
12   pygame.draw.line ( screen, ( 0, 250, 0 ), ( i, size ), ( size, size - i ), 1 )
13   #time.sleep ( .5 )
14   #pygame.display.flip()
15 pygame.display.flip()
16
17 raw_input()
18 pygame.quit()

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content