Библиотека pygame №1
pygame — это библиотека модулей для языка Python, созданная для разработки 2D игр.
Для того чтобы установить pygame на свой компьютер необходимо открыть командную строку или терминал и написать команду
pip3 install pygame
После установки необходимо создать новый файл и импортировать модуль pygame и написать шаблон игры
# Импортируем библиотеку pygame
import pygame
# Импортируем системную функцию exit
from sys import exit
# Инициализируем pygame
pygame. init ()
# Создаем окошко 800 пикселей шириной
# и 600 пикселей высотой и записываем его
# в переменную display.
# Переменную display называют поверхностью.
display = pygame.display. set_mode ( ( 800 , 600 ) )
# Основной цикл игры
while True :
# Ждем события (действия пользователя)
f or event in pygame.event. get ():
# Если нажали на крестик,
# то закрываем окно
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
# Обновляем поверхность игры
# на каждом шаге основного цикла игры
pygame.display. update ()
Пользователь может взаимодействовать с нашей игрой. Каждое действие пользователя — это некоторое событие , которое мы можем обработать . Выражение pygame.event.get() — это список событий, произошедших в нашей игре.
Цикл for просто перебирает необработанные события. Каждое событие он присваивает переменной event (можно написать любую другую).
Поговорим о цикле while , основном цикле игры . Как часто он выполняется? Очень и очень часто, это зависит от мощности компьютера. Для обновления экрана в играх часто используют 60 кадров в секунду.
Ограничим количество выполнений цикла.
import pygame
from sys import exit
display = pygame.display. set_mode ( ( 800 , 600 ) )
FPS = 60 # Создаем переменную FPS
clock = pg.time. Clock () # Создаем счетчик для FPS
while True :
f or event in pygame.event. get ():
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
clock. tick (FPS) # Замедляем цикл до 60 выполнений в секунду
Методу tick() передается желаемое количество кадров в секунду. Задержку он вычисляет сам. На каждой итерации основного цикла игры секунда делится на 60 и на вычисленную величину выполняется задержка.
Рисование фигур
В библиотеке pygame существует множество функций для рисования различных фигур.
Функция polygon() рисует произвольную фигуру. Она принимает 3 обязательных параметра (поверхность, цвет и кортеж координат) и 1 необязательный (толщину линий).
import pygame
from sys import exit
display = pygame.display. set_mode ( ( 800 , 600 ) )
# Рисуем полигон (да, получится квадратик)
pygame.draw. polygon ( display, ( 255 , 0 , 0 ) , ( ( 0 , 0 ), ( 100 , 0 ), ( 100 , 100 ), ( 0 , 100 ) ) )
FPS = 60
clock = pg.time. Clock ()
while True :
f or event in pygame.event. get ():
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
display — наша поверхность
(255, 0, 0) — красный цвет , почитайте про rgb
( (0, 0), (100, 0), (100, 100), (0, 100) ) — координаты вершин квадрата. Возьмите листочек и нарисуйте его координатах (замените сотню на единицу).
Давайте нарисуем треугольник
import pygame
from sys import exit
display = pygame.display. set_mode ( ( 800 , 600 ) )
# Рисуем квадратик
pygame.draw. polygon ( display, ( 255 , 0 , 0 ) , ( ( 0 , 0 ), ( 100 , 0 ), ( 100 , 100 ), ( 0 , 100 ) ) )
# Рисуем синий треугольник
pygame.draw. polygon ( display, ( 0 , 0 , 255 ) , ( ( 100 , 100 ), ( 200 , 200 ), ( 100 , 200 ) ) )
FPS = 60 # Создаем переменную FPS
clock = pg.time. Clock ()
while True :
f or event in pygame.event. get ():
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
(0, 0, 255) — синий цвет
((100, 100), (200, 200), (100, 200)) — координаты вершин нашего треугольник.
Самостоятельно нарисуйте пятиугольник (вам помогут карандаш и лист бумаги)
Рисование окружностей
Чтобы нарисовать окружность нужно вызвать метод circle из модуля draw. Команда выглядит так: pygame.draw.circle(display, color, position, radius).
display — поверхность, на которой рисуем
color — цвет, записанный в кортеже из трех чисел. (еще раз про rgb)
position — координаты точки центра окружности ( кортеж из двух чисел (x, y) )
radius — радиус окружности в пикселях
import pygame
from sys import exit
display = pygame.display. set_mode ( ( 800 , 600 ) )
# Рисуем квадратик
pygame.draw. polygon ( display, ( 255 , 0 , 0 ) , ( ( 0 , 0 ), ( 100 , 0 ), ( 100 , 100 ), ( 0 , 100 ) ) )
# Рисуем синию линию
pygame.draw. polygon ( display, ( 0 , 0 , 255 ) , ( ( 100 , 100 ), ( 200 , 200 ), ( 100 , 200 ) ) )
# Рисуем желтую окружность с радиусом 100 пикселей
pygame.draw. circle ( display, ( 255 , 255 , 0 ) , ( 400 , 200 ), 100 )
FPS = 60
clock = pg.time. Clock ()
while True :
f or event in pygame.event. get ():
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
display — наша поверхнотсть для рисования
(255, 255, 0) — желтый цвет
(400, 200) — координаты точки центра (в нашем случае 400 пикселей от верхнего левого угла по горизонтали и 200 пикселей по вертикали)
100 — радиус нашей окружности в пикселях
Объявления переменных для цветов
Для нашего с вами удобства давайте объявим несколько переменных, в которые сохраним используемые нами цвета
import pygame
from sys import exit
WHITE = ( 255 , 255 , 255 )
BLACK = ( 0 , 0 , 0 )
PURPLE = ( 156 , 39 , 176 )
INDIGO = ( 63 , 81 , 181 )
BLUE = ( 33 , 150 , 243 )
GREEN = ( 76 , 175 , 80 )
YELLOW = ( 255 , 235 , 59 )
ORANGE = ( 255 , 152 , 0 )
GREY = ( 158 , 158 , 158 )
display = pygame.display. set_mode ( ( 800 , 600 ) )
# Рисуем квадратик
pygame.draw. polygon ( display, ( 255 , 0 , 0 ) , ( ( 0 , 0 ), ( 100 , 0 ), ( 100 , 100 ), ( 0 , 100 ) ) )
# Рисуем синию линию
pygame.draw. polygon ( display, ( 0 , 0 , 255 ) , ( ( 100 , 100 ), ( 200 , 200 ), ( 100 , 200 ) ) )
# Рисуем желтую окружность с радиусом 100 пикселей
pygame.draw. circle ( display, ( 255 , 255 , 0 ) , ( 400 , 200 ), 100 )
FPS = 60
clock = pg.time. Clock ()
while True :
f or event in pygame.event. get ():
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
Рисование прямоугольников
Для отрисовки прямоугольников можно использовать метод rect.
pygame.draw.rect(display, color, (x, y, width, height) )
color — цвет (теперь можно просто написать имя переменную)
(x, y, width, height) — кортеж из четырех значений. Первые два значения — это координаты верхнего левого угла прямоугольника, а два последних — это ширина и высота.
import pygame
from sys import exit
WHITE = ( 255 , 255 , 255 )
BLACK = ( 0 , 0 , 0 )
PURPLE = ( 156 , 39 , 176 )
INDIGO = ( 63 , 81 , 181 )
BLUE = ( 33 , 150 , 243 )
GREEN = ( 76 , 175 , 80 )
YELLOW = ( 255 , 235 , 59 )
ORANGE = ( 255 , 152 , 0 )
GREY = ( 158 , 158 , 158 )
display = pygame.display. set_mode ( ( 800 , 600 ) )
# Рисуем квадратик
pygame.draw. polygon ( display, ( 255 , 0 , 0 ) , ( ( 0 , 0 ), ( 100 , 0 ), ( 100 , 100 ), ( 0 , 100 ) ) )
# Рисуем синию линию
pygame.draw. polygon ( display, ( 0 , 0 , 255 ) , ( ( 100 , 100 ), ( 200 , 200 ), ( 100 , 200 ) ) )
# Рисуем желтую окружность с радиусом 100 пикселей
pygame.draw. circle ( display, ( 255 , 255 , 0 ) , ( 400 , 200 ), 100 )
# Рисуем фиолетовый прямоугольник 200х300
pygame.draw. rect ( display, PURPLE , ( 600 , 300 , 200 , 300 ))
FPS = 60
clock = pg.time. Clock ()
while True :
f or event in pygame.event. get ():
if event.type == pygame.QUIT:
pygame. quit ()
exit ()
Если ваша творческая натура требует большего, то вот ссылка на документацию модулю draw
Там можно найти рисование линий, дуг, эллипсов.
Большой пример ( запусти его у себя на компьтере:
import pygame
from sys import exit
from random import randint
# Функция, возвращающая случайный оттенок зеленого цвета
def randomGreen ():
return randint ( 0 , 100 ), randint ( 100 , 255 ), randint ( 0 , 100 )
# Функция, возвращающая случайный оттенок красного цвета
def randomRed ():
return randint ( 100 , 255 ), randint ( 0 , 100 ), randint ( 0 , 100 )
pygame
Рисование на экране
Pygame имеет модуль pygame.draw , который содержит функции, которые могут рисовать фигуры непосредственно на поверхности.
| функция | Описание |
|---|---|
| pygame.draw.rect | нарисовать прямоугольную форму |
| pygame.draw.polygon | нарисуйте фигуру с любым количеством сторон |
| pygame.draw.circle | нарисуйте круг вокруг точки |
| pygame.draw.ellipse | нарисуйте круглую форму внутри прямоугольника |
| pygame.draw.arc | нарисуйте частичную часть эллипса |
| pygame.draw.line | нарисуйте отрезок прямой линии |
| pygame.draw.lines | нарисовать несколько смежных отрезков |
| pygame.draw.aaline | нарисовать тонкие сглаженные линии |
| pygame.draw.aalines | нарисовать связанную последовательность сглаженных линий |
Как использовать модуль
Чтобы использовать модуль, вам сначала нужно правильно импортировать и инициализировать pygame и установить режим отображения. Удобно определять цветовые константы заранее, делая ваш код более читабельным и красивым. Все функции принимают поверх поверхности, аргумент цвета и позиции, который представляет собой либо pygame Rect, либо 2-элементную последовательность integer / float ( pygame.draw.circle будет принимать только целые числа из-за неопределенных причин).
пример
В приведенном ниже коде будут показаны все различные функции, способы их использования и способы их просмотра. Мы инициализируем pygame и определяем некоторые константы перед примерами.
Черный цвет — это цвет по умолчанию для поверхности и представляет собой часть поверхности, на которую не нарисовано. Параметры каждой функции описаны ниже в параметрах .
многоугольник
Отверстия являются неудачным следствием алгоритма рисования pygame.
Эллипс
Отверстия являются неудачным следствием алгоритма рисования pygame.
Линия
линии
Сглаженная линия
Сглаженные линии
Попробуйте
Попробуйте сами: скопируйте один из фрагментов кода выше и код ниже в пустой файл, измените изображение имени на имя поверхности, которую хотите разбить и поэкспериментировать.
Поверхности
В pygame вы обычно используете Surfaces для представления внешнего вида объектов и Rectangles для представления своих позиций. A Поверхность похожа на чистый лист бумаги, который содержит цвета или изображения. Существует два способа создания Поверхности: пустая с нуля или загрузка изображения.
Создание поверхности
Чтобы создать Поверхность, вам нужен минимум ее размер, который представляет собой 2-элементную целую последовательность ширины и высоты, представляющую размер в пикселях.
Вы также можете передавать дополнительные аргументы при создании Поверхности для управления глубиной, масками и дополнительными функциями в качестве пикселя альфа и / или создания изображения в видеопамяти. Однако это выходит за рамки этого примера.
Вы можете использовать модуль pygame.draw для рисования фигур на поверхности или заливки цветом, вызвав метод fill(color) поверхности fill(color) . Цвет аргумента представляет собой целую последовательность из 3 или 4 элементов или объект pygame.Color .
Загрузить изображение
Чаще всего вы хотели бы использовать свои собственные изображения в игре (называемые спрайтами). Создание поверхности с вашим изображением так же просто, как:
Путь к изображению может быть относительным или абсолютным. Для повышения производительности обычно целесообразно преобразовать изображение в тот же формат пикселей, что и экран. Это можно сделать, вызвав метод Surface метода convert() , например:
Если ваше изображение содержит прозрачность (альфа-значения), вы просто вызываете метод convert_alpha() :
блиттинг
Для того, чтобы их можно было отображать, на экране должны быть блистерны. Blitting по существу означает копирование пикселей с одной поверхности на другую (экран также является поверхностью). Вам также необходимо передать позицию поверхности, которая должна быть 2-элементной целочисленной последовательностью или объектом Rect. Поверхность Поверхности будет помещена в позицию.
Можно смешать с другими поверхностями, чем экран. Чтобы показать, что было на экране, вам нужно вызвать pygame.display.update() или pygame.display.flip() .
прозрачность
В pygame есть виды 3 прозрачности: colorkeys, Surface alphas и per-pixel alphas.
Colorkeys
Делает цвет полностью прозрачным или более точно, делая цвет просто не blit. Если у вас есть изображение с черным прямоугольником внутри, вы можете установить colorkey, чтобы черный цвет не блистал.
Поверхность может иметь только один colorkey. Установка другого colorkey перезапишет предыдущий. Colorkeys не может иметь разные значения альфа, он может только сделать цвет невидимым.
Поверхностные альфы
Делает всю поверхность прозрачной по альфа-значению. С помощью этого метода вы можете иметь разные значения альфа, но это повлияет на всю поверхность.
Пер-пиксельная альфа
Делает каждый пиксель в прозрачной поверхности индивидуальным альфа-значением. Это дает вам максимальную свободу и гибкость, но также является самым медленным методом. Этот метод также требует, чтобы поверхность создавалась как пиксельная альфа-поверхность, а цветовые аргументы должны содержать четвертое целое число.
Теперь поверхность будет рисовать прозрачность, если цвет содержит четвертое значение альфа.
В отличие от других поверхностей, этот цвет по умолчанию не будет черным, но прозрачным. Вот почему черный прямоугольник посередине исчезает.
Объединить colorkey и Surface alpha
Colorkeys и Surface alphas можно комбинировать, но альфа-пиксель не может. Это может быть полезно, если вы не хотите более медленную производительность для пиксельной поверхности.
Полный код
Скопируйте это в пустой файл и запустите его. Нажмите клавиши 1, 2, 3 или 4, чтобы отобразить изображения. Нажмите 2, 3 или 4 раза, чтобы сделать их более непрозрачными.
Как нарисовать круг в pygame

pygame documentation
Draw several simple shapes to a surface. These functions will work for rendering to any format of surface.
Most of the functions take a width argument to represent the size of stroke (thickness) around the edge of the shape. If a width of 0 is passed the shape will be filled (solid).
All the drawing functions respect the clip area for the surface and will be constrained to that area. The functions return a rectangle representing the bounding area of changed pixels. This bounding rectangle is the ‘minimum’ bounding box that encloses the affected area.
All the drawing functions accept a color argument that can be one of the following formats:
-
a pygame.Color pygame object for color representations object
-
an (RGB) triplet (tuple/list)
-
an (RGBA) quadruplet (tuple/list)
-
an integer value that has been mapped to the surface’s pixel format (see pygame.Surface.map_rgb() convert a color into a mapped color value and pygame.Surface.unmap_rgb() convert a mapped integer color value into a Color )
A color’s alpha value will be written directly into the surface (if the surface contains pixel alphas), but the draw function will not draw transparently.
These functions temporarily lock the surface they are operating on. Many sequential drawing calls can be sped up by locking and unlocking the surface object around the draw calls (see pygame.Surface.lock() lock the Surface memory for pixel access and pygame.Surface.unlock() unlock the Surface memory from pixel access ).
See the pygame.gfxdraw pygame module for drawing shapes module for alternative draw methods.
Draws a rectangle on the given surface.
surface (Surface) — surface to draw on
rect (Rect) — rectangle to draw, position and dimensions
width (int) —
(optional) used for line thickness or to indicate that the rectangle is to be filled (not to be confused with the width value of the rect parameter)
Changed in pygame 2.1.1: Drawing rects with width now draws the width correctly inside the rect’s area, rather than using an internal call to draw.lines(), which had half the width spill outside the rect area.
border_radius (int) — (optional) used for drawing rectangle with rounded corners. The supported range is [0, min(height, width) / 2], with 0 representing a rectangle without rounded corners.
border_top_left_radius (int) — (optional) used for setting the value of top left border. If you don’t set this value, it will use the border_radius value.
border_top_right_radius (int) — (optional) used for setting the value of top right border. If you don’t set this value, it will use the border_radius value.
border_bottom_left_radius (int) — (optional) used for setting the value of bottom left border. If you don’t set this value, it will use the border_radius value.
border_bottom_right_radius (int) —
(optional) used for setting the value of bottom right border. If you don’t set this value, it will use the border_radius value.
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the position of the given rect parameter and its width and height will be 0
The pygame.Surface.fill() fill Surface with a solid color method works just as well for drawing filled rectangles and can be hardware accelerated on some platforms.
Changed in pygame 2.0.0: Added support for keyword arguments.
Changed in pygame 2.0.0.dev8: Added support for border radius.
Draws a polygon on the given surface.
surface (Surface) — surface to draw on
points (tuple(coordinate) or list(coordinate)) — a sequence of 3 or more (x, y) coordinates that make up the vertices of the polygon, each coordinate in the sequence must be a tuple/list/ pygame.math.Vector2 a 2-Dimensional Vector of 2 ints/floats, e.g. [(x1, y1), (x2, y2), (x3, y3)]
width (int) —
(optional) used for line thickness or to indicate that the polygon is to be filled
Note
When using width values > 1 , the edge lines will grow outside the original boundary of the polygon. For more details on how the thickness for edge lines grow, refer to the width notes of the pygame.draw.line() draw a straight line function.
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
ValueError — if len(points) < 3 (must have at least 3 points)
TypeError — if points is not a sequence or points does not contain number pairs
For an aapolygon, use aalines() with closed=True .
Changed in pygame 2.0.0: Added support for keyword arguments.
Draws a circle on the given surface.
surface (Surface) — surface to draw on
radius (int or float) — radius of the circle, measured from the center parameter, nothing will be drawn if the radius is less than 1
width (int) —
(optional) used for line thickness or to indicate that the circle is to be filled
Note
When using width values > 1 , the edge lines will only grow inward.
draw_top_right (bool) — (optional) if this is set to True then the top right corner of the circle will be drawn
draw_top_left (bool) — (optional) if this is set to True then the top left corner of the circle will be drawn
draw_bottom_left (bool) — (optional) if this is set to True then the bottom left corner of the circle will be drawn
draw_bottom_right (bool) —
(optional) if this is set to True then the bottom right corner of the circle will be drawn
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the center parameter value (float values will be truncated) and its width and height will be 0
TypeError — if center is not a sequence of two numbers
TypeError — if radius is not a number
Changed in pygame 2.0.0: Added support for keyword arguments. Nothing is drawn when the radius is 0 (a pixel at the center coordinates used to be drawn when the radius equaled 0). Floats, and Vector2 are accepted for the center param. The drawing algorithm was improved to look more like a circle.
Changed in pygame 2.0.0.dev8: Added support for drawing circle quadrants.
Draws an ellipse on the given surface.
surface (Surface) — surface to draw on
rect (Rect) — rectangle to indicate the position and dimensions of the ellipse, the ellipse will be centered inside the rectangle and bounded by it
width (int) —
(optional) used for line thickness or to indicate that the ellipse is to be filled (not to be confused with the width value of the rect parameter)
Note
When using width values > 1 , the edge lines will only grow inward from the original boundary of the rect parameter.
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the position of the given rect parameter and its width and height will be 0
Changed in pygame 2.0.0: Added support for keyword arguments.
Draws an elliptical arc on the given surface.
The two angle arguments are given in radians and indicate the start and stop positions of the arc. The arc is drawn in a counterclockwise direction from the start_angle to the stop_angle .
surface (Surface) — surface to draw on
rect (Rect) — rectangle to indicate the position and dimensions of the ellipse which the arc will be based on, the ellipse will be centered inside the rectangle
start_angle (float) — start angle of the arc in radians
stop_angle (float) —
stop angle of the arc in radians
width (int) —
(optional) used for line thickness (not to be confused with the width value of the rect parameter)
Note
When using width values > 1 , the edge lines will only grow inward from the original boundary of the rect parameter.
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the position of the given rect parameter and its width and height will be 0
Changed in pygame 2.0.0: Added support for keyword arguments.
Draws a straight line on the given surface. There are no endcaps. For thick lines the ends are squared off.
surface (Surface) — surface to draw on
width (int) —
(optional) used for line thickness
When using width values > 1 , lines will grow as follows.
For odd width values, the thickness of each line grows with the original line being in the center.
For even width values, the thickness of each line grows with the original line being offset from the center (as there is no exact center line drawn). As a result, lines with a slope < 1 (horizontal-ish) will have 1 more pixel of thickness below the original line (in the y direction). Lines with a slope >= 1 (vertical-ish) will have 1 more pixel of thickness to the right of the original line (in the x direction).
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the start_pos parameter value (float values will be truncated) and its width and height will be 0
TypeError — if start_pos or end_pos is not a sequence of two numbers
Changed in pygame 2.0.0: Added support for keyword arguments.
Draws a sequence of contiguous straight lines on the given surface. There are no endcaps or miter joints. For thick lines the ends are squared off. Drawing thick lines with sharp corners can have undesired looking results.
surface (Surface) — surface to draw on
closed (bool) — if True an additional line segment is drawn between the first and last points in the points sequence
points (tuple(coordinate) or list(coordinate)) — a sequence of 2 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/ pygame.math.Vector2 a 2-Dimensional Vector of 2 ints/floats and adjacent coordinates will be connected by a line segment, e.g. for the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2) and from (x2, y2) to (x3, y3) , additionally if the closed parameter is True another line segment will be drawn from (x3, y3) to (x1, y1)
width (int) —
(optional) used for line thickness
When using width values > 1 refer to the width notes of line() for details on how thick lines grow.
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
ValueError — if len(points) < 2 (must have at least 2 points)
TypeError — if points is not a sequence or points does not contain number pairs
Changed in pygame 2.0.0: Added support for keyword arguments.
Draws a straight antialiased line on the given surface.
The line has a thickness of one pixel and the endpoints have a height and width of one pixel each.
The way a line and its endpoints are drawn:
If both endpoints are equal, only a single pixel is drawn (after rounding floats to nearest integer).
Otherwise if the line is not steep (i.e. if the length along the x-axis is greater than the height along the y-axis):
For each endpoint:
If x , the endpoint’s x-coordinate, is a whole number find which pixels would be covered by it and draw them.
Otherwise:
Calculate the position of the nearest point with a whole number for its x-coordinate, when extending the line past the endpoint.
Find which pixels would be covered and how much by that point.
If the endpoint is the left one, multiply the coverage by (1 — the decimal part of x ).
Otherwise multiply the coverage by the decimal part of x .
Then draw those pixels.
e.g.:
Then for each point between the endpoints, along the line, whose x-coordinate is a whole number:
Find which pixels would be covered and how much by that point and draw them.
e.g.:
Otherwise do the same for steep lines as for non-steep lines except along the y-axis instead of the x-axis (using y instead of x , top instead of left and bottom instead of right).
Regarding float values for coordinates, a point with coordinate consisting of two whole numbers is considered being right in the center of said pixel (and having a height and width of 1 pixel would therefore completely cover it), while a point with coordinate where one (or both) of the numbers have non-zero decimal parts would be partially covering two (or four if both numbers have decimal parts) adjacent pixels, e.g. the point (1.4, 2) covers 60% of the pixel (1, 2) and 40% of the pixel (2,2) .
surface (Surface) — surface to draw on
blend (int) — (optional) (deprecated) if non-zero (default) the line will be blended with the surface’s existing pixel shades, otherwise it will overwrite them
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the start_pos parameter value (float values will be truncated) and its width and height will be 0
TypeError — if start_pos or end_pos is not a sequence of two numbers
Changed in pygame 2.0.0: Added support for keyword arguments.
Draws a sequence of contiguous straight antialiased lines on the given surface.
surface (Surface) — surface to draw on
closed (bool) — if True an additional line segment is drawn between the first and last points in the points sequence
points (tuple(coordinate) or list(coordinate)) — a sequence of 2 or more (x, y) coordinates, where each coordinate in the sequence must be a tuple/list/ pygame.math.Vector2 a 2-Dimensional Vector of 2 ints/floats and adjacent coordinates will be connected by a line segment, e.g. for the points [(x1, y1), (x2, y2), (x3, y3)] a line segment will be drawn from (x1, y1) to (x2, y2) and from (x2, y2) to (x3, y3) , additionally if the closed parameter is True another line segment will be drawn from (x3, y3) to (x1, y1)
blend (int) — (optional) (deprecated) if non-zero (default) each line will be blended with the surface’s existing pixel shades, otherwise the pixels will be overwritten
a rect bounding the changed pixels, if nothing is drawn the bounding rect’s position will be the position of the first point in the points parameter (float values will be truncated) and its width and height will be 0
ValueError — if len(points) < 2 (must have at least 2 points)
TypeError — if points is not a sequence or points does not contain number pairs
Pygame Draw Objects and Shapes

Pygame Draw : In this tutorial, we will see how to create simple geometric figures with the Draw function of the Pygame module.
Introduction
Pygame is a free cross-platform library that facilitates the development of real-time video games using the Python programming language. It allows you to program the multimedia part (graphics, sound and keyboard, mouse or joystick inputs).
Pygame, in addition to adapting SDL to Python, also provides a small number of functions specific to game development. One of the most commonly used functions is the draw function. The draw function allows you to create a multitude of simple and complex geometric figures.
Here are the different shapes that we will go through in this tutorial :
| Function | Description |
|---|---|
| draw.rect | draw a rectangle shape |
| draw.line | draw a straight line |
| draw.lines | draw multiple contiguous line |
| draw.circle | draw a circle |
| draw.arc | draw an arc |
| draw.polygon | draw a shape with a multitude of sides |
| pygame.draw.ellipse | draw a round shape inside a rectangle |
| draw.aaline | draw fine antialiased lines |
| draw.aalines | draw a connected sequence of antialiased lines |
If you need to install the pygame module, I recommend you to check my previous tutorial :
Pygame Draw : Getting Started
Create a new window
Before we can use the draw function, we must import and initialize the pygame module. Here is the code to do this:
To open a new window, you can use the following code:
The function pygame.display.set_mode will open a new window of size 650px by 450px. We will store this window in an object called screen which will be useful later to draw our different shapes. You can set any screen size, it depends on your need.
If you have set the screen size to 650×450, this means that the window can contain 650×450 = 292,500 points.
Here are some elements to help you find your way around the window:
- The point (0,0) is in the upper left corner of the screen.
- The point (650,0) is in the upper right corner of the screen.
- The point (0,450) is in the lower left corner of the screen.
- The point (650,450) is in the lower right corner of the screen.
To summarize, the x-coordinates increase from left to right and the y-coordinates increase from top to bottom.
Update Window
To update the window, we must use the function
pygame.display.update(). Without this function, it will be impossible to see the display changes on our window.
Here is an example that allows you to change the background color of the window and update it:

The function screen.fill(color) allows to fill the whole screen with the color passed in parameter. To update the screen, the pygame.display.update() function must be used.
Pygame Draw
Draw a rectangle
pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height))
The first shape we will draw is a rectangle. To do this we will use the function rect().
This function can take several parameters, the most important of which are :
- surface: surface to draw on
- color: color to draw with
- rect (Rect): rectangle to draw, position, and dimensions
- width (int,optional): used for line thickness or to indicate that the rectangle must be filled (not to be confused with the width value of the rest parameter)
Here is the code to draw a filled or unfilled rectangle:

Draw a line
pygame.draw.line (surface, color, (startX, startY), (endX, endY), width)

Draw multiple contiguous lines
pygame.draw.lines(screen, color, closed , points, width)

Draw a Circle
pygame.draw.circle(surface, color, (x, y), radius)

Draw an Arc
pygame.draw.arc(surface, color, rect, start_angle, stop_angle,width)

Draw a polygon
pygame.draw.polygon(surface, color, point_list)

Draw an ellipse
pygame.draw.ellipse(surface, color, rect, width=0)

Conclusion
We have seen in this tutorial how to create simple shapes with Pygame. It is possible to create more complex shapes by playing with the parameters of the different functions we have seen. I hope this article has helped you better understand the draw function of the Pygame module.
In any case, don’t hesitate to tell me in comments if you have any problems using one of these functions, I would be happy to answer.
I’m a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming 🙂