Categories
Python Answers

How to draw a rectangle with Pygame?

Spread the love

Sometimes, we want to draw a rectangle with Pygame.

In this article, we’ll look at how to draw a rectangle with Pygame.

How to draw a rectangle with Pygame?

To draw a rectangle with Pygame, we can use the draw.rect method.

For instance, we write

import pygame, sys
from pygame.locals import *


def main():
    pygame.init()

    DISPLAY = pygame.display.set_mode((500, 400), 0, 32)

    WHITE = (255, 255, 255)
    BLUE = (0, 0, 255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY, BLUE, (200, 150, 100, 50))

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()


main()

to call pygame.draw.rec to draw a rectangle.

We call it with the DISPLAY mode to set the fill to WHITE, BLUE color to set the border to blue, and the coordinates of the left, top, width, and height values in the tuple.

And then we run a while loop to show the rectangle until we quit the game.

Conclusion

To draw a rectangle with Pygame, we can use the draw.rect method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *