How to Draw a Rectangle in Pygame?

Susan Sarandon
Release: 2024-10-26 00:35:28
Original
220 people have browsed it

How to Draw a Rectangle in Pygame?

Drawing Rectangles in Pygame

In game development, drawing rectangles is a fundamental skill. In Python, using the Pygame library, drawing rectangles is made straightforward.

Solution

To draw a rectangle in Pygame (3.2), follow these steps:

  1. Import the necessary Pygame modules:
<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 surface to draw the rectangle on:
<code class="python">DISPLAY = pygame.display.set_mode((500, 400), 0, 32)</code>
Copy after login
  1. Define the colors you want to use:
<code class="python">WHITE = (255, 255, 255)
BLUE = (0, 0, 255)</code>
Copy after login
  1. Fill the display surface with a background color:
<code class="python">DISPLAY.fill(WHITE)</code>
Copy after login
  1. Use the pygame.draw.rect function to draw the rectangle:
<code class="python">pygame.draw.rect(DISPLAY, BLUE, (200, 150, 100, 50))</code>
Copy after login
  1. Display the updated surface:
<code class="python">pygame.display.update()</code>
Copy after login

The pygame.draw.rect function takes the following parameters:

  • The display surface to draw the rectangle on
  • The color of the rectangle
  • A tuple of the rectangle's coordinates and dimensions

In this example, a blue rectangle with a width of 100 and a height of 50 is drawn at the coordinates (200, 150) on a white display surface.

Additional Resources

For more information on drawing rectangles with Pygame, refer to the official Pygame documentation: https://www.pygame.org/docs/ref/draw.html#pygame.draw.rect

The above is the detailed content of How to Draw a Rectangle in 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!