0

I was learning to create a simple Pygame window which displays a Rectangle. I watched two different videos on Youtube. One of the Youtuber used Pygame.draw.rect() to create a rectangle whereas other Youtuber used both pygame.Rect() and Pygame.draw.rect(). Both gave same result at the end. So what is the difference between these two codes??

  • Pretty much none, as per timeit(the timing module) pygame.draw.rect() is 0.97 ms slower than pygame.rect(), or atleast on my PC core i5 7200u cpu – Aryan Mar 21 '21 at 04:24
  • @AryanMishra Sorry, but this is wrong. Read the answer – Rabbid76 Mar 21 '21 at 06:41

2 Answers2

3

pygame.Rect is a class whose instances represent rectangular areas.

pygame.draw.rect is a function that draws rectangles. One of its arguments is a pygame.Rect instance representing the rectangle to draw.

They are completely different things.

user2357112
  • 260,549
  • 28
  • 431
  • 505
3

pygame.Rect creates a Rect instance to be passed into pygame.draw.rect. Consider this short snippet:

For anyone else who is reading this, first install pygame by running pip install pygame in your IDE's terminal or your default operating system's terminal.

import pygame
SCREEN = pygame.display.set_mode((300, 300))

while True:
    pygame.draw.rect(SCREEN, 'white', (30, 30, 100, 100))
    pygame.display.update()

The tuple that we passed in to pygame.draw.rect consists of (x, y, width, height):

  • x being where our rectangle will sit on the vertical axis
  • y being where our rectangle will sit on the horizontal axis
  • width being the width of our rectangle
  • height being the height of our rectangle

This is how you would use pygame.draw.rect by itself. Behind the scenes, pygame transforms this tuple into a pygame.Rect object. So you are only doing a bit more work when using pygame.Rect. For example:

pygame_rect_object = pygame.Rect(30, 30, 100, 100)
pygame.draw.rect(SCREEN, 'white', pygame_rect_object)

As you can see, creating a pygame.Rect object is the same as passing the tuple. A few advantages are readability, and you can pass it into multiple pygame.draw.rect functions without having to repeat the tuple.

Hope this has helped!!!

theProCoder
  • 390
  • 6
  • 21