Before we start creating cool games, we need an introduction to the drawing functionality of Pygame. As we noticed in the previous recipe, in Pygame we draw on the Surface
objects. There is a myriad of drawing options—different colors, rectangles, polygons, lines, circles, ellipses, animation, and different fonts.
The following steps will help you diverge into the different drawing options you can use with Pygame:
import numpy
colors = numpy.random.randint(0, 255, size=(4, 3))
Then define the white color as a variable:
WHITE = (255, 255, 255)
screen.fill(WHITE)
pygame.draw.circle(screen, colors[0], (200, 200), 25, 0)
3
:pygame.draw.line(screen, colors[1], (0, 0), (200, 200), 3)
pygame.draw.rect(screen, colors[2], (200, 0, 100, 100))
pygame.draw.ellipse(screen, colors[3], (100, 300, 100, 50), 2)
The resulting window with a circle, line, rectangle, and ellipse using random colors:
The code for the drawing demo is as follows:
import pygame, sys from pygame.locals import * import numpy pygame.init() screen = pygame.display.set_mode((400, 400)) pygame.display.set_caption('Drawing with Pygame') colors = numpy.random.randint(0, 255, size=(4, 3)) WHITE = (255, 255, 255) #Make screen white screen.fill(WHITE) #Circle in the center of the window pygame.draw.circle(screen, colors[0], (200, 200), 25, 0) # Half diagonal from the upper-left corner to the center pygame.draw.line(screen, colors[1], (0, 0), (200, 200), 3) pygame.draw.rect(screen, colors[2], (200, 0, 100, 100)) pygame.draw.ellipse(screen, colors[3], (100, 300, 100, 50), 2) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()