Pygame Tutorial – Drawing Rectangle

In this Pygame Tutorial we want to learn Drawing Rectangle in Pygame, if you are creating a game or any other kind of interactive program with Pygame, some times you will need to draw rectangles. Rectangles are useful for creating game objects, UI elements and much more. in this article we want to talk that how to draw rectangles using pygame.draw.rect() function.

 

 

 

First of all you need to import Pygame module and initialize it with pygame.init() function.

 

 

 

So before you draw a rectangle, you need to set dimensions of the Pygame display. you can do this byusing pygame.display.set_mode() function.

 

 

 

 

Now we are ready to draw rectangle, pygame.draw.rect() function takes several arguments, including display surface to draw on, color of the rectangle, position of the top left corner of rectangle and  dimensions of the rectangle. this is an example of how to draw a rectangle:

 

 

 

After drawing a rectangle, you need to update Pygame display for the changes to take effect. you can do this with pygame.display.update() function.

 

 

 

This is the complete code for this article

This code initializes Pygame and sets dimensions of the display window. after that it draws  red rectangle using pygame.draw.rect(). and finally this code enters a game loop that continually updates the display until the user closes the window.

 

 

 

 

 

 

Run the complete code and this will be the result

Pygame Tutorial - Drawing Rectangle
Pygame Tutorial – Drawing Rectangle

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×