How to Draw a Rectangle in Python Using Pygame?

Patricia Arquette
Release: 2024-10-26 06:15:30
Original
1086 people have browsed it

How to Draw a Rectangle in Python Using Pygame?

Drawing a Rectangle with Pygame

In Python, you can draw a rectangle on a Pygame display by utilizing the pygame.draw.rect function.

Syntax

The syntax for pygame.draw.rect is as follows:

pygame.draw.rect(surface, color, rect, width=0)
Copy after login

where:

  • surface is the surface on which you want to draw the rectangle.
  • color is the color of the rectangle. It can be a tuple of three integers representing RGB values (e.g., (255, 0, 0) for red) or a pygame.Color object.
  • rect is a pygame.Rect object representing the dimensions and position of the rectangle.
  • width (optional) is the width of the rectangle's border. If omitted, it defaults to 0, resulting in a filled rectangle.

Example

Here's an example of how to draw a blue rectangle in a Pygame window:

<code class="python">import pygame

# Initialize Pygame
pygame.init()

# Set up the display
DISPLAY = pygame.display.set_mode((500, 400), 0, 32)

# Create the colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)

# Fill the display with white
DISPLAY.fill(WHITE)

# Draw the rectangle
pygame.draw.rect(DISPLAY, BLUE, (200, 150, 100, 50))

# Update the display
pygame.display.update()

# Keep the window open until the user quits
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()</code>
Copy after login

This code creates a 500x400 pixel white display. It then draws a blue rectangle with coordinates (200, 150) and dimensions (100, 50).

The above is the detailed content of How to Draw a Rectangle in Python Using Pygame?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template