With our PyGame code initialised let's draw something on the screen.
Here's a code snippet:
# get mouse position
pos = pygame.mouse.get_pos()
# define a disc size and colour
discSize = random.randint(5,50)
r = random.randint(100,255)
g = random.randint(100,255)
b = random.randint(100,255)
discCol = [r,g,b]
# draw a disc at the current mouse position
pygame.draw.circle(screen, discCol, pos, discSize)
# update the screen with what we've drawn
# control the draw update speed
In the first statement we call
pygame.mouse.get_pos to return the mouse coordinates and store them in a variable called
pos. As we'll see later this code will be called in a endless loop. So, on each loop iteration (which means many times a second)
pygame.mouse.get_pos captures the current mouse position.
In this example we draw a simple disc on the screen, so the next five statements set a disc size and colour. Note we're using the random package here to vary the size and colour of the disc each time.
Next we call the
pygame.draw.circle function to draw a coloured disc. There are four parameters. The first parameter is our
screen object (which we created in the initialisation section) onto which the disc is drawn. The second parameter contains the RGB
discCol value we defined earlier. Parameter three contains the mouse position coordinates as stored in the
pos variable. And the fourth parameter declares the disc radius using the
Now we come a particularly important function
pygame.display.flip. This does the magic necessary to render our graphical elements on the screen. Without this line we'd see nothing. I say magic because there's loads of clever stuff going on under the covers to create smooth, flicker-free animation. This involves many hundreds of lines of Python code, however all we need to do is call a single function.
The final statement is also important. It controls the update speed of the screen display using the function
clock.tick. Remember, we created the clock object in the initialisation section. The
tick function parameter fixs the update speed. The lower the number the fewer the number of screen updates.
A post from my Learn Python on the Raspberry Pi tutorial.