Home >Backend Development >Python Tutorial >How to Draw Rectangles in Pygame Using `pygame.draw.rect`?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 16:19:30477browse

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:
<code class="python">import pygame, sys
from pygame.locals import *</code>
  1. Initialize Pygame:
<code class="python">pygame.init()</code>
  1. Create a display window:
<code class="python">DISPLAY=pygame.display.set_mode((500,400),0,32)</code>
  1. Set colors:
<code class="python">WHITE=(255,255,255)
BLUE=(0,0,255)</code>
  1. Fill the display with white:
<code class="python">DISPLAY.fill(WHITE)</code>
  1. Draw a blue rectangle using pygame.draw.rect:
<code class="python">pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))</code>
  1. Start the game loop:
<code class="python">while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    # Update the display
    pygame.display.update()</code>

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.

The above is the detailed content of How to Draw Rectangles in Pygame Using `pygame.draw.rect`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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