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

Barbara Streisand
Release: 2024-10-26 16:19:30
Original
365 people have browsed it

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>
Copy after login
  1. Initialize Pygame:
<code class="python">pygame.init()</code>
Copy after login
  1. Create a display window:
<code class="python">DISPLAY=pygame.display.set_mode((500,400),0,32)</code>
Copy after login
  1. Set colors:
<code class="python">WHITE=(255,255,255)
BLUE=(0,0,255)</code>
Copy after login
  1. Fill the display with white:
<code class="python">DISPLAY.fill(WHITE)</code>
Copy after login
  1. Draw a blue rectangle using pygame.draw.rect:
<code class="python">pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))</code>
Copy after login
  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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!