Draw Polygon with Pygame

Today we will continue with our draw’s class in Pygame and in this article we will draw a Polygon object with the pygame.draw.polygon method. This polygon method will take in a few arguments. 1) The screen surface 2) The color of the Polygon 3) An array of tuples contain the x, y coordinate 4) An optional width value if stated then the pygame.draw.polygon method will draw a hollow Polygon object or else the Polygon will be filled with solid color.

In the following script, after you have clicked on any 5 locations on the screen then the pygame.draw.polygon method will start to draw Polygon on the surface of that screen!

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
cooordinate = []

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        if event.type == MOUSEBUTTONDOWN: #if mouse click then coordinate array will append x,y tuple 
            cooordinate.append(event.pos)
    screen.fill((255,255,255))
    screen.lock()
    if len(cooordinate) >= 5:
        pygame.draw.polygon(screen, (255,255,100), cooordinate, 3)
    
    screen.unlock()
    pygame.display.update()

Click on more positions on the screen and the shape will now change accordingly.

Pygame draw polygon
Pygame draw polygon