"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Draw Rectangles in Pygame Using `pygame.draw.rect`?

How to Draw Rectangles in Pygame Using `pygame.draw.rect`?

Published on 2024-11-08
Browse:356

How to Draw Rectangles in Pygame Using `pygame.draw.rect`?

Drawing Rectangles with Pygame

In Python's Pygame library, creating rectangles is an essential task for developing games.

For Pygame versions like 3.2, drawing rectangles involves using the pygame.draw.rect function. Here's how you can achieve this:

  1. Import Pygame and essential constants:
import pygame, sys
from pygame.locals import *
  1. Initialize Pygame:
pygame.init()
  1. Create a display window:
DISPLAY=pygame.display.set_mode((500,400),0,32)
  1. Set colors:
WHITE=(255,255,255)
BLUE=(0,0,255)
  1. Fill the display with white:
DISPLAY.fill(WHITE)
  1. Draw a blue rectangle using pygame.draw.rect:
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
  1. Start the game loop:
while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    # Update the display
    pygame.display.update()

This sample code creates a white window with dimensions of 500 pixels wide and 400 pixels high and places a blue rectangle with coordinates (200, 150) and dimensions of 100 pixels wide and 50 pixels high.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3