How to draw rectangle in Pygame?

How to draw rectangle in Pygame?

Drawing a rectangle in pygame is straightforward using the pygame.draw.rect() method. Here's a step-by-step guide on how to draw a rectangle in a Pygame window:

Step 1: Install Pygame

If you haven't already, you need to install pygame:

pip install pygame 

Step 2: Basic Pygame Setup

Set up a basic pygame window:

import pygame # Initialize pygame pygame.init() # Set display dimensions WIDTH, HEIGHT = 800, 600 # Colors (R, G, B) WHITE = (255, 255, 255) RED = (255, 0, 0) # Create the display surface screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Set the title of the window pygame.display.set_caption('Rectangle Drawing') 

Step 3: Drawing a Rectangle

Now, you can use pygame.draw.rect() to draw a rectangle on your display surface:

running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Fill the background with white color screen.fill(WHITE) # Draw a rectangle: pygame.draw.rect(surface, color, (x, y, width, height)) pygame.draw.rect(screen, RED, (350, 250, 100, 100)) # Update the display pygame.display.flip() pygame.quit() 

In the above code:

  • screen is the surface on which we're drawing.
  • RED is the color of the rectangle.
  • (350, 250, 100, 100) is a tuple where:
    • 350 and 250 are the x and y coordinates of the top-left corner of the rectangle.
    • 100 is the width of the rectangle.
    • 100 is the height of the rectangle.

When you run the complete code, you should see a Pygame window with a red rectangle drawn in the middle. Adjust the parameters as necessary to change the rectangle's position, size, and color.


More Tags

automake pandas-to-sql multi-level etl product spp topshelf has-many terraform-provider-azure permutation

More Programming Guides

Other Guides

More Programming Examples