Home  >  Article  >  Backend Development  >  How do I draw a rectangle in a Pygame window using Python?

How do I draw a rectangle in a Pygame window using Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 05:11:02554browse

How do I draw a rectangle in a Pygame window using Python?

How to Draw a Rectangle in Pygame

Drawing a rectangle in Python using the Pygame library is essential for many game development tasks. In this question, we'll explore the specific steps involved in drawing a rectangle for Python 3.2.

In the provided Python code:

<code class="python">import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY = pygame.display.set_mode((500, 400), 0, 32)

    WHITE = (255, 255, 255)
    BLUE = (0, 0, 255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY, BLUE, (200, 150, 100, 50))

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

if __name__ == "__main__":
    main()</code>
  1. Initialize Pygame: The pygame.init() function initializes the Pygame library.
  2. Create a Game Window: pygame.display.set_mode((500, 400), 0, 32) creates a game window with a resolution of 500x400 pixels.
  3. Fill the Window: DISPLAY.fill(WHITE) fills the window with the specified color, in this case, white.
  4. Draw a Rectangle: pygame.draw.rect(DISPLAY, BLUE, (200, 150, 100, 50)) draws a rectangle using the DISPLAY surface, the color BLUE, and the coordinates (200, 150) as the top-left corner and (100, 50) as the width and height.
  5. Game Loop: The main game loop handles events and updates the display. When the quit event is detected, pygame.quit() and sys.exit() are called to cleanly exit the game.

This code demonstrates how to draw a simple blue rectangle in a Pygame window. For more information and tutorials on using Pygame, refer to the Pygame website: www.pygame.org.

The above is the detailed content of How do I draw a rectangle in a Pygame window using Python?. 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