Implementing pygame.Rect in Python

In this module, we are going to discuss the creation of pygame.Rect objects and these objects are used for storing rectangular coordinates. The main objective of this is to store and manipulate rectangular areas.

Creating pygame.Rect object using python

The following syntax gives a description of the creation of pygame. Rect object as follows

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

This is treated as a constructor in pygame and all constructors start with a capital letter.

If we want to know the x-coordinate of the right of pygame.Rect object we can access Rect right attribute. First, let us create pygame. Rect object as follows

rect_obj=pygame.Rect(20,40,250,350)

Here we have created a rectangular object of width-250, height-350 and it is located at coordinates (top, left)=(20,40). Now to access the right attribute we use the syntax as follows

rect_object.attribute

pygame support the following attributes:

  • left,right,top,bottom.
  • centrex,centrey.
  • topleft,topright,bottomleft,bottomright.
  • midleft,midright,midtop,midbottom.

The following gives the required attribute position. now, let us take an example from the above-created object.

print(rect_obj.right)

Output:

270

We got output as 270 because the left edge is present at coordinate 20 and the rectangle width is 250 when we add both we get the position of rectangle right edge.so, now it is situated at coordinate 270.

We can change the position of the rectangle by reassigning them with new values as follows

rect_obj.attribute=new_value

When we change the attribute value all other attribute values are automatically recalculated and changes are made to the other attributes as well.

When we are changing two values i.e, mid-left that takes a tuple as input as follows

rect_obj.midleft=(left,centrey) 
rect_obj.topleft=(left,top) 
rect_obj.midtop=(centrex,top)

The following code gives a description of the attribute value changes.

import pygame
rect_obj=pygame.Rect(20,40,250,350)
print(rect_obj.left)
print(rect_obj.right)
rect_obj.left=250
print(rect_obj.left)
print(rect_obj.right)

Output:

20
270
250
500

Here as we could see when we changed the left attribute to 250 it is modified and the right attribute is also modified to 500 which is initially 20.like this we can modify the attributes of a rectangular object.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *