Pygame Rect, what are the arguments?
Asked Answered
C

2

6

I know this may sound stupid, but the pygame documentation on their website says that it is:

x = pygame.Rect(left,top,width,height)

However, in my program, I cannot figure out if that is true, or if the arguments are actually two sets of coordinates. I'm not nearly experienced to find out by looking through the pygame source code.

Crowl answered 4/1, 2015 at 21:35 Comment(0)
L
6

Both of them work:

class pygame.Rect
    pygame object for storing rectangular coordinates
    Rect(left, top, width, height) -> Rect
    Rect((left, top), (width, height)) -> Rect
    Rect(object) -> Rect

So, if you have coordinates (x1, y1) and (x2, y2), both of the following would work:

pygame.Rect(x1, y1, x2-x1, y2-y1)
pygame.Rect((x1, y1), (x2-x1, y2-y1))
Licha answered 4/1, 2015 at 21:37 Comment(2)
but could I also put Rect(x1,y1,x2,y2)? as in two sets of coordinatesCrowl
@AndrewLalis No, it would be Rect(x1, y1, x2-x1, y2-y1). The second pair of arguments is the width and the height.Licha
S
0

To help make things more clear. When you make an instance of a Rect, aka a Rect object. You specify it's top left corner position. Then specify it's width, which extends to the right of that position. Next it's height which extends down from that point.

If you want to confirm the 4 corners of the Rect object you would call those variables. Ex. Rect.topleft, Rect.topright, Rect.bottomleft, Rect.bottomright. All you would need to do is call them inside of a print function to see them on the console.

# Example
import pygame

# First I'll make a Rect whose topleft corner is in the coordinate (0, 0) with a width=10 and height=10
test_rect = pygame.Rect(0, 0, 10, 30)

# Next print the four corners to the console
print(test_rect.topleft)
print(test_rect.topright)
print(test_rect.bottomleft)
print(test_rect.bottomright)

This should result in the four positions:

(0, 0)
(10, 0)
(0, 30)
(10, 30)

Because of how pygame plots on the screen once you get to the graphics portion it important to note that it's x accends from left to right, which is normal.

However, it y coordinates ascend from top to bottom, which would normally be negative values for standard graph plotting.

Sirotek answered 6/8, 2023 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.