cjor530
cjor530

Reputation: 67

Is it possible to create a new, assignable attribute for pygame.Rect objects?

I want to be able to set the center coordinate of a Rect object equal to a tuple the same way one would go about setting any of the corner coordinates or the coordinates for the midpoints of any of the sides equal to a tuple, which would be to assign the value to the appropriate Rect attribute using code that looks something like this:

a_rectangle = pygame.Rect(ValueForX, ValueForY, width, height) #creates Rect object with top-left corner at (ValueForX, ValueForY)
a_rectangle.topleft = (DifferentX, DifferentY) #sets top-left corner coordinates to (DifferentX, DifferentY)

To my knowledge, there is no pre-existing attribute for the center of a Rect object--see here--so instead of using the above code, I have to use code that looks something like this:

a_rectangle = pygame.Rect(ValueForX, ValueForY, width, height) #creates Rect object with top-left corner at (ValueForX, ValueForY)
a_rectangle.centerx = Xvalue #sets x-value for the center coordinate to Xvalue
a_rectangle.centery = Yvalue #sets y-value for the center coordinate to Yvalue

Since, depending on the program, it's not exactly as simple as picking a few numbers out of a hat and being done with it, I'd rather be able to use fewer lines of code so that I don't end up with a mess on my hands.

Does anyone know if it's possible to create a new attribute for the center coordinate of a Rect object, and, if so, how to do it? Thanks!

Upvotes: 1

Views: 314

Answers (1)

furas
furas

Reputation: 142774

Rect has center

a_rectangle.center = (X, Y)

To center element in window or center text on button

a_rectangle.center = window.center
text.center = button.center

See official documentation: Rect

x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h

EDIT:

If you need new functions or variables in Rect then you can create own class based on Rect and add own functions. And later use your class instead of Rect

import math
import pygame

class MyRect(pygame.Rect):

    @property    
    def area(self):
        return self.width * self.height

    @area.setter
    def area(self, value):
        self.width = self.height = int(math.sqrt(value))

a_rectangle = MyRect(0, 0, 10, 10) 
print( a_rectangle.center )

print( a_rectangle.area ) # 100
print( a_rectangle.width, a_rectangle.height ) # 10, 10

a_rectangle.area = 144

print( a_rectangle.area ) # 144
print( a_rectangle.width, a_rectangle.height ) # 12, 12

Upvotes: 2

Related Questions