In this vignette, we are going to explain how to draw on the screen. We are going to need to do this so that we can draw both the snake and the food it eats.
Pygame comes with the pygame.draw.rect method which will draw a rectangle on the screen. The arguments to this function are:
- the screen itself
- the colour we wish to draw
- a list of the form
[left, top, width, height]
which specifies the limits of the rectangle.
We are now going to draw a stationary white square in the middle of the screen.
import pygame
pygame.init()
# Create screen
SCREEN_HEIGHT = 400
SCREEN_WIDTH = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# Define colours in red-green-blue form
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Run game loop
game_over=False
while not game_over:
for event in pygame.event.get():
if event.type==pygame.QUIT:
game_over=True
# Draw black canvas
screen.fill(BLACK)
# Draw square
size = 20
pygame.draw.rect(
screen, WHITE,
[SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, size, size]
)
pygame.display.update()
pygame.quit()
We are now going to add some text to the screen.
We can do this with a combination of functions starting with pygame.font.SysFont, which selects the font we are going to display the message in. This function takes as arguments:
- a font name (here we specify None so as to get the default font)
- a font size
We then create the message itself using .render()
as shown in the below code snipped. The arguments to this function are:
- the text we wish to display
- whether to specify the characters as having smooth edges (here we always use
True
for this) - the text colour
The final thing we do is draw the object on the screen using blit
. The arguments to this are:
- the rendered message
- a list specifying the horizontal and vertical positions of where we wish to display it
The following draws "UNIQ+ rocks!" near the top of the screen.
import pygame
pygame.init()
# Create screen
SCREEN_HEIGHT = 400
SCREEN_WIDTH = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# Define colours in red-green-blue form
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Run game loop
game_over=False
while not game_over:
for event in pygame.event.get():
if event.type==pygame.QUIT:
game_over=True
# Draw black canvas
screen.fill(BLACK)
# Draw square
size = 20
pygame.draw.rect(
screen, WHITE,
[SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, size, size]
)
# Draw text
font_style = pygame.font.SysFont(None, 50)
mesg = font_style.render("UNIQ+ rocks!", True, WHITE)
screen.blit(mesg, [SCREEN_WIDTH // 2, 0])
# Update display
pygame.display.update()
pygame.quit()
Now that we know how to draw on our canvas, we want to be able to move our rectangle using the arrow keys. Our next vignette shows how to determine whether the keys are pressed by a user during the game.